babylon.viewer.max.js 5.2 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613836148361583616836178361883619836208362183622836238362483625836268362783628836298363083631836328363383634836358363683637836388363983640836418364283643836448364583646836478364883649836508365183652836538365483655836568365783658836598366083661836628366383664836658366683667836688366983670836718367283673836748367583676836778367883679836808368183682836838368483685836868368783688836898369083691836928369383694836958369683697836988369983700837018370283703837048370583706837078370883709837108371183712837138371483715837168371783718837198372083721837228372383724837258372683727837288372983730837318373283733837348373583736837378373883739837408374183742837438374483745837468374783748837498375083751837528375383754837558375683757837588375983760837618376283763837648376583766837678376883769837708377183772837738377483775837768377783778837798378083781837828378383784837858378683787837888378983790837918379283793837948379583796837978379883799838008380183802838038380483805838068380783808838098381083811838128381383814838158381683817838188381983820838218382283823838248382583826838278382883829838308383183832838338383483835838368383783838838398384083841838428384383844838458384683847838488384983850838518385283853838548385583856838578385883859838608386183862838638386483865838668386783868838698387083871838728387383874838758387683877838788387983880838818388283883838848388583886838878388883889838908389183892838938389483895838968389783898838998390083901839028390383904839058390683907839088390983910839118391283913839148391583916839178391883919839208392183922839238392483925839268392783928839298393083931839328393383934839358393683937839388393983940839418394283943839448394583946839478394883949839508395183952839538395483955839568395783958839598396083961839628396383964839658396683967839688396983970839718397283973839748397583976839778397883979839808398183982839838398483985839868398783988839898399083991839928399383994839958399683997839988399984000840018400284003840048400584006840078400884009840108401184012840138401484015840168401784018840198402084021840228402384024840258402684027840288402984030840318403284033840348403584036840378403884039840408404184042840438404484045840468404784048840498405084051840528405384054840558405684057840588405984060840618406284063840648406584066840678406884069840708407184072840738407484075840768407784078840798408084081840828408384084840858408684087840888408984090840918409284093840948409584096840978409884099841008410184102841038410484105841068410784108841098411084111841128411384114841158411684117841188411984120841218412284123841248412584126841278412884129841308413184132841338413484135841368413784138841398414084141841428414384144841458414684147841488414984150841518415284153841548415584156841578415884159841608416184162841638416484165841668416784168841698417084171841728417384174841758417684177841788417984180841818418284183841848418584186841878418884189841908419184192841938419484195841968419784198841998420084201842028420384204842058420684207842088420984210842118421284213842148421584216842178421884219842208422184222842238422484225842268422784228842298423084231842328423384234842358423684237842388423984240842418424284243842448424584246842478424884249842508425184252842538425484255842568425784258842598426084261842628426384264842658426684267842688426984270842718427284273842748427584276842778427884279842808428184282842838428484285842868428784288842898429084291842928429384294842958429684297842988429984300843018430284303843048430584306843078430884309843108431184312843138431484315843168431784318843198432084321843228432384324843258432684327843288432984330843318433284333843348433584336843378433884339843408434184342843438434484345843468434784348843498435084351843528435384354843558435684357843588435984360843618436284363843648436584366843678436884369843708437184372843738437484375843768437784378843798438084381843828438384384843858438684387843888438984390843918439284393843948439584396843978439884399844008440184402844038440484405844068440784408844098441084411844128441384414844158441684417844188441984420844218442284423844248442584426844278442884429844308443184432844338443484435844368443784438844398444084441844428444384444844458444684447844488444984450844518445284453844548445584456844578445884459844608446184462844638446484465844668446784468844698447084471844728447384474844758447684477844788447984480844818448284483844848448584486844878448884489844908449184492844938449484495844968449784498844998450084501845028450384504845058450684507845088450984510845118451284513845148451584516845178451884519845208452184522845238452484525845268452784528845298453084531845328453384534845358453684537845388453984540845418454284543845448454584546845478454884549845508455184552845538455484555845568455784558845598456084561845628456384564845658456684567845688456984570845718457284573845748457584576845778457884579845808458184582845838458484585845868458784588845898459084591845928459384594845958459684597845988459984600846018460284603846048460584606846078460884609846108461184612846138461484615846168461784618846198462084621846228462384624846258462684627846288462984630846318463284633846348463584636846378463884639846408464184642846438464484645846468464784648846498465084651846528465384654846558465684657846588465984660846618466284663846648466584666846678466884669846708467184672846738467484675846768467784678846798468084681846828468384684846858468684687846888468984690846918469284693846948469584696846978469884699847008470184702847038470484705847068470784708847098471084711847128471384714847158471684717847188471984720847218472284723847248472584726847278472884729847308473184732847338473484735847368473784738847398474084741847428474384744847458474684747847488474984750847518475284753847548475584756847578475884759847608476184762847638476484765847668476784768847698477084771847728477384774847758477684777847788477984780847818478284783847848478584786847878478884789847908479184792847938479484795847968479784798847998480084801848028480384804848058480684807848088480984810848118481284813848148481584816848178481884819848208482184822848238482484825848268482784828848298483084831848328483384834848358483684837848388483984840848418484284843848448484584846848478484884849848508485184852848538485484855848568485784858848598486084861848628486384864848658486684867848688486984870848718487284873848748487584876848778487884879848808488184882848838488484885848868488784888848898489084891848928489384894848958489684897848988489984900849018490284903849048490584906849078490884909849108491184912849138491484915849168491784918849198492084921849228492384924849258492684927849288492984930849318493284933849348493584936849378493884939849408494184942849438494484945849468494784948849498495084951849528495384954849558495684957849588495984960849618496284963849648496584966849678496884969849708497184972849738497484975849768497784978849798498084981849828498384984849858498684987849888498984990849918499284993849948499584996849978499884999850008500185002850038500485005850068500785008850098501085011850128501385014850158501685017850188501985020850218502285023850248502585026850278502885029850308503185032850338503485035850368503785038850398504085041850428504385044850458504685047850488504985050850518505285053850548505585056850578505885059850608506185062850638506485065850668506785068850698507085071850728507385074850758507685077850788507985080850818508285083850848508585086850878508885089850908509185092850938509485095850968509785098850998510085101851028510385104851058510685107851088510985110851118511285113851148511585116851178511885119851208512185122851238512485125851268512785128851298513085131851328513385134851358513685137851388513985140851418514285143851448514585146851478514885149851508515185152851538515485155851568515785158851598516085161851628516385164851658516685167851688516985170851718517285173851748517585176851778517885179851808518185182851838518485185851868518785188851898519085191851928519385194851958519685197851988519985200852018520285203852048520585206852078520885209852108521185212852138521485215852168521785218852198522085221852228522385224852258522685227852288522985230852318523285233852348523585236852378523885239852408524185242852438524485245852468524785248852498525085251852528525385254852558525685257852588525985260852618526285263852648526585266852678526885269852708527185272852738527485275852768527785278852798528085281852828528385284852858528685287852888528985290852918529285293852948529585296852978529885299853008530185302853038530485305853068530785308853098531085311853128531385314853158531685317853188531985320853218532285323853248532585326853278532885329853308533185332853338533485335853368533785338853398534085341853428534385344853458534685347853488534985350853518535285353853548535585356853578535885359853608536185362853638536485365853668536785368853698537085371853728537385374853758537685377853788537985380853818538285383853848538585386853878538885389853908539185392853938539485395853968539785398853998540085401854028540385404854058540685407854088540985410854118541285413854148541585416854178541885419854208542185422854238542485425854268542785428854298543085431854328543385434854358543685437854388543985440854418544285443854448544585446854478544885449854508545185452854538545485455854568545785458854598546085461854628546385464854658546685467854688546985470854718547285473854748547585476854778547885479854808548185482854838548485485854868548785488854898549085491854928549385494854958549685497854988549985500855018550285503855048550585506855078550885509855108551185512855138551485515855168551785518855198552085521855228552385524855258552685527855288552985530855318553285533855348553585536855378553885539855408554185542855438554485545855468554785548855498555085551855528555385554855558555685557855588555985560855618556285563855648556585566855678556885569855708557185572855738557485575855768557785578855798558085581855828558385584855858558685587855888558985590855918559285593855948559585596855978559885599856008560185602856038560485605856068560785608856098561085611856128561385614856158561685617856188561985620856218562285623856248562585626856278562885629856308563185632856338563485635856368563785638856398564085641856428564385644856458564685647856488564985650856518565285653856548565585656856578565885659856608566185662856638566485665856668566785668856698567085671856728567385674856758567685677856788567985680856818568285683856848568585686856878568885689856908569185692856938569485695856968569785698856998570085701857028570385704857058570685707857088570985710857118571285713857148571585716857178571885719857208572185722857238572485725857268572785728857298573085731857328573385734857358573685737857388573985740857418574285743857448574585746857478574885749857508575185752857538575485755857568575785758857598576085761857628576385764857658576685767857688576985770857718577285773857748577585776857778577885779857808578185782857838578485785857868578785788857898579085791857928579385794857958579685797857988579985800858018580285803858048580585806858078580885809858108581185812858138581485815858168581785818858198582085821858228582385824858258582685827858288582985830858318583285833858348583585836858378583885839858408584185842858438584485845858468584785848858498585085851858528585385854858558585685857858588585985860858618586285863858648586585866858678586885869858708587185872858738587485875858768587785878858798588085881858828588385884858858588685887858888588985890858918589285893858948589585896858978589885899859008590185902859038590485905859068590785908859098591085911859128591385914859158591685917859188591985920859218592285923859248592585926859278592885929859308593185932859338593485935859368593785938859398594085941859428594385944859458594685947859488594985950859518595285953859548595585956859578595885959859608596185962859638596485965859668596785968859698597085971859728597385974859758597685977859788597985980859818598285983859848598585986859878598885989859908599185992859938599485995859968599785998859998600086001860028600386004860058600686007860088600986010860118601286013860148601586016860178601886019860208602186022860238602486025860268602786028860298603086031860328603386034860358603686037860388603986040860418604286043860448604586046860478604886049860508605186052860538605486055860568605786058860598606086061860628606386064860658606686067860688606986070860718607286073860748607586076860778607886079860808608186082860838608486085860868608786088860898609086091860928609386094860958609686097860988609986100861018610286103861048610586106861078610886109861108611186112861138611486115861168611786118861198612086121861228612386124861258612686127861288612986130861318613286133861348613586136861378613886139861408614186142861438614486145861468614786148861498615086151861528615386154861558615686157861588615986160861618616286163861648616586166861678616886169861708617186172861738617486175861768617786178861798618086181861828618386184861858618686187861888618986190861918619286193861948619586196861978619886199862008620186202862038620486205862068620786208862098621086211862128621386214862158621686217862188621986220862218622286223862248622586226862278622886229862308623186232862338623486235862368623786238862398624086241862428624386244862458624686247862488624986250862518625286253862548625586256862578625886259862608626186262862638626486265862668626786268862698627086271862728627386274862758627686277862788627986280862818628286283862848628586286862878628886289862908629186292862938629486295862968629786298862998630086301863028630386304863058630686307863088630986310863118631286313863148631586316863178631886319863208632186322863238632486325863268632786328863298633086331863328633386334863358633686337863388633986340863418634286343863448634586346863478634886349863508635186352863538635486355863568635786358863598636086361863628636386364863658636686367863688636986370863718637286373863748637586376863778637886379863808638186382863838638486385863868638786388863898639086391863928639386394863958639686397863988639986400864018640286403864048640586406864078640886409864108641186412864138641486415864168641786418864198642086421864228642386424864258642686427864288642986430864318643286433864348643586436864378643886439864408644186442864438644486445864468644786448864498645086451864528645386454864558645686457864588645986460864618646286463864648646586466864678646886469864708647186472864738647486475864768647786478864798648086481864828648386484864858648686487864888648986490864918649286493864948649586496864978649886499865008650186502865038650486505865068650786508865098651086511865128651386514865158651686517865188651986520865218652286523865248652586526865278652886529865308653186532865338653486535865368653786538865398654086541865428654386544865458654686547865488654986550865518655286553865548655586556865578655886559865608656186562865638656486565865668656786568865698657086571865728657386574865758657686577865788657986580865818658286583865848658586586865878658886589865908659186592865938659486595865968659786598865998660086601866028660386604866058660686607866088660986610866118661286613866148661586616866178661886619866208662186622866238662486625866268662786628866298663086631866328663386634866358663686637866388663986640866418664286643866448664586646866478664886649866508665186652866538665486655866568665786658866598666086661866628666386664866658666686667866688666986670866718667286673866748667586676866778667886679866808668186682866838668486685866868668786688866898669086691866928669386694866958669686697866988669986700867018670286703867048670586706867078670886709867108671186712867138671486715867168671786718867198672086721867228672386724867258672686727867288672986730867318673286733867348673586736867378673886739867408674186742867438674486745867468674786748867498675086751867528675386754867558675686757867588675986760867618676286763867648676586766867678676886769867708677186772867738677486775867768677786778867798678086781867828678386784867858678686787867888678986790867918679286793867948679586796867978679886799868008680186802868038680486805868068680786808868098681086811868128681386814868158681686817868188681986820868218682286823868248682586826868278682886829868308683186832868338683486835868368683786838868398684086841868428684386844868458684686847868488684986850868518685286853868548685586856868578685886859868608686186862868638686486865868668686786868868698687086871868728687386874868758687686877868788687986880868818688286883868848688586886868878688886889868908689186892868938689486895868968689786898868998690086901869028690386904869058690686907869088690986910869118691286913869148691586916869178691886919869208692186922869238692486925869268692786928869298693086931869328693386934869358693686937869388693986940869418694286943869448694586946869478694886949869508695186952869538695486955869568695786958869598696086961869628696386964869658696686967869688696986970869718697286973869748697586976869778697886979869808698186982869838698486985869868698786988869898699086991869928699386994869958699686997869988699987000870018700287003870048700587006870078700887009870108701187012870138701487015870168701787018870198702087021870228702387024870258702687027870288702987030870318703287033870348703587036870378703887039870408704187042870438704487045870468704787048870498705087051870528705387054870558705687057870588705987060870618706287063870648706587066870678706887069870708707187072870738707487075870768707787078870798708087081870828708387084870858708687087870888708987090870918709287093870948709587096870978709887099871008710187102871038710487105871068710787108871098711087111871128711387114871158711687117871188711987120871218712287123871248712587126871278712887129871308713187132871338713487135871368713787138871398714087141871428714387144871458714687147871488714987150871518715287153871548715587156871578715887159871608716187162871638716487165871668716787168871698717087171871728717387174871758717687177871788717987180871818718287183871848718587186871878718887189871908719187192871938719487195871968719787198871998720087201872028720387204872058720687207872088720987210872118721287213872148721587216872178721887219872208722187222872238722487225872268722787228872298723087231872328723387234872358723687237872388723987240872418724287243872448724587246872478724887249872508725187252872538725487255872568725787258872598726087261872628726387264872658726687267872688726987270872718727287273872748727587276872778727887279872808728187282872838728487285872868728787288872898729087291872928729387294872958729687297872988729987300873018730287303873048730587306873078730887309873108731187312873138731487315873168731787318873198732087321873228732387324873258732687327873288732987330873318733287333873348733587336873378733887339873408734187342873438734487345873468734787348873498735087351873528735387354873558735687357873588735987360873618736287363873648736587366873678736887369873708737187372873738737487375873768737787378873798738087381873828738387384873858738687387873888738987390873918739287393873948739587396873978739887399874008740187402874038740487405874068740787408874098741087411874128741387414874158741687417874188741987420874218742287423874248742587426874278742887429874308743187432874338743487435874368743787438874398744087441874428744387444874458744687447874488744987450874518745287453874548745587456874578745887459874608746187462874638746487465874668746787468874698747087471874728747387474874758747687477874788747987480874818748287483874848748587486874878748887489874908749187492874938749487495874968749787498874998750087501875028750387504875058750687507875088750987510875118751287513875148751587516875178751887519875208752187522875238752487525875268752787528875298753087531875328753387534875358753687537875388753987540875418754287543875448754587546875478754887549875508755187552875538755487555875568755787558875598756087561875628756387564875658756687567875688756987570875718757287573875748757587576875778757887579875808758187582875838758487585875868758787588875898759087591875928759387594875958759687597875988759987600876018760287603876048760587606876078760887609876108761187612876138761487615876168761787618876198762087621876228762387624876258762687627876288762987630876318763287633876348763587636876378763887639876408764187642876438764487645876468764787648876498765087651876528765387654876558765687657876588765987660876618766287663876648766587666876678766887669876708767187672876738767487675876768767787678876798768087681876828768387684876858768687687876888768987690876918769287693876948769587696876978769887699877008770187702877038770487705877068770787708877098771087711877128771387714877158771687717877188771987720877218772287723877248772587726877278772887729877308773187732877338773487735877368773787738877398774087741877428774387744877458774687747877488774987750877518775287753877548775587756877578775887759877608776187762877638776487765877668776787768877698777087771877728777387774877758777687777877788777987780877818778287783877848778587786877878778887789877908779187792877938779487795877968779787798877998780087801878028780387804878058780687807878088780987810878118781287813878148781587816878178781887819878208782187822878238782487825878268782787828878298783087831878328783387834878358783687837878388783987840878418784287843878448784587846878478784887849878508785187852878538785487855878568785787858878598786087861878628786387864878658786687867878688786987870878718787287873878748787587876878778787887879878808788187882878838788487885878868788787888878898789087891878928789387894878958789687897878988789987900879018790287903879048790587906879078790887909879108791187912879138791487915879168791787918879198792087921879228792387924879258792687927879288792987930879318793287933879348793587936879378793887939879408794187942879438794487945879468794787948879498795087951879528795387954879558795687957879588795987960879618796287963879648796587966879678796887969879708797187972879738797487975879768797787978879798798087981879828798387984879858798687987879888798987990879918799287993879948799587996879978799887999880008800188002880038800488005880068800788008880098801088011880128801388014880158801688017880188801988020880218802288023880248802588026880278802888029880308803188032880338803488035880368803788038880398804088041880428804388044880458804688047880488804988050880518805288053880548805588056880578805888059880608806188062880638806488065880668806788068880698807088071880728807388074880758807688077880788807988080880818808288083880848808588086880878808888089880908809188092880938809488095880968809788098880998810088101881028810388104881058810688107881088810988110881118811288113881148811588116881178811888119881208812188122881238812488125881268812788128881298813088131881328813388134881358813688137881388813988140881418814288143881448814588146881478814888149881508815188152881538815488155881568815788158881598816088161881628816388164881658816688167881688816988170881718817288173881748817588176881778817888179881808818188182881838818488185881868818788188881898819088191881928819388194881958819688197881988819988200882018820288203882048820588206882078820888209882108821188212882138821488215882168821788218882198822088221882228822388224882258822688227882288822988230882318823288233882348823588236882378823888239882408824188242882438824488245882468824788248882498825088251882528825388254882558825688257882588825988260882618826288263882648826588266882678826888269882708827188272882738827488275882768827788278882798828088281882828828388284882858828688287882888828988290882918829288293882948829588296882978829888299883008830188302883038830488305883068830788308883098831088311883128831388314883158831688317883188831988320883218832288323883248832588326883278832888329883308833188332883338833488335883368833788338883398834088341883428834388344883458834688347883488834988350883518835288353883548835588356883578835888359883608836188362883638836488365883668836788368883698837088371883728837388374883758837688377883788837988380883818838288383883848838588386883878838888389883908839188392883938839488395883968839788398883998840088401884028840388404884058840688407884088840988410884118841288413884148841588416884178841888419884208842188422884238842488425884268842788428884298843088431884328843388434884358843688437884388843988440884418844288443884448844588446884478844888449884508845188452884538845488455884568845788458884598846088461884628846388464884658846688467884688846988470884718847288473884748847588476884778847888479884808848188482884838848488485884868848788488884898849088491884928849388494884958849688497884988849988500885018850288503885048850588506885078850888509885108851188512885138851488515885168851788518885198852088521885228852388524885258852688527885288852988530885318853288533885348853588536885378853888539885408854188542885438854488545885468854788548885498855088551885528855388554885558855688557885588855988560885618856288563885648856588566885678856888569885708857188572885738857488575885768857788578885798858088581885828858388584885858858688587885888858988590885918859288593885948859588596885978859888599886008860188602886038860488605886068860788608886098861088611886128861388614886158861688617886188861988620886218862288623886248862588626886278862888629886308863188632886338863488635886368863788638886398864088641886428864388644886458864688647886488864988650886518865288653886548865588656886578865888659886608866188662886638866488665886668866788668886698867088671886728867388674886758867688677886788867988680886818868288683886848868588686886878868888689886908869188692886938869488695886968869788698886998870088701887028870388704887058870688707887088870988710887118871288713887148871588716887178871888719887208872188722887238872488725887268872788728887298873088731887328873388734887358873688737887388873988740887418874288743887448874588746887478874888749887508875188752887538875488755887568875788758887598876088761887628876388764887658876688767887688876988770887718877288773887748877588776887778877888779887808878188782887838878488785887868878788788887898879088791887928879388794887958879688797887988879988800888018880288803888048880588806888078880888809888108881188812888138881488815888168881788818888198882088821888228882388824888258882688827888288882988830888318883288833888348883588836888378883888839888408884188842888438884488845888468884788848888498885088851888528885388854888558885688857888588885988860888618886288863888648886588866888678886888869888708887188872888738887488875888768887788878888798888088881888828888388884888858888688887888888888988890888918889288893888948889588896888978889888899889008890188902889038890488905889068890788908889098891088911889128891388914889158891688917889188891988920889218892288923889248892588926889278892888929889308893188932889338893488935889368893788938889398894088941889428894388944889458894688947889488894988950889518895288953889548895588956889578895888959889608896188962889638896488965889668896788968889698897088971889728897388974889758897688977889788897988980889818898288983889848898588986889878898888989889908899188992889938899488995889968899788998889998900089001890028900389004890058900689007890088900989010890118901289013890148901589016890178901889019890208902189022890238902489025890268902789028890298903089031890328903389034890358903689037890388903989040890418904289043890448904589046890478904889049890508905189052890538905489055890568905789058890598906089061890628906389064890658906689067890688906989070890718907289073890748907589076890778907889079890808908189082890838908489085890868908789088890898909089091890928909389094890958909689097890988909989100891018910289103891048910589106891078910889109891108911189112891138911489115891168911789118891198912089121891228912389124891258912689127891288912989130891318913289133891348913589136891378913889139891408914189142891438914489145891468914789148891498915089151891528915389154891558915689157891588915989160891618916289163891648916589166891678916889169891708917189172891738917489175891768917789178891798918089181891828918389184891858918689187891888918989190891918919289193891948919589196891978919889199892008920189202892038920489205892068920789208892098921089211892128921389214892158921689217892188921989220892218922289223892248922589226892278922889229892308923189232892338923489235892368923789238892398924089241892428924389244892458924689247892488924989250892518925289253892548925589256892578925889259892608926189262892638926489265892668926789268892698927089271892728927389274892758927689277892788927989280892818928289283892848928589286892878928889289892908929189292892938929489295892968929789298892998930089301893028930389304893058930689307893088930989310893118931289313893148931589316893178931889319893208932189322893238932489325893268932789328893298933089331893328933389334893358933689337893388933989340893418934289343893448934589346893478934889349893508935189352893538935489355893568935789358893598936089361893628936389364893658936689367893688936989370893718937289373893748937589376893778937889379893808938189382893838938489385893868938789388893898939089391893928939389394893958939689397893988939989400894018940289403894048940589406894078940889409894108941189412894138941489415894168941789418894198942089421894228942389424894258942689427894288942989430894318943289433894348943589436894378943889439894408944189442894438944489445894468944789448894498945089451894528945389454894558945689457894588945989460894618946289463894648946589466894678946889469894708947189472894738947489475894768947789478894798948089481894828948389484894858948689487894888948989490894918949289493894948949589496894978949889499895008950189502895038950489505895068950789508895098951089511895128951389514895158951689517895188951989520895218952289523895248952589526895278952889529895308953189532895338953489535895368953789538895398954089541895428954389544895458954689547895488954989550895518955289553895548955589556895578955889559895608956189562895638956489565895668956789568895698957089571895728957389574895758957689577895788957989580895818958289583895848958589586895878958889589895908959189592895938959489595895968959789598895998960089601896028960389604896058960689607896088960989610896118961289613896148961589616896178961889619896208962189622896238962489625896268962789628896298963089631896328963389634896358963689637896388963989640896418964289643896448964589646896478964889649896508965189652896538965489655896568965789658896598966089661896628966389664896658966689667896688966989670896718967289673896748967589676896778967889679896808968189682896838968489685896868968789688896898969089691896928969389694896958969689697896988969989700897018970289703897048970589706897078970889709897108971189712897138971489715897168971789718897198972089721897228972389724897258972689727897288972989730897318973289733897348973589736897378973889739897408974189742897438974489745897468974789748897498975089751897528975389754897558975689757897588975989760897618976289763897648976589766897678976889769897708977189772897738977489775897768977789778897798978089781897828978389784897858978689787897888978989790897918979289793897948979589796897978979889799898008980189802898038980489805898068980789808898098981089811898128981389814898158981689817898188981989820898218982289823898248982589826898278982889829898308983189832898338983489835898368983789838898398984089841898428984389844898458984689847898488984989850898518985289853898548985589856898578985889859898608986189862898638986489865898668986789868898698987089871898728987389874898758987689877898788987989880898818988289883898848988589886898878988889889898908989189892898938989489895898968989789898898998990089901899028990389904899058990689907899088990989910899118991289913899148991589916899178991889919899208992189922899238992489925899268992789928899298993089931899328993389934899358993689937899388993989940899418994289943899448994589946899478994889949899508995189952899538995489955899568995789958899598996089961899628996389964899658996689967899688996989970899718997289973899748997589976899778997889979899808998189982899838998489985899868998789988899898999089991899928999389994899958999689997899988999990000900019000290003900049000590006900079000890009900109001190012900139001490015900169001790018900199002090021900229002390024900259002690027900289002990030900319003290033900349003590036900379003890039900409004190042900439004490045900469004790048900499005090051900529005390054900559005690057900589005990060900619006290063900649006590066900679006890069900709007190072900739007490075900769007790078900799008090081900829008390084900859008690087900889008990090900919009290093900949009590096900979009890099901009010190102901039010490105901069010790108901099011090111901129011390114901159011690117901189011990120901219012290123901249012590126901279012890129901309013190132901339013490135901369013790138901399014090141901429014390144901459014690147901489014990150901519015290153901549015590156901579015890159901609016190162901639016490165901669016790168901699017090171901729017390174901759017690177901789017990180901819018290183901849018590186901879018890189901909019190192901939019490195901969019790198901999020090201902029020390204902059020690207902089020990210902119021290213902149021590216902179021890219902209022190222902239022490225902269022790228902299023090231902329023390234902359023690237902389023990240902419024290243902449024590246902479024890249902509025190252902539025490255902569025790258902599026090261902629026390264902659026690267902689026990270902719027290273902749027590276902779027890279902809028190282902839028490285902869028790288902899029090291902929029390294902959029690297902989029990300903019030290303903049030590306903079030890309903109031190312903139031490315903169031790318903199032090321903229032390324903259032690327903289032990330903319033290333903349033590336903379033890339903409034190342903439034490345903469034790348903499035090351903529035390354903559035690357903589035990360903619036290363903649036590366903679036890369903709037190372903739037490375903769037790378903799038090381903829038390384903859038690387903889038990390903919039290393903949039590396903979039890399904009040190402904039040490405904069040790408904099041090411904129041390414904159041690417904189041990420904219042290423904249042590426904279042890429904309043190432904339043490435904369043790438904399044090441904429044390444904459044690447904489044990450904519045290453904549045590456904579045890459904609046190462904639046490465904669046790468904699047090471904729047390474904759047690477904789047990480904819048290483904849048590486904879048890489904909049190492904939049490495904969049790498904999050090501905029050390504905059050690507905089050990510905119051290513905149051590516905179051890519905209052190522905239052490525905269052790528905299053090531905329053390534905359053690537905389053990540905419054290543905449054590546905479054890549905509055190552905539055490555905569055790558905599056090561905629056390564905659056690567905689056990570905719057290573905749057590576905779057890579905809058190582905839058490585905869058790588905899059090591905929059390594905959059690597905989059990600906019060290603906049060590606906079060890609906109061190612906139061490615906169061790618906199062090621906229062390624906259062690627906289062990630906319063290633906349063590636906379063890639906409064190642906439064490645906469064790648906499065090651906529065390654906559065690657906589065990660906619066290663906649066590666906679066890669906709067190672906739067490675906769067790678906799068090681906829068390684906859068690687906889068990690906919069290693906949069590696906979069890699907009070190702907039070490705907069070790708907099071090711907129071390714907159071690717907189071990720907219072290723907249072590726907279072890729907309073190732907339073490735907369073790738907399074090741907429074390744907459074690747907489074990750907519075290753907549075590756907579075890759907609076190762907639076490765907669076790768907699077090771907729077390774907759077690777907789077990780907819078290783907849078590786907879078890789907909079190792907939079490795907969079790798907999080090801908029080390804908059080690807908089080990810908119081290813908149081590816908179081890819908209082190822908239082490825908269082790828908299083090831908329083390834908359083690837908389083990840908419084290843908449084590846908479084890849908509085190852908539085490855908569085790858908599086090861908629086390864908659086690867908689086990870908719087290873908749087590876908779087890879908809088190882908839088490885908869088790888908899089090891908929089390894908959089690897908989089990900909019090290903909049090590906909079090890909909109091190912909139091490915909169091790918909199092090921909229092390924909259092690927909289092990930909319093290933909349093590936909379093890939909409094190942909439094490945909469094790948909499095090951909529095390954909559095690957909589095990960909619096290963909649096590966909679096890969909709097190972909739097490975909769097790978909799098090981909829098390984909859098690987909889098990990909919099290993909949099590996909979099890999910009100191002910039100491005910069100791008910099101091011910129101391014910159101691017910189101991020910219102291023910249102591026910279102891029910309103191032910339103491035910369103791038910399104091041910429104391044910459104691047910489104991050910519105291053910549105591056910579105891059910609106191062910639106491065910669106791068910699107091071910729107391074910759107691077910789107991080910819108291083910849108591086910879108891089910909109191092910939109491095910969109791098910999110091101911029110391104911059110691107911089110991110911119111291113911149111591116911179111891119911209112191122911239112491125911269112791128911299113091131911329113391134911359113691137911389113991140911419114291143911449114591146911479114891149911509115191152911539115491155911569115791158911599116091161911629116391164911659116691167911689116991170911719117291173911749117591176911779117891179911809118191182911839118491185911869118791188911899119091191911929119391194911959119691197911989119991200912019120291203912049120591206912079120891209912109121191212912139121491215912169121791218912199122091221912229122391224912259122691227912289122991230912319123291233912349123591236912379123891239912409124191242912439124491245912469124791248912499125091251912529125391254912559125691257912589125991260912619126291263912649126591266912679126891269912709127191272912739127491275912769127791278912799128091281912829128391284912859128691287912889128991290912919129291293912949129591296912979129891299913009130191302913039130491305913069130791308913099131091311913129131391314913159131691317913189131991320913219132291323913249132591326913279132891329913309133191332913339133491335913369133791338913399134091341913429134391344913459134691347913489134991350913519135291353913549135591356913579135891359913609136191362913639136491365913669136791368913699137091371913729137391374913759137691377913789137991380913819138291383913849138591386913879138891389913909139191392913939139491395913969139791398913999140091401914029140391404914059140691407914089140991410914119141291413914149141591416914179141891419914209142191422914239142491425914269142791428914299143091431914329143391434914359143691437914389143991440914419144291443914449144591446914479144891449914509145191452914539145491455914569145791458914599146091461914629146391464914659146691467914689146991470914719147291473914749147591476914779147891479914809148191482914839148491485914869148791488914899149091491914929149391494914959149691497914989149991500915019150291503915049150591506915079150891509915109151191512915139151491515915169151791518915199152091521915229152391524915259152691527915289152991530915319153291533915349153591536915379153891539915409154191542915439154491545915469154791548915499155091551915529155391554915559155691557915589155991560915619156291563915649156591566915679156891569915709157191572915739157491575915769157791578915799158091581915829158391584915859158691587915889158991590915919159291593915949159591596915979159891599916009160191602916039160491605916069160791608916099161091611916129161391614916159161691617916189161991620916219162291623916249162591626916279162891629916309163191632916339163491635916369163791638916399164091641916429164391644916459164691647916489164991650916519165291653916549165591656916579165891659916609166191662916639166491665916669166791668916699167091671916729167391674916759167691677916789167991680916819168291683916849168591686916879168891689916909169191692916939169491695916969169791698916999170091701917029170391704917059170691707917089170991710917119171291713917149171591716917179171891719917209172191722917239172491725917269172791728917299173091731917329173391734917359173691737917389173991740917419174291743917449174591746917479174891749917509175191752917539175491755917569175791758917599176091761917629176391764917659176691767917689176991770917719177291773917749177591776917779177891779917809178191782917839178491785917869178791788917899179091791917929179391794917959179691797917989179991800918019180291803918049180591806918079180891809918109181191812918139181491815918169181791818918199182091821918229182391824918259182691827918289182991830918319183291833918349183591836918379183891839918409184191842918439184491845918469184791848918499185091851918529185391854918559185691857918589185991860918619186291863918649186591866918679186891869918709187191872918739187491875918769187791878918799188091881918829188391884918859188691887918889188991890918919189291893918949189591896918979189891899919009190191902919039190491905919069190791908919099191091911919129191391914919159191691917919189191991920919219192291923919249192591926919279192891929919309193191932919339193491935919369193791938919399194091941919429194391944919459194691947919489194991950919519195291953919549195591956919579195891959919609196191962919639196491965919669196791968919699197091971919729197391974919759197691977919789197991980919819198291983919849198591986919879198891989919909199191992919939199491995919969199791998919999200092001920029200392004920059200692007920089200992010920119201292013920149201592016920179201892019920209202192022920239202492025920269202792028920299203092031920329203392034920359203692037920389203992040920419204292043920449204592046920479204892049920509205192052920539205492055920569205792058920599206092061920629206392064920659206692067920689206992070920719207292073920749207592076920779207892079920809208192082920839208492085920869208792088920899209092091920929209392094920959209692097920989209992100921019210292103921049210592106921079210892109921109211192112921139211492115921169211792118921199212092121921229212392124921259212692127921289212992130921319213292133921349213592136921379213892139921409214192142921439214492145921469214792148921499215092151921529215392154921559215692157921589215992160921619216292163921649216592166921679216892169921709217192172921739217492175921769217792178921799218092181921829218392184921859218692187921889218992190921919219292193921949219592196921979219892199922009220192202922039220492205922069220792208922099221092211922129221392214922159221692217922189221992220922219222292223922249222592226922279222892229922309223192232922339223492235922369223792238922399224092241922429224392244922459224692247922489224992250922519225292253922549225592256922579225892259922609226192262922639226492265922669226792268922699227092271922729227392274922759227692277922789227992280922819228292283922849228592286922879228892289922909229192292922939229492295922969229792298922999230092301923029230392304923059230692307923089230992310923119231292313923149231592316923179231892319923209232192322923239232492325923269232792328923299233092331923329233392334923359233692337923389233992340923419234292343923449234592346923479234892349923509235192352923539235492355923569235792358923599236092361923629236392364923659236692367923689236992370923719237292373923749237592376923779237892379923809238192382923839238492385923869238792388923899239092391923929239392394923959239692397923989239992400924019240292403924049240592406924079240892409924109241192412924139241492415924169241792418924199242092421924229242392424924259242692427924289242992430924319243292433924349243592436924379243892439924409244192442924439244492445924469244792448924499245092451924529245392454924559245692457924589245992460924619246292463924649246592466924679246892469924709247192472924739247492475924769247792478924799248092481924829248392484924859248692487924889248992490924919249292493924949249592496924979249892499925009250192502925039250492505925069250792508925099251092511925129251392514925159251692517925189251992520925219252292523925249252592526925279252892529925309253192532925339253492535925369253792538925399254092541925429254392544925459254692547925489254992550925519255292553925549255592556925579255892559925609256192562925639256492565925669256792568925699257092571925729257392574925759257692577925789257992580925819258292583925849258592586925879258892589925909259192592925939259492595925969259792598925999260092601926029260392604926059260692607926089260992610926119261292613926149261592616926179261892619926209262192622926239262492625926269262792628926299263092631926329263392634926359263692637926389263992640926419264292643926449264592646926479264892649926509265192652926539265492655926569265792658926599266092661926629266392664926659266692667926689266992670926719267292673926749267592676926779267892679926809268192682926839268492685926869268792688926899269092691926929269392694926959269692697926989269992700927019270292703927049270592706927079270892709927109271192712927139271492715927169271792718927199272092721927229272392724927259272692727927289272992730927319273292733927349273592736927379273892739927409274192742927439274492745927469274792748927499275092751927529275392754927559275692757927589275992760927619276292763927649276592766927679276892769927709277192772927739277492775927769277792778927799278092781927829278392784927859278692787927889278992790927919279292793927949279592796927979279892799928009280192802928039280492805928069280792808928099281092811928129281392814928159281692817928189281992820928219282292823928249282592826928279282892829928309283192832928339283492835928369283792838928399284092841928429284392844928459284692847928489284992850928519285292853928549285592856928579285892859928609286192862928639286492865928669286792868928699287092871928729287392874928759287692877928789287992880928819288292883928849288592886928879288892889928909289192892928939289492895928969289792898928999290092901929029290392904929059290692907929089290992910929119291292913929149291592916929179291892919929209292192922929239292492925929269292792928929299293092931929329293392934929359293692937929389293992940929419294292943929449294592946929479294892949929509295192952929539295492955929569295792958929599296092961929629296392964929659296692967929689296992970929719297292973929749297592976929779297892979929809298192982929839298492985929869298792988929899299092991929929299392994929959299692997929989299993000930019300293003930049300593006930079300893009930109301193012930139301493015930169301793018930199302093021930229302393024930259302693027930289302993030930319303293033930349303593036930379303893039930409304193042930439304493045930469304793048930499305093051930529305393054930559305693057930589305993060930619306293063930649306593066930679306893069930709307193072930739307493075930769307793078930799308093081930829308393084930859308693087930889308993090930919309293093930949309593096930979309893099931009310193102931039310493105931069310793108931099311093111931129311393114931159311693117931189311993120931219312293123931249312593126931279312893129931309313193132931339313493135931369313793138931399314093141931429314393144931459314693147931489314993150931519315293153931549315593156931579315893159931609316193162931639316493165931669316793168931699317093171931729317393174931759317693177931789317993180931819318293183931849318593186931879318893189931909319193192931939319493195931969319793198931999320093201932029320393204932059320693207932089320993210932119321293213932149321593216932179321893219932209322193222932239322493225932269322793228932299323093231932329323393234932359323693237932389323993240932419324293243932449324593246932479324893249932509325193252932539325493255932569325793258932599326093261932629326393264932659326693267932689326993270932719327293273932749327593276932779327893279932809328193282932839328493285932869328793288932899329093291932929329393294932959329693297932989329993300933019330293303933049330593306933079330893309933109331193312933139331493315933169331793318933199332093321933229332393324933259332693327933289332993330933319333293333933349333593336933379333893339933409334193342933439334493345933469334793348933499335093351933529335393354933559335693357933589335993360933619336293363933649336593366933679336893369933709337193372933739337493375933769337793378933799338093381933829338393384933859338693387933889338993390933919339293393933949339593396933979339893399934009340193402934039340493405934069340793408934099341093411934129341393414934159341693417934189341993420934219342293423934249342593426934279342893429934309343193432934339343493435934369343793438934399344093441934429344393444934459344693447934489344993450934519345293453934549345593456934579345893459934609346193462934639346493465934669346793468934699347093471934729347393474934759347693477934789347993480934819348293483934849348593486934879348893489934909349193492934939349493495934969349793498934999350093501935029350393504935059350693507935089350993510935119351293513935149351593516935179351893519935209352193522935239352493525935269352793528935299353093531935329353393534935359353693537935389353993540935419354293543935449354593546935479354893549935509355193552935539355493555935569355793558935599356093561935629356393564935659356693567935689356993570935719357293573935749357593576935779357893579935809358193582935839358493585935869358793588935899359093591935929359393594935959359693597935989359993600936019360293603936049360593606936079360893609936109361193612936139361493615936169361793618936199362093621936229362393624936259362693627936289362993630936319363293633936349363593636936379363893639936409364193642936439364493645936469364793648936499365093651936529365393654936559365693657936589365993660936619366293663936649366593666936679366893669936709367193672936739367493675936769367793678936799368093681936829368393684936859368693687936889368993690936919369293693936949369593696936979369893699937009370193702937039370493705937069370793708937099371093711937129371393714937159371693717937189371993720937219372293723937249372593726937279372893729937309373193732937339373493735937369373793738937399374093741937429374393744937459374693747937489374993750937519375293753937549375593756937579375893759937609376193762937639376493765937669376793768937699377093771937729377393774937759377693777937789377993780937819378293783937849378593786937879378893789937909379193792937939379493795937969379793798937999380093801938029380393804938059380693807938089380993810938119381293813938149381593816938179381893819938209382193822938239382493825938269382793828938299383093831938329383393834938359383693837938389383993840938419384293843938449384593846938479384893849938509385193852938539385493855938569385793858938599386093861938629386393864938659386693867938689386993870938719387293873938749387593876938779387893879938809388193882938839388493885938869388793888938899389093891938929389393894938959389693897938989389993900939019390293903939049390593906939079390893909939109391193912939139391493915939169391793918939199392093921939229392393924939259392693927939289392993930939319393293933939349393593936939379393893939939409394193942939439394493945939469394793948939499395093951939529395393954939559395693957939589395993960939619396293963939649396593966939679396893969939709397193972939739397493975939769397793978939799398093981939829398393984939859398693987939889398993990939919399293993939949399593996939979399893999940009400194002940039400494005940069400794008940099401094011940129401394014940159401694017940189401994020940219402294023940249402594026940279402894029940309403194032940339403494035940369403794038940399404094041940429404394044940459404694047940489404994050940519405294053940549405594056940579405894059940609406194062940639406494065940669406794068940699407094071940729407394074940759407694077940789407994080940819408294083940849408594086940879408894089940909409194092940939409494095940969409794098940999410094101941029410394104941059410694107941089410994110941119411294113941149411594116941179411894119941209412194122941239412494125941269412794128941299413094131941329413394134941359413694137941389413994140941419414294143941449414594146941479414894149941509415194152941539415494155941569415794158941599416094161941629416394164941659416694167941689416994170941719417294173941749417594176941779417894179941809418194182941839418494185941869418794188941899419094191941929419394194941959419694197941989419994200942019420294203942049420594206942079420894209942109421194212942139421494215942169421794218942199422094221942229422394224942259422694227942289422994230942319423294233942349423594236942379423894239942409424194242942439424494245942469424794248942499425094251942529425394254942559425694257942589425994260942619426294263942649426594266942679426894269942709427194272942739427494275942769427794278942799428094281942829428394284942859428694287942889428994290942919429294293942949429594296942979429894299943009430194302943039430494305943069430794308943099431094311943129431394314943159431694317943189431994320943219432294323943249432594326943279432894329943309433194332943339433494335943369433794338943399434094341943429434394344943459434694347943489434994350943519435294353943549435594356943579435894359943609436194362943639436494365943669436794368943699437094371943729437394374943759437694377943789437994380943819438294383943849438594386943879438894389943909439194392943939439494395943969439794398943999440094401944029440394404944059440694407944089440994410944119441294413944149441594416944179441894419944209442194422944239442494425944269442794428944299443094431944329443394434944359443694437944389443994440944419444294443944449444594446944479444894449944509445194452944539445494455944569445794458944599446094461944629446394464944659446694467944689446994470944719447294473944749447594476944779447894479944809448194482944839448494485944869448794488944899449094491944929449394494944959449694497944989449994500945019450294503945049450594506945079450894509945109451194512945139451494515945169451794518945199452094521945229452394524945259452694527945289452994530945319453294533945349453594536945379453894539945409454194542945439454494545945469454794548945499455094551945529455394554945559455694557945589455994560945619456294563945649456594566945679456894569945709457194572945739457494575945769457794578945799458094581945829458394584945859458694587945889458994590945919459294593945949459594596945979459894599946009460194602946039460494605946069460794608946099461094611946129461394614946159461694617946189461994620946219462294623946249462594626946279462894629946309463194632946339463494635946369463794638946399464094641946429464394644946459464694647946489464994650946519465294653946549465594656946579465894659946609466194662946639466494665946669466794668946699467094671946729467394674946759467694677946789467994680946819468294683946849468594686946879468894689946909469194692946939469494695946969469794698946999470094701947029470394704947059470694707947089470994710947119471294713947149471594716947179471894719947209472194722947239472494725947269472794728947299473094731947329473394734947359473694737947389473994740947419474294743947449474594746947479474894749947509475194752947539475494755947569475794758947599476094761947629476394764947659476694767947689476994770947719477294773947749477594776947779477894779947809478194782947839478494785947869478794788947899479094791947929479394794947959479694797947989479994800948019480294803948049480594806948079480894809948109481194812948139481494815948169481794818948199482094821948229482394824948259482694827948289482994830948319483294833948349483594836948379483894839948409484194842948439484494845948469484794848948499485094851948529485394854948559485694857948589485994860948619486294863948649486594866948679486894869948709487194872948739487494875948769487794878948799488094881948829488394884948859488694887948889488994890948919489294893948949489594896948979489894899949009490194902949039490494905949069490794908949099491094911949129491394914949159491694917949189491994920949219492294923949249492594926949279492894929949309493194932949339493494935949369493794938949399494094941949429494394944949459494694947949489494994950949519495294953949549495594956949579495894959949609496194962949639496494965949669496794968949699497094971949729497394974949759497694977949789497994980949819498294983949849498594986949879498894989949909499194992949939499494995949969499794998949999500095001950029500395004950059500695007950089500995010950119501295013950149501595016950179501895019950209502195022950239502495025950269502795028950299503095031950329503395034950359503695037950389503995040950419504295043950449504595046950479504895049950509505195052950539505495055950569505795058950599506095061950629506395064950659506695067950689506995070950719507295073950749507595076950779507895079950809508195082950839508495085950869508795088950899509095091950929509395094950959509695097950989509995100951019510295103951049510595106951079510895109951109511195112951139511495115951169511795118951199512095121951229512395124951259512695127951289512995130951319513295133951349513595136951379513895139951409514195142951439514495145951469514795148951499515095151951529515395154951559515695157951589515995160951619516295163951649516595166951679516895169951709517195172951739517495175951769517795178951799518095181951829518395184951859518695187951889518995190951919519295193951949519595196951979519895199952009520195202952039520495205952069520795208952099521095211952129521395214952159521695217952189521995220952219522295223952249522595226952279522895229952309523195232952339523495235952369523795238952399524095241952429524395244952459524695247952489524995250952519525295253952549525595256952579525895259952609526195262952639526495265952669526795268952699527095271952729527395274952759527695277952789527995280952819528295283952849528595286952879528895289952909529195292952939529495295952969529795298952999530095301953029530395304953059530695307953089530995310953119531295313953149531595316953179531895319953209532195322953239532495325953269532795328953299533095331953329533395334953359533695337953389533995340953419534295343953449534595346953479534895349953509535195352953539535495355953569535795358953599536095361953629536395364953659536695367953689536995370953719537295373953749537595376953779537895379953809538195382953839538495385953869538795388953899539095391953929539395394953959539695397953989539995400954019540295403954049540595406954079540895409954109541195412954139541495415954169541795418954199542095421954229542395424954259542695427954289542995430954319543295433954349543595436954379543895439954409544195442954439544495445954469544795448954499545095451954529545395454954559545695457954589545995460954619546295463954649546595466954679546895469954709547195472954739547495475954769547795478954799548095481954829548395484954859548695487954889548995490954919549295493954949549595496954979549895499955009550195502955039550495505955069550795508955099551095511955129551395514955159551695517955189551995520955219552295523955249552595526955279552895529955309553195532955339553495535955369553795538955399554095541955429554395544955459554695547955489554995550955519555295553955549555595556955579555895559955609556195562955639556495565955669556795568955699557095571955729557395574955759557695577955789557995580955819558295583955849558595586955879558895589955909559195592955939559495595955969559795598955999560095601956029560395604956059560695607956089560995610956119561295613956149561595616956179561895619956209562195622956239562495625956269562795628956299563095631956329563395634956359563695637956389563995640956419564295643956449564595646956479564895649956509565195652956539565495655956569565795658956599566095661956629566395664956659566695667956689566995670956719567295673956749567595676956779567895679956809568195682956839568495685956869568795688956899569095691956929569395694956959569695697956989569995700957019570295703957049570595706957079570895709957109571195712957139571495715957169571795718957199572095721957229572395724957259572695727957289572995730957319573295733957349573595736957379573895739957409574195742957439574495745957469574795748957499575095751957529575395754957559575695757957589575995760957619576295763957649576595766957679576895769957709577195772957739577495775957769577795778957799578095781957829578395784957859578695787957889578995790957919579295793957949579595796957979579895799958009580195802958039580495805958069580795808958099581095811958129581395814958159581695817958189581995820958219582295823958249582595826958279582895829958309583195832958339583495835958369583795838958399584095841958429584395844958459584695847958489584995850958519585295853958549585595856958579585895859958609586195862958639586495865958669586795868958699587095871958729587395874958759587695877958789587995880958819588295883958849588595886958879588895889958909589195892958939589495895958969589795898958999590095901959029590395904959059590695907959089590995910959119591295913959149591595916959179591895919959209592195922959239592495925959269592795928959299593095931959329593395934959359593695937959389593995940959419594295943959449594595946959479594895949959509595195952959539595495955959569595795958959599596095961959629596395964959659596695967959689596995970959719597295973959749597595976959779597895979959809598195982959839598495985959869598795988959899599095991959929599395994959959599695997959989599996000960019600296003960049600596006960079600896009960109601196012960139601496015960169601796018960199602096021960229602396024960259602696027960289602996030960319603296033960349603596036960379603896039960409604196042960439604496045960469604796048960499605096051960529605396054960559605696057960589605996060960619606296063960649606596066960679606896069960709607196072960739607496075960769607796078960799608096081960829608396084960859608696087960889608996090960919609296093960949609596096960979609896099961009610196102961039610496105961069610796108961099611096111961129611396114961159611696117961189611996120961219612296123961249612596126961279612896129961309613196132961339613496135961369613796138961399614096141961429614396144961459614696147961489614996150961519615296153961549615596156961579615896159961609616196162961639616496165961669616796168961699617096171961729617396174961759617696177961789617996180961819618296183961849618596186961879618896189961909619196192961939619496195961969619796198961999620096201962029620396204962059620696207962089620996210962119621296213962149621596216962179621896219962209622196222962239622496225962269622796228962299623096231962329623396234962359623696237962389623996240962419624296243962449624596246962479624896249962509625196252962539625496255962569625796258962599626096261962629626396264962659626696267962689626996270962719627296273962749627596276962779627896279962809628196282962839628496285962869628796288962899629096291962929629396294962959629696297962989629996300963019630296303963049630596306963079630896309963109631196312963139631496315963169631796318963199632096321963229632396324963259632696327963289632996330963319633296333963349633596336963379633896339963409634196342963439634496345963469634796348963499635096351963529635396354963559635696357963589635996360963619636296363963649636596366963679636896369963709637196372963739637496375963769637796378963799638096381963829638396384963859638696387963889638996390963919639296393963949639596396963979639896399964009640196402964039640496405964069640796408964099641096411964129641396414964159641696417964189641996420964219642296423964249642596426964279642896429964309643196432964339643496435964369643796438964399644096441964429644396444964459644696447964489644996450964519645296453964549645596456964579645896459964609646196462964639646496465964669646796468964699647096471964729647396474964759647696477964789647996480964819648296483964849648596486964879648896489964909649196492964939649496495964969649796498964999650096501965029650396504965059650696507965089650996510965119651296513965149651596516965179651896519965209652196522965239652496525965269652796528965299653096531965329653396534965359653696537965389653996540965419654296543965449654596546965479654896549965509655196552965539655496555965569655796558965599656096561965629656396564965659656696567965689656996570965719657296573965749657596576965779657896579965809658196582965839658496585965869658796588965899659096591965929659396594965959659696597965989659996600966019660296603966049660596606966079660896609966109661196612966139661496615966169661796618966199662096621966229662396624966259662696627966289662996630966319663296633966349663596636966379663896639966409664196642966439664496645966469664796648966499665096651966529665396654966559665696657966589665996660966619666296663966649666596666966679666896669966709667196672966739667496675966769667796678966799668096681966829668396684966859668696687966889668996690966919669296693966949669596696966979669896699967009670196702967039670496705967069670796708967099671096711967129671396714967159671696717967189671996720967219672296723967249672596726967279672896729967309673196732967339673496735967369673796738967399674096741967429674396744967459674696747967489674996750967519675296753967549675596756967579675896759967609676196762967639676496765967669676796768967699677096771967729677396774967759677696777967789677996780967819678296783967849678596786967879678896789967909679196792967939679496795967969679796798967999680096801968029680396804968059680696807968089680996810968119681296813968149681596816968179681896819968209682196822968239682496825968269682796828968299683096831968329683396834968359683696837968389683996840968419684296843968449684596846968479684896849968509685196852968539685496855968569685796858968599686096861968629686396864968659686696867968689686996870968719687296873968749687596876968779687896879968809688196882968839688496885968869688796888968899689096891968929689396894968959689696897968989689996900969019690296903969049690596906969079690896909969109691196912969139691496915969169691796918969199692096921969229692396924969259692696927969289692996930969319693296933969349693596936969379693896939969409694196942969439694496945969469694796948969499695096951969529695396954969559695696957969589695996960969619696296963969649696596966969679696896969969709697196972969739697496975969769697796978969799698096981969829698396984969859698696987969889698996990969919699296993969949699596996969979699896999970009700197002970039700497005970069700797008970099701097011970129701397014970159701697017970189701997020970219702297023970249702597026970279702897029970309703197032970339703497035970369703797038970399704097041970429704397044970459704697047970489704997050970519705297053970549705597056970579705897059970609706197062970639706497065970669706797068970699707097071970729707397074970759707697077970789707997080970819708297083970849708597086970879708897089970909709197092970939709497095970969709797098970999710097101971029710397104971059710697107971089710997110971119711297113971149711597116971179711897119971209712197122971239712497125971269712797128971299713097131971329713397134971359713697137971389713997140971419714297143971449714597146971479714897149971509715197152971539715497155971569715797158971599716097161971629716397164971659716697167971689716997170971719717297173971749717597176971779717897179971809718197182971839718497185971869718797188971899719097191971929719397194971959719697197971989719997200972019720297203972049720597206972079720897209972109721197212972139721497215972169721797218972199722097221972229722397224972259722697227972289722997230972319723297233972349723597236972379723897239972409724197242972439724497245972469724797248972499725097251972529725397254972559725697257972589725997260972619726297263972649726597266972679726897269972709727197272972739727497275972769727797278972799728097281972829728397284972859728697287972889728997290972919729297293972949729597296972979729897299973009730197302973039730497305973069730797308973099731097311973129731397314973159731697317973189731997320973219732297323973249732597326973279732897329973309733197332973339733497335973369733797338973399734097341973429734397344973459734697347973489734997350973519735297353973549735597356973579735897359973609736197362973639736497365973669736797368973699737097371973729737397374973759737697377973789737997380973819738297383973849738597386973879738897389973909739197392973939739497395973969739797398973999740097401974029740397404974059740697407974089740997410974119741297413974149741597416974179741897419974209742197422974239742497425974269742797428974299743097431974329743397434974359743697437974389743997440974419744297443974449744597446974479744897449974509745197452974539745497455974569745797458974599746097461974629746397464974659746697467974689746997470974719747297473974749747597476974779747897479974809748197482974839748497485974869748797488974899749097491974929749397494974959749697497974989749997500975019750297503975049750597506975079750897509975109751197512975139751497515975169751797518975199752097521975229752397524975259752697527975289752997530975319753297533975349753597536975379753897539975409754197542975439754497545975469754797548975499755097551975529755397554975559755697557975589755997560975619756297563975649756597566975679756897569975709757197572975739757497575975769757797578975799758097581975829758397584975859758697587975889758997590975919759297593975949759597596975979759897599976009760197602976039760497605976069760797608976099761097611976129761397614976159761697617976189761997620976219762297623976249762597626976279762897629976309763197632976339763497635976369763797638976399764097641976429764397644976459764697647976489764997650976519765297653976549765597656976579765897659976609766197662976639766497665976669766797668976699767097671976729767397674976759767697677976789767997680976819768297683976849768597686976879768897689976909769197692976939769497695976969769797698976999770097701977029770397704977059770697707977089770997710977119771297713977149771597716977179771897719977209772197722977239772497725977269772797728977299773097731977329773397734977359773697737977389773997740977419774297743977449774597746977479774897749977509775197752977539775497755977569775797758977599776097761977629776397764977659776697767977689776997770977719777297773977749777597776977779777897779977809778197782977839778497785977869778797788977899779097791977929779397794977959779697797977989779997800978019780297803978049780597806978079780897809978109781197812978139781497815978169781797818978199782097821978229782397824978259782697827978289782997830978319783297833978349783597836978379783897839978409784197842978439784497845978469784797848978499785097851978529785397854978559785697857978589785997860978619786297863978649786597866978679786897869978709787197872978739787497875978769787797878978799788097881978829788397884978859788697887978889788997890978919789297893978949789597896978979789897899979009790197902979039790497905979069790797908979099791097911979129791397914979159791697917979189791997920979219792297923979249792597926979279792897929979309793197932979339793497935979369793797938979399794097941979429794397944979459794697947979489794997950979519795297953979549795597956979579795897959979609796197962979639796497965979669796797968979699797097971979729797397974979759797697977979789797997980979819798297983979849798597986979879798897989979909799197992979939799497995979969799797998979999800098001980029800398004980059800698007980089800998010980119801298013980149801598016980179801898019980209802198022980239802498025980269802798028980299803098031980329803398034980359803698037980389803998040980419804298043980449804598046980479804898049980509805198052980539805498055980569805798058980599806098061980629806398064980659806698067980689806998070980719807298073980749807598076980779807898079980809808198082980839808498085980869808798088980899809098091980929809398094980959809698097980989809998100981019810298103981049810598106981079810898109981109811198112981139811498115981169811798118981199812098121981229812398124981259812698127981289812998130981319813298133981349813598136981379813898139981409814198142981439814498145981469814798148981499815098151981529815398154981559815698157981589815998160981619816298163981649816598166981679816898169981709817198172981739817498175981769817798178981799818098181981829818398184981859818698187981889818998190981919819298193981949819598196981979819898199982009820198202982039820498205982069820798208982099821098211982129821398214982159821698217982189821998220982219822298223982249822598226982279822898229982309823198232982339823498235982369823798238982399824098241982429824398244982459824698247982489824998250982519825298253982549825598256982579825898259982609826198262982639826498265982669826798268982699827098271982729827398274982759827698277982789827998280982819828298283982849828598286982879828898289982909829198292982939829498295982969829798298982999830098301983029830398304983059830698307983089830998310983119831298313983149831598316983179831898319983209832198322983239832498325983269832798328983299833098331983329833398334983359833698337983389833998340983419834298343983449834598346983479834898349983509835198352983539835498355983569835798358983599836098361983629836398364983659836698367983689836998370983719837298373983749837598376983779837898379983809838198382983839838498385983869838798388983899839098391983929839398394983959839698397983989839998400984019840298403984049840598406984079840898409984109841198412984139841498415984169841798418984199842098421984229842398424984259842698427984289842998430984319843298433984349843598436984379843898439984409844198442984439844498445984469844798448984499845098451984529845398454984559845698457984589845998460984619846298463984649846598466984679846898469984709847198472984739847498475984769847798478984799848098481984829848398484984859848698487984889848998490984919849298493984949849598496984979849898499985009850198502985039850498505985069850798508985099851098511985129851398514985159851698517985189851998520985219852298523985249852598526985279852898529985309853198532985339853498535985369853798538985399854098541985429854398544985459854698547985489854998550985519855298553985549855598556985579855898559985609856198562985639856498565985669856798568985699857098571985729857398574985759857698577985789857998580985819858298583985849858598586985879858898589985909859198592985939859498595985969859798598985999860098601986029860398604986059860698607986089860998610986119861298613986149861598616986179861898619986209862198622986239862498625986269862798628986299863098631986329863398634986359863698637986389863998640986419864298643986449864598646986479864898649986509865198652986539865498655986569865798658986599866098661986629866398664986659866698667986689866998670986719867298673986749867598676986779867898679986809868198682986839868498685986869868798688986899869098691986929869398694986959869698697986989869998700987019870298703987049870598706987079870898709987109871198712987139871498715987169871798718987199872098721987229872398724987259872698727987289872998730987319873298733987349873598736987379873898739987409874198742987439874498745987469874798748987499875098751987529875398754987559875698757987589875998760987619876298763987649876598766987679876898769987709877198772987739877498775987769877798778987799878098781987829878398784987859878698787987889878998790987919879298793987949879598796987979879898799988009880198802988039880498805988069880798808988099881098811988129881398814988159881698817988189881998820988219882298823988249882598826988279882898829988309883198832988339883498835988369883798838988399884098841988429884398844988459884698847988489884998850988519885298853988549885598856988579885898859988609886198862988639886498865988669886798868988699887098871988729887398874988759887698877988789887998880988819888298883988849888598886988879888898889988909889198892988939889498895988969889798898988999890098901989029890398904989059890698907989089890998910989119891298913989149891598916989179891898919989209892198922989239892498925989269892798928989299893098931989329893398934989359893698937989389893998940989419894298943989449894598946989479894898949989509895198952989539895498955989569895798958989599896098961989629896398964989659896698967989689896998970989719897298973989749897598976989779897898979989809898198982989839898498985989869898798988989899899098991989929899398994989959899698997989989899999000990019900299003990049900599006990079900899009990109901199012990139901499015990169901799018990199902099021990229902399024990259902699027990289902999030990319903299033990349903599036990379903899039990409904199042990439904499045990469904799048990499905099051990529905399054990559905699057990589905999060990619906299063990649906599066990679906899069990709907199072990739907499075990769907799078990799908099081990829908399084990859908699087990889908999090990919909299093990949909599096990979909899099991009910199102991039910499105991069910799108991099911099111991129911399114991159911699117991189911999120991219912299123991249912599126991279912899129991309913199132991339913499135991369913799138991399914099141991429914399144991459914699147991489914999150991519915299153991549915599156991579915899159991609916199162991639916499165991669916799168991699917099171991729917399174991759917699177991789917999180991819918299183991849918599186991879918899189991909919199192991939919499195991969919799198991999920099201992029920399204992059920699207992089920999210992119921299213992149921599216992179921899219992209922199222992239922499225992269922799228992299923099231992329923399234992359923699237992389923999240992419924299243992449924599246992479924899249992509925199252992539925499255992569925799258992599926099261992629926399264992659926699267992689926999270992719927299273992749927599276992779927899279992809928199282992839928499285992869928799288992899929099291992929929399294992959929699297992989929999300993019930299303993049930599306993079930899309993109931199312993139931499315993169931799318993199932099321993229932399324993259932699327993289932999330993319933299333993349933599336993379933899339993409934199342993439934499345993469934799348993499935099351993529935399354993559935699357993589935999360993619936299363993649936599366993679936899369993709937199372993739937499375993769937799378993799938099381993829938399384993859938699387993889938999390993919939299393993949939599396993979939899399994009940199402994039940499405994069940799408994099941099411994129941399414994159941699417994189941999420994219942299423994249942599426994279942899429994309943199432994339943499435994369943799438994399944099441994429944399444994459944699447994489944999450994519945299453994549945599456994579945899459994609946199462994639946499465994669946799468994699947099471994729947399474994759947699477994789947999480994819948299483994849948599486994879948899489994909949199492994939949499495994969949799498994999950099501995029950399504995059950699507995089950999510995119951299513995149951599516995179951899519995209952199522995239952499525995269952799528995299953099531995329953399534995359953699537995389953999540995419954299543995449954599546995479954899549995509955199552995539955499555995569955799558995599956099561995629956399564995659956699567995689956999570995719957299573995749957599576995779957899579995809958199582995839958499585995869958799588995899959099591995929959399594995959959699597995989959999600996019960299603996049960599606996079960899609996109961199612996139961499615996169961799618996199962099621996229962399624996259962699627996289962999630996319963299633996349963599636996379963899639996409964199642996439964499645996469964799648996499965099651996529965399654996559965699657996589965999660996619966299663996649966599666996679966899669996709967199672996739967499675996769967799678996799968099681996829968399684996859968699687996889968999690996919969299693996949969599696996979969899699997009970199702997039970499705997069970799708997099971099711997129971399714997159971699717997189971999720997219972299723997249972599726997279972899729997309973199732997339973499735997369973799738997399974099741997429974399744997459974699747997489974999750997519975299753997549975599756997579975899759997609976199762997639976499765997669976799768997699977099771997729977399774997759977699777997789977999780997819978299783997849978599786997879978899789997909979199792997939979499795997969979799798997999980099801998029980399804998059980699807998089980999810998119981299813998149981599816998179981899819998209982199822998239982499825998269982799828998299983099831998329983399834998359983699837998389983999840998419984299843998449984599846998479984899849998509985199852998539985499855998569985799858998599986099861998629986399864998659986699867998689986999870998719987299873998749987599876998779987899879998809988199882998839988499885998869988799888998899989099891998929989399894998959989699897998989989999900999019990299903999049990599906999079990899909999109991199912999139991499915999169991799918999199992099921999229992399924999259992699927999289992999930999319993299933999349993599936999379993899939999409994199942999439994499945999469994799948999499995099951999529995399954999559995699957999589995999960999619996299963999649996599966999679996899969999709997199972999739997499975999769997799978999799998099981999829998399984999859998699987999889998999990999919999299993999949999599996999979999899999100000100001100002100003100004100005100006100007100008100009100010100011100012100013100014100015100016100017100018100019100020100021100022100023100024100025100026100027100028100029100030100031100032100033100034100035100036100037100038100039100040100041100042100043100044100045100046100047100048100049100050100051100052100053100054100055100056100057100058100059100060100061100062100063100064100065100066100067100068100069100070100071100072100073100074100075100076100077100078100079100080100081100082100083100084100085100086100087100088100089100090100091100092100093100094100095100096100097100098100099100100100101100102100103100104100105100106100107100108100109100110100111100112100113100114100115100116100117100118100119100120100121100122100123100124100125100126100127100128100129100130100131100132100133100134100135100136100137100138100139100140100141100142100143100144100145100146100147100148100149100150100151100152100153100154100155100156100157100158100159100160100161100162100163100164100165100166100167100168100169100170100171100172100173100174100175100176100177100178100179100180100181100182100183100184100185100186100187100188100189100190100191100192100193100194100195100196100197100198100199100200100201100202100203100204100205100206100207100208100209100210100211100212100213100214100215100216100217100218100219100220100221100222100223100224100225100226100227100228100229100230100231100232100233100234100235100236100237100238100239100240100241100242100243100244100245100246100247100248100249100250100251100252100253100254100255100256100257100258100259100260100261100262100263100264100265100266100267100268100269100270100271100272100273100274100275100276100277100278100279100280100281100282100283100284100285100286100287100288100289100290100291100292100293100294100295100296100297100298100299100300100301100302100303100304100305100306100307100308100309100310100311100312100313100314100315100316100317100318100319100320100321100322100323100324100325100326100327100328100329100330100331100332100333100334100335100336100337100338100339100340100341100342100343100344100345100346100347100348100349100350100351100352100353100354100355100356100357100358100359100360100361100362100363100364100365100366100367100368100369100370100371100372100373100374100375100376100377100378100379100380100381100382100383100384100385100386100387100388100389100390100391100392100393100394100395100396100397100398100399100400100401100402100403100404100405100406100407100408100409100410100411100412100413100414100415100416100417100418100419100420100421100422100423100424100425100426100427100428100429100430100431100432100433100434100435100436100437100438100439100440100441100442100443100444100445100446100447100448100449100450100451100452100453100454100455100456100457100458100459100460100461100462100463100464100465100466100467100468100469100470100471100472100473100474100475100476100477100478100479100480100481100482100483100484100485100486100487100488100489100490100491100492100493100494100495100496100497100498100499100500100501100502100503100504100505100506100507100508100509100510100511100512100513100514100515100516100517100518100519100520100521100522100523100524100525100526100527100528100529100530100531100532100533100534100535100536100537100538100539100540100541100542100543100544100545100546100547100548100549100550100551100552100553100554100555100556100557100558100559100560100561100562100563100564100565100566100567100568100569100570100571100572100573100574100575100576100577100578100579100580100581100582100583100584100585100586100587100588100589100590100591100592100593100594100595100596100597100598100599100600100601100602100603100604100605100606100607100608100609100610100611100612100613100614100615100616100617100618100619100620100621100622100623100624100625100626100627100628100629100630100631100632100633100634100635100636100637100638100639100640100641100642100643100644100645100646100647100648100649100650100651100652100653100654100655100656100657100658100659100660100661100662100663100664100665100666100667100668100669100670100671100672100673100674100675100676100677100678100679100680100681100682100683100684100685100686100687100688100689100690100691100692100693100694100695100696100697100698100699100700100701100702100703100704100705100706100707100708100709100710100711100712100713100714100715100716100717100718100719100720100721100722100723100724100725100726100727100728100729100730100731100732100733100734100735100736100737100738100739100740100741100742100743100744100745100746100747100748100749100750100751100752100753100754100755100756100757100758100759100760100761100762100763100764100765100766100767100768100769100770100771100772100773100774100775100776100777100778100779100780100781100782100783100784100785100786100787100788100789100790100791100792100793100794100795100796100797100798100799100800100801100802100803100804100805100806100807100808100809100810100811100812100813100814100815100816100817100818100819100820100821100822100823100824100825100826100827100828100829100830100831100832100833100834100835100836100837100838100839100840100841100842100843100844100845100846100847100848100849100850100851100852100853100854100855100856100857100858100859100860100861100862100863100864100865100866100867100868100869100870100871100872100873100874100875100876100877100878100879100880100881100882100883100884100885100886100887100888100889100890100891100892100893100894100895100896100897100898100899100900100901100902100903100904100905100906100907100908100909100910100911100912100913100914100915100916100917100918100919100920100921100922100923100924100925100926100927100928100929100930100931100932100933100934100935100936100937100938100939100940100941100942100943100944100945100946100947100948100949100950100951100952100953100954100955100956100957100958100959100960100961100962100963100964100965100966100967100968100969100970100971100972100973100974100975100976100977100978100979100980100981100982100983100984100985100986100987100988100989100990100991100992100993100994100995100996100997100998100999101000101001101002101003101004101005101006101007101008101009101010101011101012101013101014101015101016101017101018101019101020101021101022101023101024101025101026101027101028101029101030101031101032101033101034101035101036101037101038101039101040101041101042101043101044101045101046101047101048101049101050101051101052101053101054101055101056101057101058101059101060101061101062101063101064101065101066101067101068101069101070101071101072101073101074101075101076101077101078101079101080101081101082101083101084101085101086101087101088101089101090101091101092101093101094101095101096101097101098101099101100101101101102101103101104101105101106101107101108101109101110101111101112101113101114101115101116101117101118101119101120101121101122101123101124101125101126101127101128101129101130101131101132101133101134101135101136101137101138101139101140101141101142101143101144101145101146101147101148101149101150101151101152101153101154101155101156101157101158101159101160101161101162101163101164101165101166101167101168101169101170101171101172101173101174101175101176101177101178101179101180101181101182101183101184101185101186101187101188101189101190101191101192101193101194101195101196101197101198101199101200101201101202101203101204101205101206101207101208101209101210101211101212101213101214101215101216101217101218101219101220101221101222101223101224101225101226101227101228101229101230101231101232101233101234101235101236101237101238101239101240101241101242101243101244101245101246101247101248101249101250101251101252101253101254101255101256101257101258101259101260101261101262101263101264101265101266101267101268101269101270101271101272101273101274101275101276101277101278101279101280101281101282101283101284101285101286101287101288101289101290101291101292101293101294101295101296101297101298101299101300101301101302101303101304101305101306101307101308101309101310101311101312101313101314101315101316101317101318101319101320101321101322101323101324101325101326101327101328101329101330101331101332101333101334101335101336101337101338101339101340101341101342101343101344101345101346101347101348101349101350101351101352101353101354101355101356101357101358101359101360101361101362101363101364101365101366101367101368101369101370101371101372101373101374101375101376101377101378101379101380101381101382101383101384101385101386101387101388101389101390101391101392101393101394101395101396101397101398101399101400101401101402101403101404101405101406101407101408101409101410101411101412101413101414101415101416101417101418101419101420101421101422101423101424101425101426101427101428101429101430101431101432101433101434101435101436101437101438101439101440101441101442101443101444101445101446101447101448101449101450101451101452101453101454101455101456101457101458101459101460101461101462101463101464101465101466101467101468101469101470101471101472101473101474101475101476101477101478101479101480101481101482101483101484101485101486101487101488101489101490101491101492101493101494101495101496101497101498101499101500101501101502101503101504101505101506101507101508101509101510101511101512101513101514101515101516101517101518101519101520101521101522101523101524101525101526101527101528101529101530101531101532101533101534101535101536101537101538101539101540101541101542101543101544101545101546101547101548101549101550101551101552101553101554101555101556101557101558101559101560101561101562101563101564101565101566101567101568101569101570101571101572101573101574101575101576101577101578101579101580101581101582101583101584101585101586101587101588101589101590101591101592101593101594101595101596101597101598101599101600101601101602101603101604101605101606101607101608101609101610101611101612101613101614101615101616101617101618101619101620101621101622101623101624101625101626101627101628101629101630101631101632101633101634101635101636101637101638101639101640101641101642101643101644101645101646101647101648101649101650101651101652101653101654101655101656101657101658101659101660101661101662101663101664101665101666101667101668101669101670101671101672101673101674101675101676101677101678101679101680101681101682101683101684101685101686101687101688101689101690101691101692101693101694101695101696101697101698101699101700101701101702101703101704101705101706101707101708101709101710101711101712101713101714101715101716101717101718101719101720101721101722101723101724101725101726101727101728101729101730101731101732101733101734101735101736101737101738101739101740101741101742101743101744101745101746101747101748101749101750101751101752101753101754101755101756101757101758101759101760101761101762101763101764101765101766101767101768101769101770101771101772101773101774101775101776101777101778101779101780101781101782101783101784101785101786101787101788101789101790101791101792101793101794101795101796101797101798101799101800101801101802101803101804101805101806101807101808101809101810101811101812101813101814101815101816101817101818101819101820101821101822101823101824101825101826101827101828101829101830101831101832101833101834101835101836101837101838101839101840101841101842101843101844101845101846101847101848101849101850101851101852101853101854101855101856101857101858101859101860101861101862101863101864101865101866101867101868101869101870101871101872101873101874101875101876101877101878101879101880101881101882101883101884101885101886101887101888101889101890101891101892101893101894101895101896101897101898101899101900101901101902101903101904101905101906101907101908101909101910101911101912101913101914101915101916101917101918101919101920101921101922101923101924101925101926101927101928101929101930101931101932101933101934101935101936101937101938101939101940101941101942101943101944101945101946101947101948101949101950101951101952101953101954101955101956101957101958101959101960101961101962101963101964101965101966101967101968101969101970101971101972101973101974101975101976101977101978101979101980101981101982101983101984101985101986101987101988101989101990101991101992101993101994101995101996101997101998101999102000102001102002102003102004102005102006102007102008102009102010102011102012102013102014102015102016102017102018102019102020102021102022102023102024102025102026102027102028102029102030102031102032102033102034102035102036102037102038102039102040102041102042102043102044102045102046102047102048102049102050102051102052102053102054102055102056102057102058102059102060102061102062102063102064102065102066102067102068102069102070102071102072102073102074102075102076102077102078102079102080102081102082102083102084102085102086102087102088102089102090102091102092102093102094102095102096102097102098102099102100102101102102102103102104102105102106102107102108102109102110102111102112102113102114102115102116102117102118102119102120102121102122102123102124102125102126102127102128102129102130102131102132102133102134102135102136102137102138102139102140102141102142102143102144102145102146102147102148102149102150102151102152102153102154102155102156102157102158102159102160102161102162102163102164102165102166102167102168102169102170102171102172102173102174102175102176102177102178102179102180102181102182102183102184102185102186102187102188102189102190102191102192102193102194102195102196102197102198102199102200102201102202102203102204102205102206102207102208102209102210102211102212102213102214102215102216102217102218102219102220102221102222102223102224102225102226102227102228102229102230102231102232102233102234102235102236102237102238102239102240102241102242102243102244102245102246102247102248102249102250102251102252102253102254102255102256102257102258102259102260102261102262102263102264102265102266102267102268102269102270102271102272102273102274102275102276102277102278102279102280102281102282102283102284102285102286102287102288102289102290102291102292102293102294102295102296102297102298102299102300102301102302102303102304102305102306102307102308102309102310102311102312102313102314102315102316102317102318102319102320102321102322102323102324102325102326102327102328102329102330102331102332102333102334102335102336102337102338102339102340102341102342102343102344102345102346102347102348102349102350102351102352102353102354102355102356102357102358102359102360102361102362102363102364102365102366102367102368102369102370102371102372102373102374102375102376102377102378102379102380102381102382102383102384102385102386102387102388102389102390102391102392102393102394102395102396102397102398102399102400102401102402102403102404102405102406102407102408102409102410102411102412102413102414102415102416102417102418102419102420102421102422102423102424102425102426102427102428102429102430102431102432102433102434102435102436102437102438102439102440102441102442102443102444102445102446102447102448102449102450102451102452102453102454102455102456102457102458102459102460102461102462102463102464102465102466102467102468102469102470102471102472102473102474102475102476102477102478102479102480102481102482102483102484102485102486102487102488102489102490102491102492102493102494102495102496102497102498102499102500102501102502102503102504102505102506102507102508102509102510102511102512102513102514102515102516102517102518102519102520102521102522102523102524102525102526102527102528102529102530102531102532102533102534102535102536102537102538102539102540102541102542102543102544102545102546102547102548102549102550102551102552102553102554102555102556102557102558102559102560102561102562102563102564102565102566102567102568102569102570102571102572102573102574102575102576102577102578102579102580102581102582102583102584102585102586102587102588102589102590102591102592102593102594102595102596102597102598102599102600102601102602102603102604102605102606102607102608102609102610102611102612102613102614102615102616102617102618102619102620102621102622102623102624102625102626102627102628102629102630102631102632102633102634102635102636102637102638102639102640102641102642102643102644102645102646102647102648102649102650102651102652102653102654102655102656102657102658102659102660102661102662102663102664102665102666102667102668102669102670102671102672102673102674102675102676102677102678102679102680102681102682102683102684102685102686102687102688102689102690102691102692102693102694102695102696102697102698102699102700102701102702102703102704102705102706102707102708102709102710102711102712102713102714102715102716102717102718102719102720102721102722102723102724102725102726102727102728102729102730102731102732102733102734102735102736102737102738102739102740102741102742102743102744102745102746102747102748102749102750102751102752102753102754102755102756102757102758102759102760102761102762102763102764102765102766102767102768102769102770102771102772102773102774102775102776102777102778102779102780102781102782102783102784102785102786102787102788102789102790102791102792102793102794102795102796102797102798102799102800102801102802102803102804102805102806102807102808102809102810102811102812102813102814102815102816102817102818102819102820102821102822102823102824102825102826102827102828102829102830102831102832102833102834102835102836102837102838102839102840102841102842102843102844102845102846102847102848102849102850102851102852102853102854102855102856102857102858102859102860102861102862102863102864102865102866102867102868102869102870102871102872102873102874102875102876102877102878102879102880102881102882102883102884102885102886102887102888102889102890102891102892102893102894102895102896102897102898102899102900102901102902102903102904102905102906102907102908102909102910102911102912102913102914102915102916102917102918102919102920102921102922102923102924102925102926102927102928102929102930102931102932102933102934102935102936102937102938102939102940102941102942102943102944102945102946102947102948102949102950102951102952102953102954102955102956102957102958102959102960102961102962102963102964102965102966102967102968102969102970102971102972102973102974102975102976102977102978102979102980102981102982102983102984102985102986102987102988102989102990102991102992102993102994102995102996102997102998102999103000103001103002103003103004103005103006103007103008103009103010103011103012103013103014103015103016103017103018103019103020103021103022103023103024103025103026103027103028103029103030103031103032103033103034103035103036103037103038103039103040103041103042103043103044103045103046103047103048103049103050103051103052103053103054103055103056103057103058103059103060103061103062103063103064103065103066103067103068103069103070103071103072103073103074103075103076103077103078103079103080103081103082103083103084103085103086103087103088103089103090103091103092103093103094103095103096103097103098103099103100103101103102103103103104103105103106103107103108103109103110103111103112103113103114103115103116103117103118103119103120103121103122103123103124103125103126103127103128103129103130103131103132103133103134103135103136103137103138103139103140103141103142103143103144103145103146103147103148103149103150103151103152103153103154103155103156103157103158103159103160103161103162103163103164103165103166103167103168103169103170103171103172103173103174103175103176103177103178103179103180103181103182103183103184103185103186103187103188103189103190103191103192103193103194103195103196103197103198103199103200103201103202103203103204103205103206103207103208103209103210103211103212103213103214103215103216103217103218103219103220103221103222103223103224103225103226103227103228103229103230103231103232103233103234103235103236103237103238103239103240103241103242103243103244103245103246103247103248103249103250103251103252103253103254103255103256103257103258103259103260103261103262103263103264103265103266103267103268103269103270103271103272103273103274103275103276103277103278103279103280103281103282103283103284103285103286103287103288103289103290103291103292103293103294103295103296103297103298103299103300103301103302103303103304103305103306103307103308103309103310103311103312103313103314103315103316103317103318103319103320103321103322103323103324103325103326103327103328103329103330103331103332103333103334103335103336103337103338103339103340103341103342103343103344103345103346103347103348103349103350103351103352103353103354103355103356103357103358103359103360103361103362103363103364103365103366103367103368103369103370103371103372103373103374103375103376103377103378103379103380103381103382103383103384103385103386103387103388103389103390103391103392103393103394103395103396103397103398103399103400103401103402103403103404103405103406103407103408103409103410103411103412103413103414103415103416103417103418103419103420103421103422103423103424103425103426103427103428103429103430103431103432103433103434103435103436103437103438103439103440103441103442103443103444103445103446103447103448103449103450103451103452103453103454103455103456103457103458103459103460103461103462103463103464103465103466103467103468103469103470103471103472103473103474103475103476103477103478103479103480103481103482103483103484103485103486103487103488103489103490103491103492103493103494103495103496103497103498103499103500103501103502103503103504103505103506103507103508103509103510103511103512103513103514103515103516103517103518103519103520103521103522103523103524103525103526103527103528103529103530103531103532103533103534103535103536103537103538103539103540103541103542103543103544103545103546103547103548103549103550103551103552103553103554103555103556103557103558103559103560103561103562103563103564103565103566103567103568103569103570103571103572103573103574103575103576103577103578103579103580103581103582103583103584103585103586103587103588103589103590103591103592103593103594103595103596103597103598103599103600103601103602103603103604103605103606103607103608103609103610103611103612103613103614103615103616103617103618103619103620103621103622103623103624103625103626103627103628103629103630103631103632103633103634103635103636103637103638103639103640103641103642103643103644103645103646103647103648103649103650103651103652103653103654103655103656103657103658103659103660103661103662103663103664103665103666103667103668103669103670103671103672103673103674103675103676103677103678103679103680103681103682103683103684103685103686103687103688103689103690103691103692103693103694103695103696103697103698103699103700103701103702103703103704103705103706103707103708103709103710103711103712103713103714103715103716103717103718103719103720103721103722103723103724103725103726103727103728103729103730103731103732103733103734103735103736103737103738103739103740103741103742103743103744103745103746103747103748103749103750103751103752103753103754103755103756103757103758103759103760103761103762103763103764103765103766103767103768103769103770103771103772103773103774103775103776103777103778103779103780103781103782103783103784103785103786103787103788103789103790103791103792103793103794103795103796103797103798103799103800103801103802103803103804103805103806103807103808103809103810103811103812103813103814103815103816103817103818103819103820103821103822103823103824103825103826103827103828103829103830103831103832103833103834103835103836103837103838103839103840103841103842103843103844103845103846103847103848103849103850103851103852103853103854103855103856103857103858103859103860103861103862103863103864103865103866103867103868103869103870103871103872103873103874103875103876103877103878103879103880103881103882103883103884103885103886103887103888103889103890103891103892103893103894103895103896103897103898103899103900103901103902103903103904103905103906103907103908103909103910103911103912103913103914103915103916103917103918103919103920103921103922103923103924103925103926103927103928103929103930103931103932103933103934103935103936103937103938103939103940103941103942103943103944103945103946103947103948103949103950103951103952103953103954103955103956103957103958103959103960103961103962103963103964103965103966103967103968103969103970103971103972103973103974103975103976103977103978103979103980103981103982103983103984103985103986103987103988103989103990103991103992103993103994103995103996103997103998103999104000104001104002104003104004104005104006104007104008104009104010104011104012104013104014104015104016104017104018104019104020104021104022104023104024104025104026104027104028104029104030104031104032104033104034104035104036104037104038104039104040104041104042104043104044104045104046104047104048104049104050104051104052104053104054104055104056104057104058104059104060104061104062104063104064104065104066104067104068104069104070104071104072104073104074104075104076104077104078104079104080104081104082104083104084104085104086104087104088104089104090104091104092104093104094104095104096104097104098104099104100104101104102104103104104104105104106104107104108104109104110104111104112104113104114104115104116104117104118104119104120104121104122104123104124104125104126104127104128104129104130104131104132104133104134104135104136104137104138104139104140104141104142104143104144104145104146104147104148104149104150104151104152104153104154104155104156104157104158104159104160104161104162104163104164104165104166104167104168104169104170104171104172104173104174104175104176104177104178104179104180104181104182104183104184104185104186104187104188104189104190104191104192104193104194104195104196104197104198104199104200104201104202104203104204104205104206104207104208104209104210104211104212104213104214104215104216104217104218104219104220104221104222104223104224104225104226104227104228104229104230104231104232104233104234104235104236104237104238104239104240104241104242104243104244104245104246104247104248104249104250104251104252104253104254104255104256104257104258104259104260104261104262104263104264104265104266104267104268104269104270104271104272104273104274104275104276104277104278104279104280104281104282104283104284104285104286104287104288104289104290104291104292104293104294104295104296104297104298104299104300104301104302104303104304104305104306104307104308104309104310104311104312104313104314104315104316104317104318104319104320104321104322104323104324104325104326104327104328104329104330104331104332104333104334104335104336104337104338104339104340104341104342104343104344104345104346104347104348104349104350104351104352104353104354104355104356104357104358104359104360104361104362104363104364104365104366104367104368104369104370104371104372104373104374104375104376104377104378104379104380104381104382104383104384104385104386104387104388104389104390104391104392104393104394104395104396104397104398104399104400104401104402104403104404104405104406104407104408104409104410104411104412104413104414104415104416104417104418104419104420104421104422104423104424104425104426104427104428104429104430104431104432104433104434104435104436104437104438104439104440104441104442104443104444104445104446104447104448104449104450104451104452104453104454104455104456104457104458104459104460104461104462104463104464104465104466104467104468104469104470104471104472104473104474104475104476104477104478104479104480104481104482104483104484104485104486104487104488104489104490104491104492104493104494104495104496104497104498104499104500104501104502104503104504104505104506104507104508104509104510104511104512104513104514104515104516104517104518104519104520104521104522104523104524104525104526104527104528104529104530104531104532104533104534104535104536104537104538104539104540104541104542104543104544104545104546104547104548104549104550104551104552104553104554104555104556104557104558104559104560104561104562104563104564104565104566104567104568104569104570104571104572104573104574104575104576104577104578104579104580104581104582104583104584104585104586104587104588104589104590104591104592104593104594104595104596104597104598104599104600104601104602104603104604104605104606104607104608104609104610104611104612104613104614104615104616104617104618104619104620104621104622104623104624104625104626104627104628104629104630104631104632104633104634104635104636104637104638104639104640104641104642104643104644104645104646104647104648104649104650104651104652104653104654104655104656104657104658104659104660104661104662104663104664104665104666104667104668104669104670104671104672104673104674104675104676104677104678104679104680104681104682104683104684104685104686104687104688104689104690104691104692104693104694104695104696104697104698104699104700104701104702104703104704104705104706104707104708104709104710104711104712104713104714104715104716104717104718104719104720104721104722104723104724104725104726104727104728104729104730104731104732104733104734104735104736104737104738104739104740104741104742104743104744104745104746104747104748104749104750104751104752104753104754104755104756104757104758104759104760104761104762104763104764104765104766104767104768104769104770104771104772104773104774104775104776104777104778104779104780104781104782104783104784104785104786104787104788104789104790104791104792104793104794104795104796104797104798104799104800104801104802104803104804104805104806104807104808104809104810104811104812104813104814104815104816104817104818104819104820104821104822104823104824104825104826104827104828104829104830104831104832104833104834104835104836104837104838104839104840104841104842104843104844104845104846104847104848104849104850104851104852104853104854104855104856104857104858104859104860104861104862104863104864104865104866104867104868104869104870104871104872104873104874104875104876104877104878104879104880104881104882104883104884104885104886104887104888104889104890104891104892104893104894104895104896104897104898104899104900104901104902104903104904104905104906104907104908104909104910104911104912104913104914104915104916104917104918104919104920104921104922104923104924104925104926104927104928104929104930104931104932104933104934104935104936104937104938104939104940104941104942104943104944104945104946104947104948104949104950104951104952104953104954104955104956104957104958104959104960104961104962104963104964104965104966104967104968104969104970104971104972104973104974104975104976104977104978104979104980104981104982104983104984104985104986104987104988104989104990104991104992104993104994104995104996104997104998104999105000105001105002105003105004105005105006105007105008105009105010105011105012105013105014105015105016105017105018105019105020105021105022105023105024105025105026105027105028105029105030105031105032105033105034105035105036105037105038105039105040105041105042105043105044105045105046105047105048105049105050105051105052105053105054105055105056105057105058105059105060105061105062105063105064105065105066105067105068105069105070105071105072105073105074105075105076105077105078105079105080105081105082105083105084105085105086105087105088105089105090105091105092105093105094105095105096105097105098105099105100105101105102105103105104105105105106105107105108105109105110105111105112105113105114105115105116105117105118105119105120105121105122105123105124105125105126105127105128105129105130105131105132105133105134105135105136105137105138105139105140105141105142105143105144105145105146105147105148105149105150105151105152105153105154105155105156105157105158105159105160105161105162105163105164105165105166105167105168105169105170105171105172105173105174105175105176105177105178105179105180105181105182105183105184105185105186105187105188105189105190105191105192105193105194105195105196105197105198105199105200105201105202105203105204105205105206105207105208105209105210105211105212105213105214105215105216105217105218105219105220105221105222105223105224105225105226105227105228105229105230105231105232105233105234105235105236105237105238105239105240105241105242105243105244105245105246105247105248105249105250105251105252105253105254105255105256105257105258105259105260105261105262105263105264105265105266105267105268105269105270105271105272105273105274105275105276105277105278105279105280105281105282105283105284105285105286105287105288105289105290105291105292105293105294105295105296105297105298105299105300105301105302105303105304105305105306105307105308105309105310105311105312105313105314105315105316105317105318105319105320105321105322105323105324105325105326105327105328105329105330105331105332105333105334105335105336105337105338105339105340105341105342105343105344105345105346105347105348105349105350105351105352105353105354105355105356105357105358105359105360105361105362105363105364105365105366105367105368105369105370105371105372105373105374105375105376105377105378105379105380105381105382105383105384105385105386105387105388105389105390105391105392105393105394105395105396105397105398105399105400105401105402105403105404105405105406105407105408105409105410105411105412105413105414105415105416105417105418105419105420105421105422105423105424105425105426105427105428105429105430105431105432105433105434105435105436105437105438105439105440105441105442105443105444105445105446105447105448105449105450105451105452105453105454105455105456105457105458105459105460105461105462105463105464105465105466105467105468105469105470105471105472105473105474105475105476105477105478105479105480105481105482105483105484105485105486105487105488105489105490105491105492105493105494105495105496105497105498105499105500105501105502105503105504105505105506105507105508105509105510105511105512105513105514105515105516105517105518105519105520105521105522105523105524105525105526105527105528105529105530105531105532105533105534105535105536105537105538105539105540105541105542105543105544105545105546105547105548105549105550105551105552105553105554105555105556105557105558105559105560105561105562105563105564105565105566105567105568105569105570105571105572105573105574105575105576105577105578105579105580105581105582105583105584105585105586105587105588105589105590105591105592105593105594105595105596105597105598105599105600105601105602105603105604105605105606105607105608105609105610105611105612105613105614105615105616105617105618105619105620105621105622105623105624105625105626105627105628105629105630105631105632105633105634105635105636105637105638105639105640105641105642105643105644105645105646105647105648105649105650105651105652105653105654105655105656105657105658105659105660105661105662105663105664105665105666105667105668105669105670105671105672105673105674105675105676105677105678105679105680105681105682105683105684105685105686105687105688105689105690105691105692105693105694105695105696105697105698105699105700105701105702105703105704105705105706105707105708105709105710105711105712105713105714105715105716105717105718105719105720105721105722105723105724105725105726105727105728105729105730105731105732105733105734105735105736105737105738105739105740105741105742105743105744105745105746105747105748105749105750105751105752105753105754105755105756105757105758105759105760105761105762105763105764105765105766105767105768105769105770105771105772105773105774105775105776105777105778105779105780105781105782105783105784105785105786105787105788105789105790105791105792105793105794105795105796105797105798105799105800105801105802105803105804105805105806105807105808105809105810105811105812105813105814105815105816105817105818105819105820105821105822105823105824105825105826105827105828105829105830105831105832105833105834105835105836105837105838105839105840105841105842105843105844105845105846105847105848105849105850105851105852105853105854105855105856105857105858105859105860105861105862105863105864105865105866105867105868105869105870105871105872105873105874105875105876105877105878105879105880105881105882105883105884105885105886105887105888105889105890105891105892105893105894105895105896105897105898105899105900105901105902105903105904105905105906105907105908105909105910105911105912105913105914105915105916105917105918105919105920105921105922105923105924105925105926105927105928105929105930105931105932105933105934105935105936105937105938105939105940105941105942105943105944105945105946105947105948105949105950105951105952105953105954105955105956105957105958105959105960105961105962105963105964105965105966105967105968105969105970105971105972105973105974105975105976105977105978105979105980105981105982105983105984105985105986105987105988105989105990105991105992105993105994105995105996105997105998105999106000106001106002106003106004106005106006106007106008106009106010106011106012106013106014106015106016106017106018106019106020106021106022106023106024106025106026106027106028106029106030106031106032106033106034106035106036106037106038106039106040106041106042106043106044106045106046106047106048106049106050106051106052106053106054106055106056106057106058106059106060106061106062106063106064106065106066106067106068106069106070106071106072106073106074106075106076106077106078106079106080106081106082106083106084106085106086106087106088106089106090106091106092106093106094106095106096106097106098106099106100106101106102106103106104106105106106106107106108106109106110106111106112106113106114106115106116106117106118106119106120106121106122106123106124106125106126106127106128106129106130106131106132106133106134106135106136106137106138106139106140106141106142106143106144106145106146106147106148106149106150106151106152106153106154106155106156106157106158106159106160106161106162106163106164106165106166106167106168106169106170106171106172106173106174106175106176106177106178106179106180106181106182106183106184106185106186106187106188106189106190106191106192106193106194106195106196106197106198106199106200106201106202106203106204106205106206106207106208106209106210106211106212106213106214106215106216106217106218106219106220106221106222106223106224106225106226106227106228106229106230106231106232106233106234106235106236106237106238106239106240106241106242106243106244106245106246106247106248106249106250106251106252106253106254106255106256106257106258106259106260106261106262106263106264106265106266106267106268106269106270106271106272106273106274106275106276106277106278106279106280106281106282106283106284106285106286106287106288106289106290106291106292106293106294106295106296106297106298106299106300106301106302106303106304106305106306106307106308106309106310106311106312106313106314106315106316106317106318106319106320106321106322106323106324106325106326106327106328106329106330106331106332106333106334106335106336106337106338106339106340106341106342106343106344106345106346106347106348106349106350106351106352106353106354106355106356106357106358106359106360106361106362106363106364106365106366106367106368106369106370106371106372106373106374106375106376106377106378106379106380106381106382106383106384106385106386106387106388106389106390106391106392106393106394106395106396106397106398106399106400106401106402106403106404106405106406106407106408106409106410106411106412106413106414106415106416106417106418106419106420106421106422106423106424106425106426106427106428106429106430106431106432106433106434106435106436106437106438106439106440106441106442106443106444106445106446106447106448106449106450106451106452106453106454106455106456106457106458106459106460106461106462106463106464106465106466106467106468106469106470106471106472106473106474106475106476106477106478106479106480106481106482106483106484106485106486106487106488106489106490106491106492106493106494106495106496106497106498106499106500106501106502106503106504106505106506106507106508106509106510106511106512106513106514106515106516106517106518106519106520106521106522106523106524106525106526106527106528106529106530106531106532106533106534106535106536106537106538106539106540106541106542106543106544106545106546106547106548106549106550106551106552106553106554106555106556106557106558106559106560106561106562106563106564106565106566106567106568106569106570106571106572106573106574106575106576106577106578106579106580106581106582106583106584106585106586106587106588106589106590106591106592106593106594106595106596106597106598106599106600106601106602106603106604106605106606106607106608106609106610106611106612106613106614106615106616106617106618106619106620106621106622106623106624106625106626106627106628106629106630106631106632106633106634106635106636106637106638106639106640106641106642106643106644106645106646106647106648106649106650106651106652106653106654106655106656106657106658106659106660106661106662106663106664106665106666106667106668106669106670106671106672106673106674106675106676106677106678106679106680106681106682106683106684106685106686106687106688106689106690106691106692106693106694106695106696106697106698106699106700106701106702106703106704106705106706106707106708106709106710106711106712106713106714106715106716106717106718106719106720106721106722106723106724106725106726106727106728106729106730106731106732106733106734106735106736106737106738106739106740106741106742106743106744106745106746106747106748106749106750106751106752106753106754106755106756106757106758106759106760106761106762106763106764106765106766106767106768106769106770106771106772106773106774106775106776106777106778106779106780106781106782106783106784106785106786106787106788106789106790106791106792106793106794106795106796106797106798106799106800106801106802106803106804106805106806106807106808106809106810106811106812106813106814106815106816106817106818106819106820106821106822106823106824106825106826106827106828106829106830106831106832106833106834106835106836106837106838106839106840106841106842106843106844106845106846106847106848106849106850106851106852106853106854106855106856106857106858106859106860106861106862106863106864106865106866106867106868106869106870106871106872106873106874106875106876106877106878106879106880106881106882106883106884106885106886106887106888106889106890106891106892106893106894106895106896106897106898106899106900106901106902106903106904106905106906106907106908106909106910106911106912106913106914106915106916106917106918106919106920106921106922106923106924106925106926106927106928106929106930106931106932106933106934106935106936106937106938106939106940106941106942106943106944106945106946106947106948106949106950106951106952106953106954106955106956106957106958106959106960106961106962106963106964106965106966106967106968106969106970106971106972106973106974106975106976106977106978106979106980106981106982106983106984106985106986106987106988106989106990106991106992106993106994106995106996106997106998106999107000107001107002107003107004107005107006107007107008107009107010107011107012107013107014107015107016107017107018107019107020107021107022107023107024107025107026107027107028107029107030107031107032107033107034107035107036107037107038107039107040107041107042107043107044107045107046107047107048107049107050107051107052107053107054107055107056107057107058107059107060107061107062107063107064107065107066107067107068107069107070107071107072107073107074107075107076107077107078107079107080107081107082107083107084107085107086107087107088107089107090107091107092107093107094107095107096107097107098107099107100107101107102107103107104107105107106107107107108107109107110107111107112107113107114107115107116107117107118107119107120107121107122107123107124107125107126107127107128107129107130107131107132107133107134107135107136107137107138107139107140107141107142107143107144107145107146107147107148107149107150107151107152107153107154107155107156107157107158107159107160107161107162107163107164107165107166107167107168107169107170107171107172107173107174107175107176107177107178107179107180107181107182107183107184107185107186107187107188107189107190107191107192107193107194107195107196107197107198107199107200107201107202107203107204107205107206107207107208107209107210107211107212107213107214107215107216107217107218107219107220107221107222107223107224107225107226107227107228107229107230107231107232107233107234107235107236107237107238107239107240107241107242107243107244107245107246107247107248107249107250107251107252107253107254107255107256107257107258107259107260107261107262107263107264107265107266107267107268107269107270107271107272107273107274107275107276107277107278107279107280107281107282107283107284107285107286107287107288107289107290107291107292107293107294107295107296107297107298107299107300107301107302107303107304107305107306107307107308107309107310107311107312107313107314107315107316107317107318107319107320107321107322107323107324107325107326107327107328107329107330107331107332107333107334107335107336107337107338107339107340107341107342107343107344107345107346107347107348107349107350107351107352107353107354107355107356107357107358107359107360107361107362107363107364107365107366107367107368107369107370107371107372107373107374107375107376107377107378107379107380107381107382107383107384107385107386107387107388107389107390107391107392107393107394107395107396107397107398107399107400107401107402107403107404107405107406107407107408107409107410107411107412107413107414107415107416107417107418107419107420107421107422107423107424107425107426107427107428107429107430107431107432107433107434107435107436107437107438107439107440107441107442107443107444107445107446107447107448107449107450107451107452107453107454107455107456107457107458107459107460107461107462107463107464107465107466107467107468107469107470107471107472107473107474107475107476107477107478107479107480107481107482107483107484107485107486107487107488107489107490107491107492107493107494107495107496107497107498107499107500107501107502107503107504107505107506107507107508107509107510107511107512107513107514107515107516107517107518107519107520107521107522107523107524107525107526107527107528107529107530107531107532107533107534107535107536107537107538107539107540107541107542107543107544107545107546107547107548107549107550107551107552107553107554107555107556107557107558107559107560107561107562107563107564107565107566107567107568107569107570107571107572107573107574107575107576107577107578107579107580107581107582107583107584107585107586107587107588107589107590107591107592107593107594107595107596107597107598107599107600107601107602107603107604107605107606107607107608107609107610107611107612107613107614107615107616107617107618107619107620107621107622107623107624107625107626107627107628107629107630107631107632107633107634107635107636107637107638107639107640107641107642107643107644107645107646107647107648107649107650107651107652107653107654107655107656107657107658107659107660107661107662107663107664107665107666107667107668107669107670107671107672107673107674107675107676107677107678107679107680107681107682107683107684107685107686107687107688107689107690107691107692107693107694107695107696107697107698107699107700107701107702107703107704107705107706107707107708107709107710107711107712107713107714107715107716107717107718107719107720107721107722107723107724107725107726107727107728107729107730107731107732107733107734107735107736107737107738107739107740107741107742107743107744107745107746107747107748107749107750107751107752107753107754107755107756107757107758107759107760107761107762107763107764107765107766107767107768107769107770107771107772107773107774107775107776107777107778107779107780107781107782107783107784107785107786107787107788107789107790107791107792107793107794107795107796107797107798107799107800107801107802107803107804107805107806107807107808107809107810107811107812107813107814107815107816107817107818107819107820107821107822107823107824107825107826107827107828107829107830107831107832107833107834107835107836107837107838107839107840107841107842107843107844107845107846107847107848107849107850107851107852107853107854107855107856107857107858107859107860107861107862107863107864107865107866107867107868107869107870107871107872107873107874107875107876107877107878107879107880107881107882107883107884107885107886107887107888107889107890107891107892107893107894107895107896107897107898107899107900107901107902107903107904107905107906107907107908107909107910107911107912107913107914107915107916107917107918107919107920107921107922107923107924107925107926107927107928107929107930107931107932107933107934107935107936107937107938107939107940107941107942107943107944107945107946107947107948107949107950107951107952107953107954107955107956107957107958107959107960107961107962107963107964107965107966107967107968107969107970107971107972107973107974107975107976107977107978107979107980107981107982107983107984107985107986107987107988107989107990107991107992107993107994107995107996107997107998107999108000108001108002108003108004108005108006108007108008108009108010108011108012108013108014108015108016108017108018108019108020108021108022108023108024108025108026108027108028108029108030108031108032108033108034108035108036108037108038108039108040108041108042108043108044108045108046108047108048108049108050108051108052108053108054108055108056108057108058108059108060108061108062108063108064108065108066108067108068108069108070108071108072108073108074108075108076108077108078108079108080108081108082108083108084108085108086108087108088108089108090108091108092108093108094108095108096108097108098108099108100108101108102108103108104108105108106108107108108108109108110108111108112108113108114108115108116108117108118108119108120108121108122108123108124108125108126108127108128108129108130108131108132108133108134108135108136108137108138108139108140108141108142108143108144108145108146108147108148108149108150108151108152108153108154108155108156108157108158108159108160108161108162108163108164108165108166108167108168108169108170108171108172108173108174108175108176108177108178108179108180108181108182108183108184108185108186108187108188108189108190108191108192108193108194108195108196108197108198108199108200108201108202108203108204108205108206108207108208108209108210108211108212108213108214108215108216108217108218108219108220108221108222108223108224108225108226108227108228108229108230108231108232108233108234108235108236108237108238108239108240108241108242108243108244108245108246108247108248108249108250108251108252108253108254108255108256108257108258108259108260108261108262108263108264108265108266108267108268108269108270108271108272108273108274108275108276108277108278108279108280108281108282108283108284108285108286108287108288108289108290108291108292108293108294108295108296108297108298108299108300108301108302108303108304108305108306108307108308108309108310108311108312108313108314108315108316108317108318108319108320108321108322108323108324108325108326108327108328108329108330108331108332108333108334108335108336108337108338108339108340108341108342108343108344108345108346108347108348108349108350108351108352108353108354108355108356108357108358108359108360108361108362108363108364108365108366108367108368108369108370108371108372108373108374108375108376108377108378108379108380108381108382108383108384108385108386108387108388108389108390108391108392108393108394108395108396108397108398108399108400108401108402108403108404108405108406108407108408108409108410108411108412108413108414108415108416108417108418108419108420108421108422108423108424108425108426108427108428108429108430108431108432108433108434108435108436108437108438108439108440108441108442108443108444108445108446108447108448108449108450108451108452108453108454108455108456108457108458108459108460108461108462108463108464108465108466108467108468108469108470108471108472108473108474108475108476108477108478108479108480108481108482108483108484108485108486108487108488108489108490108491108492108493108494108495108496108497108498108499108500108501108502108503108504108505108506108507108508108509108510108511108512108513108514108515108516108517108518108519108520108521108522108523108524108525108526108527108528108529108530108531108532108533108534108535108536108537108538108539108540108541108542108543108544108545108546108547108548108549108550108551108552108553108554108555108556108557108558108559108560108561108562108563108564108565108566108567108568108569108570108571108572108573108574108575108576108577108578108579108580108581108582108583108584108585108586108587108588108589108590108591108592108593108594108595108596108597108598108599108600108601108602108603108604108605108606108607108608108609108610108611108612108613108614108615108616108617108618108619108620108621108622108623108624108625108626108627108628108629108630108631108632108633108634108635108636108637108638108639108640108641108642108643108644108645108646108647108648108649108650108651108652108653108654108655108656108657108658108659108660108661108662108663108664108665108666108667108668108669108670108671108672108673108674108675108676108677108678108679108680108681108682108683108684108685108686108687108688108689108690108691108692108693108694108695108696108697108698108699108700108701108702108703108704108705108706108707108708108709108710108711108712108713108714108715108716108717108718108719108720108721108722108723108724108725108726108727108728108729108730108731108732108733108734108735108736108737108738108739108740108741108742108743108744108745108746108747108748108749108750108751108752108753108754108755108756108757108758108759108760108761108762108763108764108765108766108767108768108769108770108771108772108773108774108775108776108777108778108779108780108781108782108783108784108785108786108787108788108789108790108791108792108793108794108795108796108797108798108799108800108801108802108803108804108805108806108807108808108809108810108811108812108813108814108815108816108817108818108819108820108821108822108823108824108825108826108827108828108829108830108831108832108833108834108835108836108837108838108839108840108841108842108843108844108845108846108847108848108849108850108851108852108853108854108855108856108857108858108859108860108861108862108863108864108865108866108867108868108869108870108871108872108873108874108875108876108877108878108879108880108881108882108883108884108885108886108887108888108889108890108891108892108893108894108895108896108897108898108899108900108901108902108903108904108905108906108907108908108909108910108911108912108913108914108915108916108917108918108919108920108921108922108923108924108925108926108927108928108929108930108931108932108933108934108935108936108937108938108939108940108941108942108943108944108945108946108947108948108949108950108951108952108953108954108955108956108957108958108959108960108961108962108963108964108965108966108967108968108969108970108971108972108973108974108975108976108977108978108979108980108981108982108983108984108985108986108987108988108989108990108991108992108993108994108995108996108997108998108999109000109001109002109003109004109005109006109007109008109009109010109011109012109013109014109015109016109017109018109019109020109021109022109023109024109025109026109027109028109029109030109031109032109033109034109035109036109037109038109039109040109041109042109043109044109045109046109047109048109049109050109051109052109053109054109055109056109057109058109059109060109061109062109063109064109065109066109067109068109069109070109071109072109073109074109075109076109077109078109079109080109081109082109083109084109085109086109087109088109089109090109091109092109093109094109095109096109097109098109099109100109101109102109103109104109105109106109107109108109109109110109111109112109113109114109115109116109117109118109119109120109121109122109123109124109125109126109127109128109129109130109131109132109133109134109135109136109137109138109139109140109141109142109143109144109145109146109147109148109149109150109151109152109153109154109155109156109157109158109159109160109161109162109163109164109165109166109167109168109169109170109171109172109173109174109175109176109177109178109179109180109181109182109183109184109185109186109187109188109189109190109191109192109193109194109195109196109197109198109199109200109201109202109203109204109205109206109207109208109209109210109211109212109213109214109215109216109217109218109219109220109221109222109223109224109225109226109227109228109229109230109231109232109233109234109235109236109237109238109239109240109241109242109243109244109245109246109247109248109249109250109251109252109253109254109255109256109257109258109259109260109261109262109263109264109265109266109267109268109269109270109271109272109273109274109275109276109277109278109279109280109281109282109283109284109285109286109287109288109289109290109291109292109293109294109295109296109297109298109299109300109301109302109303109304109305109306109307109308109309109310109311109312109313109314109315109316109317109318109319109320109321109322109323109324109325109326109327109328109329109330109331109332109333109334109335109336109337109338109339109340109341109342109343109344109345109346109347109348109349109350109351109352109353109354109355109356109357109358109359109360109361109362109363109364109365109366109367109368109369109370109371109372109373109374109375109376109377109378109379109380109381109382109383109384109385109386109387109388109389109390109391109392109393109394109395109396109397109398109399109400109401109402109403109404109405109406109407109408109409109410109411109412109413109414109415109416109417109418109419109420109421109422109423109424109425109426109427109428109429109430109431109432109433109434109435109436109437109438109439109440109441109442109443109444109445109446109447109448109449109450109451109452109453109454109455109456109457109458109459109460109461109462109463109464109465109466109467109468109469109470109471109472109473109474109475109476109477109478109479109480109481109482109483109484109485109486109487109488109489109490109491109492109493109494109495109496109497109498109499109500109501109502109503109504109505109506109507109508109509109510109511109512109513109514109515109516109517109518109519109520109521109522109523109524109525109526109527109528109529109530109531109532109533109534109535109536109537109538109539109540109541109542109543109544109545109546109547109548109549109550109551109552109553109554109555109556109557109558109559109560109561109562109563109564109565109566109567109568109569109570109571109572109573109574109575109576109577109578109579109580109581109582109583109584109585109586109587109588109589109590109591109592109593109594109595109596109597109598109599109600109601109602109603109604109605109606109607109608109609109610109611109612109613109614109615109616109617109618109619109620109621109622109623109624109625109626109627109628109629109630109631109632109633109634109635109636109637109638109639109640109641109642109643109644109645109646109647109648109649109650109651109652109653109654109655109656109657109658109659109660109661109662109663109664109665109666109667109668109669109670109671109672109673109674109675109676109677109678109679109680109681109682109683109684109685109686109687109688109689109690109691109692109693109694109695109696109697109698109699109700109701109702109703109704109705109706109707109708109709109710109711109712109713109714109715109716109717109718109719109720109721109722109723109724109725109726109727109728109729109730109731109732109733109734109735109736109737109738109739109740109741109742109743109744109745109746109747109748109749109750109751109752109753109754109755109756109757109758109759109760109761109762109763109764109765109766109767109768109769109770109771109772109773109774109775109776109777109778109779109780109781109782109783109784109785109786109787109788109789109790109791109792109793109794109795109796109797109798109799109800109801109802109803109804109805109806109807109808109809109810109811109812109813109814109815109816109817109818109819109820109821109822109823109824109825109826109827109828109829109830109831109832109833109834109835109836109837109838109839109840109841109842109843109844109845109846109847109848109849109850109851109852109853109854109855109856109857109858109859109860109861109862109863109864109865109866109867109868109869109870109871109872109873109874109875109876109877109878109879109880109881109882109883109884109885109886109887109888109889109890109891109892109893109894109895109896109897109898109899109900109901109902109903109904109905109906109907109908109909109910109911109912109913109914109915109916109917109918109919109920109921109922109923109924109925109926109927109928109929109930109931109932109933109934109935109936109937109938109939109940109941109942109943109944109945109946109947109948109949109950109951109952109953109954109955109956109957109958109959109960109961109962109963109964109965109966109967109968109969109970109971109972109973109974109975109976109977109978109979109980109981109982109983109984109985109986109987109988109989109990109991109992109993109994109995109996109997109998109999110000110001110002110003110004110005110006110007110008110009110010110011110012110013110014110015110016110017110018110019110020110021110022110023110024110025110026110027110028110029110030110031110032110033110034110035110036110037110038110039110040110041110042110043110044110045110046110047110048110049110050110051110052110053110054110055110056110057110058110059110060110061110062110063110064110065110066110067110068110069110070110071110072110073110074110075110076110077110078110079110080110081110082110083110084110085110086110087110088110089110090110091110092110093110094110095110096110097110098110099110100110101110102110103110104110105110106110107110108110109110110110111110112110113110114110115110116110117110118110119110120110121110122110123110124110125110126110127110128110129110130110131110132110133110134110135110136110137110138110139110140110141110142110143110144110145110146110147110148110149110150110151110152110153110154110155110156110157110158110159110160110161110162110163110164110165110166110167110168110169110170110171110172110173110174110175110176110177110178110179110180110181110182110183110184110185110186110187110188110189110190110191110192110193110194110195110196110197110198110199110200110201110202110203110204110205110206110207110208110209110210110211110212110213110214110215110216110217110218110219110220110221110222110223110224110225110226110227110228110229110230110231110232110233110234110235110236110237110238110239110240110241110242110243110244110245110246110247110248110249110250110251110252110253110254110255110256110257110258110259110260110261110262110263110264110265110266110267110268110269110270110271110272110273110274110275110276110277110278110279110280110281110282110283110284110285110286110287110288110289110290110291110292110293110294110295110296110297110298110299110300110301110302110303110304110305110306110307110308110309110310110311110312110313110314110315110316110317110318110319110320110321110322110323110324110325110326110327110328110329110330110331110332110333110334110335110336110337110338110339110340110341110342110343110344110345110346110347110348110349110350110351110352110353110354110355110356110357110358110359110360110361110362110363110364110365110366110367110368110369110370110371110372110373110374110375110376110377110378110379110380110381110382110383110384110385110386110387110388110389110390110391110392110393110394110395110396110397110398110399110400110401110402110403110404110405110406110407110408110409110410110411110412110413110414110415110416110417110418110419110420110421110422110423110424110425110426110427110428110429110430110431110432110433110434110435110436110437110438110439110440110441110442110443110444110445110446110447110448110449110450110451110452110453110454110455110456110457110458110459110460110461110462110463110464110465110466110467110468110469110470110471110472110473110474110475110476110477110478110479110480110481110482110483110484110485110486110487110488110489110490110491110492110493110494110495110496110497110498110499110500110501110502110503110504110505110506110507110508110509110510110511110512110513110514110515110516110517110518110519110520110521110522110523110524110525110526110527110528110529110530110531110532110533110534110535110536110537110538110539110540110541110542110543110544110545110546110547110548110549110550110551110552110553110554110555110556110557110558110559110560110561110562110563110564110565110566110567110568110569110570110571110572110573110574110575110576110577110578110579110580110581110582110583110584110585110586110587110588110589110590110591110592110593110594110595110596110597110598110599110600110601110602110603110604110605110606110607110608110609110610110611110612110613110614110615110616110617110618110619110620110621110622110623110624110625110626110627110628110629110630110631110632110633110634110635110636110637110638110639110640110641110642110643110644110645110646110647110648110649110650110651110652110653110654110655110656110657110658110659110660110661110662110663110664110665110666110667110668110669110670110671110672110673110674110675110676110677110678110679110680110681110682110683110684110685110686110687110688110689110690110691110692110693110694110695110696110697110698110699110700110701110702110703110704110705110706110707110708110709110710110711110712110713110714110715110716110717110718110719110720110721110722110723110724110725110726110727110728110729110730110731110732110733110734110735110736110737110738110739110740110741110742110743110744110745110746110747110748110749110750110751110752110753110754110755110756110757110758110759110760110761110762110763110764110765110766110767110768110769110770110771110772110773110774110775110776110777110778110779110780110781110782110783110784110785110786110787110788110789110790110791110792110793110794110795110796110797110798110799110800110801110802110803110804110805110806110807110808110809110810110811110812110813110814110815110816110817110818110819110820110821110822110823110824110825110826110827110828110829110830110831110832110833110834110835110836110837110838110839110840110841110842110843110844110845110846110847110848110849110850110851110852110853110854110855110856110857110858110859110860110861110862110863110864110865110866110867110868110869110870110871110872110873110874110875110876110877110878110879110880110881110882110883110884110885110886110887110888110889110890110891110892110893110894110895110896110897110898110899110900110901110902110903110904110905110906110907110908110909110910110911110912110913110914110915110916110917110918110919110920110921110922110923110924110925110926110927110928110929110930110931110932110933110934110935110936110937110938110939110940110941110942110943110944110945110946110947110948110949110950110951110952110953110954110955110956110957110958110959110960110961110962110963110964110965110966110967110968110969110970110971110972110973110974110975110976110977110978110979110980110981110982110983110984110985110986110987110988110989110990110991110992110993110994110995110996110997110998110999111000111001111002111003111004111005111006111007111008111009111010111011111012111013111014111015111016111017111018111019111020111021111022111023111024111025111026111027111028111029111030111031111032111033111034111035111036111037111038111039111040111041111042111043111044111045111046111047111048111049111050111051111052111053111054111055111056111057111058111059111060111061111062111063111064111065111066111067111068111069111070111071111072111073111074111075111076111077111078111079111080111081111082111083111084111085111086111087111088111089111090111091111092111093111094111095111096111097111098111099111100111101111102111103111104111105111106111107111108111109111110111111111112111113111114111115111116111117111118111119111120111121111122111123111124111125111126111127111128111129111130111131111132111133111134111135111136111137111138111139111140111141111142111143111144111145111146111147111148111149111150111151111152111153111154111155111156111157111158111159111160111161111162111163111164111165111166111167111168111169111170111171111172111173111174111175111176111177111178111179111180111181111182111183111184111185111186111187111188111189111190111191111192111193111194111195111196111197111198111199111200111201111202111203111204111205111206111207111208111209111210111211111212111213111214111215111216111217111218111219111220111221111222111223111224111225111226111227111228111229111230111231111232111233111234111235111236111237111238111239111240111241111242111243111244111245111246111247111248111249111250111251111252111253111254111255111256111257111258111259111260111261111262111263111264111265111266111267111268111269111270111271111272111273111274111275111276111277111278111279111280111281111282111283111284111285111286111287111288111289111290111291111292111293111294111295111296111297111298111299111300111301111302111303111304111305111306111307111308111309111310111311111312111313111314111315111316111317111318111319111320111321111322111323111324111325111326111327111328111329111330111331111332111333111334111335111336111337111338111339111340111341111342111343111344111345111346111347111348111349111350111351111352111353111354111355111356111357111358111359111360111361111362111363111364111365111366111367111368111369111370111371111372111373111374111375111376111377111378111379111380111381111382111383111384111385111386111387111388111389111390111391111392111393111394111395111396111397111398111399111400111401111402111403111404111405111406111407111408111409111410111411111412111413111414111415111416111417111418111419111420111421111422111423111424111425111426111427111428111429111430111431111432111433111434111435111436111437111438111439111440111441111442111443111444111445111446111447111448111449111450111451111452111453111454111455111456111457111458111459111460111461111462111463111464111465111466111467111468111469111470111471111472111473111474111475111476111477111478111479111480111481111482111483111484111485111486111487111488111489111490111491111492111493111494111495111496111497111498111499111500111501111502111503111504111505111506111507111508111509111510111511111512111513111514111515111516111517111518111519111520111521111522111523111524111525111526111527111528111529111530111531111532111533111534111535111536111537111538111539111540111541111542111543111544111545111546111547111548111549111550111551111552111553111554111555111556111557111558111559111560111561111562111563111564111565111566111567111568111569111570111571111572111573111574111575111576111577111578111579111580111581111582111583111584111585111586111587111588111589111590111591111592111593111594111595111596111597111598111599111600111601111602111603111604111605111606111607111608111609111610111611111612111613111614111615111616111617111618111619111620111621111622111623111624111625111626111627111628111629111630111631111632111633111634111635111636111637111638111639111640111641111642111643111644111645111646111647111648111649111650111651111652111653111654111655111656111657111658111659111660111661111662111663111664111665111666111667111668111669111670111671111672111673111674111675111676111677111678111679111680111681111682111683111684111685111686111687111688111689111690111691111692111693111694111695111696111697111698111699111700111701111702111703111704111705111706111707111708111709111710111711111712111713111714111715111716111717111718111719111720111721111722111723111724111725111726111727111728111729111730111731111732111733111734111735111736111737111738111739111740111741111742111743111744111745111746111747111748111749111750111751111752111753111754111755111756111757111758111759111760111761111762111763111764111765111766111767111768111769111770111771111772111773111774111775111776111777111778111779111780111781111782111783111784111785111786111787111788111789111790111791111792111793111794111795111796111797111798111799111800111801111802111803111804111805111806111807111808111809111810111811111812111813111814111815111816111817111818111819111820111821111822111823111824111825111826111827111828111829111830111831111832111833111834111835111836111837111838111839111840111841111842111843111844111845111846111847111848111849111850111851111852111853111854111855111856111857111858111859111860111861111862111863111864111865111866111867111868111869111870111871111872111873111874111875111876111877111878111879111880111881111882111883111884111885111886111887111888111889111890111891111892111893111894111895111896111897111898111899111900111901111902111903111904111905111906111907111908111909111910111911111912111913111914111915111916111917111918111919111920111921111922111923111924111925111926111927111928111929111930111931111932111933111934111935111936111937111938111939111940111941111942111943111944111945111946111947111948111949111950111951111952111953111954111955111956111957111958111959111960111961111962111963111964111965111966111967111968111969111970111971111972111973111974111975111976111977111978111979111980111981111982111983111984111985111986111987111988111989111990111991111992111993111994111995111996111997111998111999112000112001112002112003112004112005112006112007112008112009112010112011112012112013112014112015112016112017112018112019112020112021112022112023112024112025112026112027112028112029112030112031112032112033112034112035112036112037112038112039112040112041112042112043112044112045112046112047112048112049112050112051112052112053112054112055112056112057112058112059112060112061112062112063112064112065112066112067112068112069112070112071112072112073112074112075112076112077112078112079112080112081112082112083112084112085112086112087112088112089112090112091112092112093112094112095112096112097112098112099112100112101112102112103112104112105112106112107112108112109112110112111112112112113112114112115112116112117112118112119112120112121112122112123112124112125112126112127112128112129112130112131112132112133112134112135112136112137112138112139112140112141112142112143112144112145112146112147112148112149112150112151112152112153112154112155112156112157112158112159112160112161112162112163112164112165112166112167112168112169112170112171112172112173112174112175112176112177112178112179112180112181112182112183112184112185112186112187112188112189112190112191112192112193112194112195112196112197112198112199112200112201112202112203112204112205112206112207112208112209112210112211112212112213112214112215112216112217112218112219112220112221112222112223112224112225112226112227112228112229112230112231112232112233112234112235112236112237112238112239112240112241112242112243112244112245112246112247112248112249112250112251112252112253112254112255112256112257112258112259112260112261112262112263112264112265112266112267112268112269112270112271112272112273112274112275112276112277112278112279112280112281112282112283112284112285112286112287112288112289112290112291112292112293112294112295112296112297112298112299112300112301112302112303112304112305112306112307112308112309112310112311112312112313112314112315112316112317112318112319112320112321112322112323112324112325112326112327112328112329112330112331112332112333112334112335112336112337112338112339112340112341112342112343112344112345112346112347112348112349112350112351112352112353112354112355112356112357112358112359112360112361112362112363112364112365112366112367112368112369112370112371112372112373112374112375112376112377112378112379112380112381112382112383112384112385112386112387112388112389112390112391112392112393112394112395112396112397112398112399112400112401112402112403112404112405112406112407112408112409112410112411112412112413112414112415112416112417112418112419112420112421112422112423112424112425112426112427112428112429112430112431112432112433112434112435112436112437112438112439112440112441112442112443112444112445112446112447112448112449112450112451112452112453112454112455112456112457112458112459112460112461112462112463112464112465112466112467112468112469112470112471112472112473112474112475112476112477112478112479112480112481112482112483112484112485112486112487112488112489112490112491112492112493112494112495112496112497112498112499112500112501112502112503112504112505112506112507112508112509112510112511112512112513112514112515112516112517112518112519112520112521112522112523112524112525112526112527112528112529112530112531112532112533112534112535112536112537112538112539112540112541112542112543112544112545112546112547112548112549112550112551112552112553112554112555112556112557112558112559112560112561112562112563112564112565112566112567112568112569112570112571112572112573112574112575112576112577112578112579112580112581112582112583112584112585112586112587112588112589112590112591112592112593112594112595112596112597112598112599112600112601112602112603112604112605112606112607112608112609112610112611112612112613112614112615112616112617112618112619112620112621112622112623112624112625112626112627112628112629112630112631112632112633112634112635112636112637112638112639112640112641112642112643112644112645112646112647112648112649112650112651112652112653112654112655112656112657112658112659112660112661112662112663112664112665112666112667112668112669112670112671112672112673112674112675112676112677112678112679112680112681112682112683112684112685112686112687112688112689112690112691112692112693112694112695112696112697112698112699112700112701112702112703112704112705112706112707112708112709112710112711112712112713112714112715112716112717112718112719112720112721112722112723112724112725112726112727112728112729112730112731112732112733112734112735112736112737112738112739112740112741112742112743112744112745112746112747112748112749112750112751112752112753112754112755112756112757112758112759112760112761112762112763112764112765112766112767112768112769112770112771112772112773112774112775112776112777112778112779112780112781112782112783112784112785112786112787112788112789112790112791112792112793112794112795112796112797112798112799112800112801112802112803112804112805112806112807112808112809112810112811112812112813112814112815112816112817112818112819112820112821112822112823112824112825112826112827112828112829112830112831112832112833112834112835112836112837112838112839112840112841112842112843112844112845112846112847
  1. (function universalModuleDefinition(root, factory) {
  2. if(typeof exports === 'object' && typeof module === 'object')
  3. module.exports = factory();
  4. else if(typeof define === 'function' && define.amd)
  5. define("babylonjs-viewer", [], factory);
  6. else if(typeof exports === 'object')
  7. exports["babylonjs-viewer"] = factory();
  8. else {
  9. root["BabylonViewer"] = factory(root["BABYLON"]);
  10. }
  11. })(this, function() {
  12. var BabylonViewer =
  13. /******/ (function(modules) { // webpackBootstrap
  14. /******/ // The module cache
  15. /******/ var installedModules = {};
  16. /******/
  17. /******/ // The require function
  18. /******/ function __webpack_require__(moduleId) {
  19. /******/
  20. /******/ // Check if module is in cache
  21. /******/ if(installedModules[moduleId]) {
  22. /******/ return installedModules[moduleId].exports;
  23. /******/ }
  24. /******/ // Create a new module (and put it into the cache)
  25. /******/ var module = installedModules[moduleId] = {
  26. /******/ i: moduleId,
  27. /******/ l: false,
  28. /******/ exports: {}
  29. /******/ };
  30. /******/
  31. /******/ // Execute the module function
  32. /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
  33. /******/
  34. /******/ // Flag the module as loaded
  35. /******/ module.l = true;
  36. /******/
  37. /******/ // Return the exports of the module
  38. /******/ return module.exports;
  39. /******/ }
  40. /******/
  41. /******/
  42. /******/ // expose the modules object (__webpack_modules__)
  43. /******/ __webpack_require__.m = modules;
  44. /******/
  45. /******/ // expose the module cache
  46. /******/ __webpack_require__.c = installedModules;
  47. /******/
  48. /******/ // define getter function for harmony exports
  49. /******/ __webpack_require__.d = function(exports, name, getter) {
  50. /******/ if(!__webpack_require__.o(exports, name)) {
  51. /******/ Object.defineProperty(exports, name, {
  52. /******/ configurable: false,
  53. /******/ enumerable: true,
  54. /******/ get: getter
  55. /******/ });
  56. /******/ }
  57. /******/ };
  58. /******/
  59. /******/ // getDefaultExport function for compatibility with non-harmony modules
  60. /******/ __webpack_require__.n = function(module) {
  61. /******/ var getter = module && module.__esModule ?
  62. /******/ function getDefault() { return module['default']; } :
  63. /******/ function getModuleExports() { return module; };
  64. /******/ __webpack_require__.d(getter, 'a', getter);
  65. /******/ return getter;
  66. /******/ };
  67. /******/
  68. /******/ // Object.prototype.hasOwnProperty.call
  69. /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
  70. /******/
  71. /******/ // __webpack_public_path__
  72. /******/ __webpack_require__.p = "";
  73. /******/
  74. /******/ // Load entry module and return exports
  75. /******/ return __webpack_require__(__webpack_require__.s = 14);
  76. /******/ })
  77. /************************************************************************/
  78. /******/ ([
  79. /* 0 */
  80. /***/ (function(module, exports, __webpack_require__) {
  81. /* WEBPACK VAR INJECTION */(function(global) {var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  82. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  83. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  84. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  85. return c > 3 && r && Object.defineProperty(target, key, r), r;
  86. };
  87. var __extends = (this && this.__extends) || (function () {
  88. var extendStatics = Object.setPrototypeOf ||
  89. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  90. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  91. return function (d, b) {
  92. extendStatics(d, b);
  93. function __() { this.constructor = d; }
  94. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  95. };
  96. })();
  97. (function universalModuleDefinition(root, factory) {
  98. if(true)
  99. module.exports = factory();
  100. else if(typeof define === 'function' && define.amd)
  101. define("babylonjs", [], factory);
  102. else if(typeof exports === 'object')
  103. exports["babylonjs"] = factory();
  104. else {
  105. root["BABYLON"] = factory(root["BABYLON"]);
  106. }
  107. })(this, function() {
  108. var BABYLON;
  109. (function (BABYLON) {
  110. /**
  111. * EffectFallbacks can be used to add fallbacks (properties to disable) to certain properties when desired to improve performance.
  112. * (Eg. Start at high quality with reflection and fog, if fps is low, remove reflection, if still low remove fog)
  113. */
  114. var EffectFallbacks = /** @class */ (function () {
  115. function EffectFallbacks() {
  116. this._defines = {};
  117. this._currentRank = 32;
  118. this._maxRank = -1;
  119. }
  120. /**
  121. * Removes the fallback from the bound mesh.
  122. */
  123. EffectFallbacks.prototype.unBindMesh = function () {
  124. this._mesh = null;
  125. };
  126. /**
  127. * Adds a fallback on the specified property.
  128. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  129. * @param define The name of the define in the shader
  130. */
  131. EffectFallbacks.prototype.addFallback = function (rank, define) {
  132. if (!this._defines[rank]) {
  133. if (rank < this._currentRank) {
  134. this._currentRank = rank;
  135. }
  136. if (rank > this._maxRank) {
  137. this._maxRank = rank;
  138. }
  139. this._defines[rank] = new Array();
  140. }
  141. this._defines[rank].push(define);
  142. };
  143. /**
  144. * Sets the mesh to use CPU skinning when needing to fallback.
  145. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  146. * @param mesh The mesh to use the fallbacks.
  147. */
  148. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  149. this._mesh = mesh;
  150. if (rank < this._currentRank) {
  151. this._currentRank = rank;
  152. }
  153. if (rank > this._maxRank) {
  154. this._maxRank = rank;
  155. }
  156. };
  157. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  158. /**
  159. * Checks to see if more fallbacks are still availible.
  160. */
  161. get: function () {
  162. return this._currentRank <= this._maxRank;
  163. },
  164. enumerable: true,
  165. configurable: true
  166. });
  167. /**
  168. * Removes the defines that shoould be removed when falling back.
  169. * @param currentDefines defines the current define statements for the shader.
  170. * @param effect defines the current effect we try to compile
  171. * @returns The resulting defines with defines of the current rank removed.
  172. */
  173. EffectFallbacks.prototype.reduce = function (currentDefines, effect) {
  174. // First we try to switch to CPU skinning
  175. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0 && this._mesh.material) {
  176. this._mesh.computeBonesUsingShaders = false;
  177. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  178. var scene = this._mesh.getScene();
  179. for (var index = 0; index < scene.meshes.length; index++) {
  180. var otherMesh = scene.meshes[index];
  181. if (!otherMesh.material) {
  182. continue;
  183. }
  184. if (!otherMesh.computeBonesUsingShaders || otherMesh.numBoneInfluencers === 0) {
  185. continue;
  186. }
  187. if (otherMesh.material.getEffect() === effect) {
  188. otherMesh.computeBonesUsingShaders = false;
  189. }
  190. else {
  191. for (var _i = 0, _a = otherMesh.subMeshes; _i < _a.length; _i++) {
  192. var subMesh = _a[_i];
  193. var subMeshEffect = subMesh.effect;
  194. if (subMeshEffect === effect) {
  195. otherMesh.computeBonesUsingShaders = false;
  196. break;
  197. }
  198. }
  199. }
  200. }
  201. }
  202. else {
  203. var currentFallbacks = this._defines[this._currentRank];
  204. if (currentFallbacks) {
  205. for (var index = 0; index < currentFallbacks.length; index++) {
  206. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  207. }
  208. }
  209. this._currentRank++;
  210. }
  211. return currentDefines;
  212. };
  213. return EffectFallbacks;
  214. }());
  215. BABYLON.EffectFallbacks = EffectFallbacks;
  216. /**
  217. * Options to be used when creating an effect.
  218. */
  219. var EffectCreationOptions = /** @class */ (function () {
  220. function EffectCreationOptions() {
  221. }
  222. return EffectCreationOptions;
  223. }());
  224. BABYLON.EffectCreationOptions = EffectCreationOptions;
  225. /**
  226. * Effect containing vertex and fragment shader that can be executed on an object.
  227. */
  228. var Effect = /** @class */ (function () {
  229. /**
  230. * Instantiates an effect.
  231. * An effect can be used to create/manage/execute vertex and fragment shaders.
  232. * @param baseName Name of the effect.
  233. * @param attributesNamesOrOptions List of attribute names that will be passed to the shader or set of all options to create the effect.
  234. * @param uniformsNamesOrEngine List of uniform variable names that will be passed to the shader or the engine that will be used to render effect.
  235. * @param samplers List of sampler variables that will be passed to the shader.
  236. * @param engine Engine to be used to render the effect
  237. * @param defines Define statements to be added to the shader.
  238. * @param fallbacks Possible fallbacks for this effect to improve performance when needed.
  239. * @param onCompiled Callback that will be called when the shader is compiled.
  240. * @param onError Callback that will be called if an error occurs during shader compilation.
  241. * @param indexParameters Parameters to be used with Babylons include syntax to iterate over an array (eg. {lights: 10})
  242. */
  243. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  244. if (samplers === void 0) { samplers = null; }
  245. if (defines === void 0) { defines = null; }
  246. if (fallbacks === void 0) { fallbacks = null; }
  247. if (onCompiled === void 0) { onCompiled = null; }
  248. if (onError === void 0) { onError = null; }
  249. var _this = this;
  250. /**
  251. * Unique ID of the effect.
  252. */
  253. this.uniqueId = 0;
  254. /**
  255. * Observable that will be called when the shader is compiled.
  256. */
  257. this.onCompileObservable = new BABYLON.Observable();
  258. /**
  259. * Observable that will be called if an error occurs during shader compilation.
  260. */
  261. this.onErrorObservable = new BABYLON.Observable();
  262. /**
  263. * Observable that will be called when effect is bound.
  264. */
  265. this.onBindObservable = new BABYLON.Observable();
  266. this._uniformBuffersNames = {};
  267. this._isReady = false;
  268. this._compilationError = "";
  269. this.name = baseName;
  270. if (attributesNamesOrOptions.attributes) {
  271. var options = attributesNamesOrOptions;
  272. this._engine = uniformsNamesOrEngine;
  273. this._attributesNames = options.attributes;
  274. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  275. this._samplers = options.samplers;
  276. this.defines = options.defines;
  277. this.onError = options.onError;
  278. this.onCompiled = options.onCompiled;
  279. this._fallbacks = options.fallbacks;
  280. this._indexParameters = options.indexParameters;
  281. this._transformFeedbackVaryings = options.transformFeedbackVaryings;
  282. if (options.uniformBuffersNames) {
  283. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  284. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  285. }
  286. }
  287. }
  288. else {
  289. this._engine = engine;
  290. this.defines = defines;
  291. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  292. this._samplers = samplers;
  293. this._attributesNames = attributesNamesOrOptions;
  294. this.onError = onError;
  295. this.onCompiled = onCompiled;
  296. this._indexParameters = indexParameters;
  297. this._fallbacks = fallbacks;
  298. }
  299. this.uniqueId = Effect._uniqueIdSeed++;
  300. if (this._getFromCache(baseName)) {
  301. this._prepareEffect();
  302. return;
  303. }
  304. var vertexSource;
  305. var fragmentSource;
  306. if (baseName.vertexElement) {
  307. vertexSource = document.getElementById(baseName.vertexElement);
  308. if (!vertexSource) {
  309. vertexSource = baseName.vertexElement;
  310. }
  311. }
  312. else {
  313. vertexSource = baseName.vertex || baseName;
  314. }
  315. if (baseName.fragmentElement) {
  316. fragmentSource = document.getElementById(baseName.fragmentElement);
  317. if (!fragmentSource) {
  318. fragmentSource = baseName.fragmentElement;
  319. }
  320. }
  321. else {
  322. fragmentSource = baseName.fragment || baseName;
  323. }
  324. var finalVertexCode;
  325. this._loadVertexShaderAsync(vertexSource)
  326. .then(function (vertexCode) {
  327. return _this._processIncludesAsync(vertexCode);
  328. })
  329. .then(function (vertexCodeWithIncludes) {
  330. finalVertexCode = _this._processShaderConversion(vertexCodeWithIncludes, false);
  331. return _this._loadFragmentShaderAsync(fragmentSource);
  332. })
  333. .then(function (fragmentCode) {
  334. return _this._processIncludesAsync(fragmentCode);
  335. })
  336. .then(function (fragmentCodeWithIncludes) {
  337. var migratedFragmentCode = _this._processShaderConversion(fragmentCodeWithIncludes, true);
  338. if (baseName) {
  339. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  340. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  341. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + finalVertexCode;
  342. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  343. }
  344. else {
  345. _this._vertexSourceCode = finalVertexCode;
  346. _this._fragmentSourceCode = migratedFragmentCode;
  347. }
  348. _this._setInCache(baseName);
  349. _this._prepareEffect();
  350. });
  351. }
  352. Effect.prototype._getSourceCacheKey = function (baseName) {
  353. var cacheKey = baseName;
  354. if (this._indexParameters) {
  355. for (var key in this._indexParameters) {
  356. if (this._indexParameters.hasOwnProperty(key)) {
  357. cacheKey += "|";
  358. cacheKey += key;
  359. cacheKey += "_";
  360. cacheKey += this._indexParameters[key];
  361. }
  362. }
  363. }
  364. return cacheKey;
  365. };
  366. Effect.prototype._getFromCache = function (baseName) {
  367. if (typeof baseName !== "string") {
  368. return false;
  369. }
  370. var cacheKey = this._getSourceCacheKey(baseName);
  371. var sources = Effect._sourceCache[cacheKey];
  372. if (!sources) {
  373. return false;
  374. }
  375. this._vertexSourceCode = sources.vertex;
  376. this._fragmentSourceCode = sources.fragment;
  377. return true;
  378. };
  379. Effect.prototype._setInCache = function (baseName) {
  380. if (typeof baseName !== "string") {
  381. return;
  382. }
  383. var cacheKey = this._getSourceCacheKey(baseName);
  384. Effect._sourceCache[cacheKey] = {
  385. vertex: this._vertexSourceCode,
  386. fragment: this._fragmentSourceCode
  387. };
  388. };
  389. Object.defineProperty(Effect.prototype, "key", {
  390. /**
  391. * Unique key for this effect
  392. */
  393. get: function () {
  394. return this._key;
  395. },
  396. enumerable: true,
  397. configurable: true
  398. });
  399. /**
  400. * If the effect has been compiled and prepared.
  401. * @returns if the effect is compiled and prepared.
  402. */
  403. Effect.prototype.isReady = function () {
  404. return this._isReady;
  405. };
  406. /**
  407. * The engine the effect was initialized with.
  408. * @returns the engine.
  409. */
  410. Effect.prototype.getEngine = function () {
  411. return this._engine;
  412. };
  413. /**
  414. * The compiled webGL program for the effect
  415. * @returns the webGL program.
  416. */
  417. Effect.prototype.getProgram = function () {
  418. return this._program;
  419. };
  420. /**
  421. * The set of names of attribute variables for the shader.
  422. * @returns An array of attribute names.
  423. */
  424. Effect.prototype.getAttributesNames = function () {
  425. return this._attributesNames;
  426. };
  427. /**
  428. * Returns the attribute at the given index.
  429. * @param index The index of the attribute.
  430. * @returns The location of the attribute.
  431. */
  432. Effect.prototype.getAttributeLocation = function (index) {
  433. return this._attributes[index];
  434. };
  435. /**
  436. * Returns the attribute based on the name of the variable.
  437. * @param name of the attribute to look up.
  438. * @returns the attribute location.
  439. */
  440. Effect.prototype.getAttributeLocationByName = function (name) {
  441. var index = this._attributesNames.indexOf(name);
  442. return this._attributes[index];
  443. };
  444. /**
  445. * The number of attributes.
  446. * @returns the numnber of attributes.
  447. */
  448. Effect.prototype.getAttributesCount = function () {
  449. return this._attributes.length;
  450. };
  451. /**
  452. * Gets the index of a uniform variable.
  453. * @param uniformName of the uniform to look up.
  454. * @returns the index.
  455. */
  456. Effect.prototype.getUniformIndex = function (uniformName) {
  457. return this._uniformsNames.indexOf(uniformName);
  458. };
  459. /**
  460. * Returns the attribute based on the name of the variable.
  461. * @param uniformName of the uniform to look up.
  462. * @returns the location of the uniform.
  463. */
  464. Effect.prototype.getUniform = function (uniformName) {
  465. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  466. };
  467. /**
  468. * Returns an array of sampler variable names
  469. * @returns The array of sampler variable neames.
  470. */
  471. Effect.prototype.getSamplers = function () {
  472. return this._samplers;
  473. };
  474. /**
  475. * The error from the last compilation.
  476. * @returns the error string.
  477. */
  478. Effect.prototype.getCompilationError = function () {
  479. return this._compilationError;
  480. };
  481. /**
  482. * Adds a callback to the onCompiled observable and call the callback imediatly if already ready.
  483. * @param func The callback to be used.
  484. */
  485. Effect.prototype.executeWhenCompiled = function (func) {
  486. if (this.isReady()) {
  487. func(this);
  488. return;
  489. }
  490. this.onCompileObservable.add(function (effect) {
  491. func(effect);
  492. });
  493. };
  494. /** @ignore */
  495. Effect.prototype._loadVertexShaderAsync = function (vertex) {
  496. if (BABYLON.Tools.IsWindowObjectExist()) {
  497. // DOM element ?
  498. if (vertex instanceof HTMLElement) {
  499. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  500. return Promise.resolve(vertexCode);
  501. }
  502. }
  503. // Base64 encoded ?
  504. if (vertex.substr(0, 7) === "base64:") {
  505. var vertexBinary = window.atob(vertex.substr(7));
  506. return Promise.resolve(vertexBinary);
  507. }
  508. // Is in local store ?
  509. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  510. return Promise.resolve(Effect.ShadersStore[vertex + "VertexShader"]);
  511. }
  512. var vertexShaderUrl;
  513. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  514. vertexShaderUrl = vertex;
  515. }
  516. else {
  517. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  518. }
  519. // Vertex shader
  520. return this._engine._loadFileAsync(vertexShaderUrl + ".vertex.fx");
  521. };
  522. /** @ignore */
  523. Effect.prototype._loadFragmentShaderAsync = function (fragment) {
  524. if (BABYLON.Tools.IsWindowObjectExist()) {
  525. // DOM element ?
  526. if (fragment instanceof HTMLElement) {
  527. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  528. return Promise.resolve(fragmentCode);
  529. }
  530. }
  531. // Base64 encoded ?
  532. if (fragment.substr(0, 7) === "base64:") {
  533. var fragmentBinary = window.atob(fragment.substr(7));
  534. return Promise.resolve(fragmentBinary);
  535. }
  536. // Is in local store ?
  537. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  538. return Promise.resolve(Effect.ShadersStore[fragment + "PixelShader"]);
  539. }
  540. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  541. return Promise.resolve(Effect.ShadersStore[fragment + "FragmentShader"]);
  542. }
  543. var fragmentShaderUrl;
  544. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  545. fragmentShaderUrl = fragment;
  546. }
  547. else {
  548. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  549. }
  550. // Fragment shader
  551. return this._engine._loadFileAsync(fragmentShaderUrl + ".fragment.fx");
  552. };
  553. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  554. // Rebuild shaders source code
  555. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n" : "";
  556. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  557. vertexCode = prefix + vertexCode;
  558. fragmentCode = prefix + fragmentCode;
  559. // Number lines of shaders source code
  560. var i = 2;
  561. var regex = /\n/gm;
  562. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  563. i = 2;
  564. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  565. // Dump shaders name and formatted source code
  566. if (this.name.vertexElement) {
  567. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  568. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  569. }
  570. else if (this.name.vertex) {
  571. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  572. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  573. }
  574. else {
  575. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  576. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  577. }
  578. };
  579. ;
  580. Effect.prototype._processShaderConversion = function (sourceCode, isFragment) {
  581. var preparedSourceCode = this._processPrecision(sourceCode);
  582. if (this._engine.webGLVersion == 1) {
  583. return preparedSourceCode;
  584. }
  585. // Already converted
  586. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  587. return preparedSourceCode.replace("#version 300 es", "");
  588. }
  589. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  590. // Remove extensions
  591. // #extension GL_OES_standard_derivatives : enable
  592. // #extension GL_EXT_shader_texture_lod : enable
  593. // #extension GL_EXT_frag_depth : enable
  594. // #extension GL_EXT_draw_buffers : require
  595. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  596. var result = preparedSourceCode.replace(regex, "");
  597. // Migrate to GLSL v300
  598. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  599. result = result.replace(/attribute[ \t]/g, "in ");
  600. result = result.replace(/[ \t]attribute/g, " in");
  601. if (isFragment) {
  602. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  603. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  604. result = result.replace(/texture2D\s*\(/g, "texture(");
  605. result = result.replace(/textureCube\s*\(/g, "texture(");
  606. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  607. result = result.replace(/gl_FragColor/g, "glFragColor");
  608. result = result.replace(/gl_FragData/g, "glFragData");
  609. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  610. }
  611. return result;
  612. };
  613. Effect.prototype._processIncludesAsync = function (sourceCode) {
  614. var _this = this;
  615. return new Promise(function (resolve, reject) {
  616. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  617. var match = regex.exec(sourceCode);
  618. var returnValue = sourceCode;
  619. while (match != null) {
  620. var includeFile = match[1];
  621. // Uniform declaration
  622. if (includeFile.indexOf("__decl__") !== -1) {
  623. includeFile = includeFile.replace(/__decl__/, "");
  624. if (_this._engine.supportsUniformBuffers) {
  625. includeFile = includeFile.replace(/Vertex/, "Ubo");
  626. includeFile = includeFile.replace(/Fragment/, "Ubo");
  627. }
  628. includeFile = includeFile + "Declaration";
  629. }
  630. if (Effect.IncludesShadersStore[includeFile]) {
  631. // Substitution
  632. var includeContent = Effect.IncludesShadersStore[includeFile];
  633. if (match[2]) {
  634. var splits = match[3].split(",");
  635. for (var index = 0; index < splits.length; index += 2) {
  636. var source = new RegExp(splits[index], "g");
  637. var dest = splits[index + 1];
  638. includeContent = includeContent.replace(source, dest);
  639. }
  640. }
  641. if (match[4]) {
  642. var indexString = match[5];
  643. if (indexString.indexOf("..") !== -1) {
  644. var indexSplits = indexString.split("..");
  645. var minIndex = parseInt(indexSplits[0]);
  646. var maxIndex = parseInt(indexSplits[1]);
  647. var sourceIncludeContent = includeContent.slice(0);
  648. includeContent = "";
  649. if (isNaN(maxIndex)) {
  650. maxIndex = _this._indexParameters[indexSplits[1]];
  651. }
  652. for (var i = minIndex; i < maxIndex; i++) {
  653. if (!_this._engine.supportsUniformBuffers) {
  654. // Ubo replacement
  655. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  656. return p1 + "{X}";
  657. });
  658. }
  659. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  660. }
  661. }
  662. else {
  663. if (!_this._engine.supportsUniformBuffers) {
  664. // Ubo replacement
  665. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  666. return p1 + "{X}";
  667. });
  668. }
  669. includeContent = includeContent.replace(/\{X\}/g, indexString);
  670. }
  671. }
  672. // Replace
  673. returnValue = returnValue.replace(match[0], includeContent);
  674. }
  675. else {
  676. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  677. _this._engine._loadFileAsync(includeShaderUrl)
  678. .then(function (fileContent) {
  679. Effect.IncludesShadersStore[includeFile] = fileContent;
  680. return _this._processIncludesAsync(returnValue);
  681. })
  682. .then(function (returnValue) {
  683. resolve(returnValue);
  684. });
  685. return;
  686. }
  687. match = regex.exec(sourceCode);
  688. }
  689. resolve(returnValue);
  690. });
  691. };
  692. Effect.prototype._processPrecision = function (source) {
  693. if (source.indexOf("precision highp float") === -1) {
  694. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  695. source = "precision mediump float;\n" + source;
  696. }
  697. else {
  698. source = "precision highp float;\n" + source;
  699. }
  700. }
  701. else {
  702. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  703. source = source.replace("precision highp float", "precision mediump float");
  704. }
  705. }
  706. return source;
  707. };
  708. /**
  709. * Recompiles the webGL program
  710. * @param vertexSourceCode The source code for the vertex shader.
  711. * @param fragmentSourceCode The source code for the fragment shader.
  712. * @param onCompiled Callback called when completed.
  713. * @param onError Callback called on error.
  714. */
  715. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  716. var _this = this;
  717. this._isReady = false;
  718. this._vertexSourceCodeOverride = vertexSourceCode;
  719. this._fragmentSourceCodeOverride = fragmentSourceCode;
  720. this.onError = function (effect, error) {
  721. if (onError) {
  722. onError(error);
  723. }
  724. };
  725. this.onCompiled = function () {
  726. var scenes = _this.getEngine().scenes;
  727. for (var i = 0; i < scenes.length; i++) {
  728. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  729. }
  730. if (onCompiled) {
  731. onCompiled(_this._program);
  732. }
  733. };
  734. this._fallbacks = null;
  735. this._prepareEffect();
  736. };
  737. /**
  738. * Gets the uniform locations of the the specified variable names
  739. * @param names THe names of the variables to lookup.
  740. * @returns Array of locations in the same order as variable names.
  741. */
  742. Effect.prototype.getSpecificUniformLocations = function (names) {
  743. var engine = this._engine;
  744. return engine.getUniforms(this._program, names);
  745. };
  746. /**
  747. * Prepares the effect
  748. */
  749. Effect.prototype._prepareEffect = function () {
  750. var attributesNames = this._attributesNames;
  751. var defines = this.defines;
  752. var fallbacks = this._fallbacks;
  753. this._valueCache = {};
  754. var previousProgram = this._program;
  755. try {
  756. var engine = this._engine;
  757. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  758. this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
  759. }
  760. else {
  761. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
  762. }
  763. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  764. if (engine.supportsUniformBuffers) {
  765. for (var name in this._uniformBuffersNames) {
  766. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  767. }
  768. }
  769. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  770. this._attributes = engine.getAttributes(this._program, attributesNames);
  771. var index;
  772. for (index = 0; index < this._samplers.length; index++) {
  773. var sampler = this.getUniform(this._samplers[index]);
  774. if (sampler == null) {
  775. this._samplers.splice(index, 1);
  776. index--;
  777. }
  778. }
  779. engine.bindSamplers(this);
  780. this._compilationError = "";
  781. this._isReady = true;
  782. if (this.onCompiled) {
  783. this.onCompiled(this);
  784. }
  785. this.onCompileObservable.notifyObservers(this);
  786. this.onCompileObservable.clear();
  787. // Unbind mesh reference in fallbacks
  788. if (this._fallbacks) {
  789. this._fallbacks.unBindMesh();
  790. }
  791. if (previousProgram) {
  792. this.getEngine()._deleteProgram(previousProgram);
  793. }
  794. }
  795. catch (e) {
  796. this._compilationError = e.message;
  797. // Let's go through fallbacks then
  798. BABYLON.Tools.Error("Unable to compile effect:");
  799. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  800. return " " + uniform;
  801. }));
  802. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  803. return " " + attribute;
  804. }));
  805. this._dumpShadersSource(this._vertexSourceCode, this._fragmentSourceCode, defines);
  806. BABYLON.Tools.Error("Error: " + this._compilationError);
  807. if (previousProgram) {
  808. this._program = previousProgram;
  809. this._isReady = true;
  810. if (this.onError) {
  811. this.onError(this, this._compilationError);
  812. }
  813. this.onErrorObservable.notifyObservers(this);
  814. }
  815. if (fallbacks && fallbacks.isMoreFallbacks) {
  816. BABYLON.Tools.Error("Trying next fallback.");
  817. this.defines = fallbacks.reduce(this.defines, this);
  818. this._prepareEffect();
  819. }
  820. else {
  821. if (this.onError) {
  822. this.onError(this, this._compilationError);
  823. }
  824. this.onErrorObservable.notifyObservers(this);
  825. this.onErrorObservable.clear();
  826. // Unbind mesh reference in fallbacks
  827. if (this._fallbacks) {
  828. this._fallbacks.unBindMesh();
  829. }
  830. }
  831. }
  832. };
  833. Object.defineProperty(Effect.prototype, "isSupported", {
  834. /**
  835. * Checks if the effect is supported. (Must be called after compilation)
  836. */
  837. get: function () {
  838. return this._compilationError === "";
  839. },
  840. enumerable: true,
  841. configurable: true
  842. });
  843. /**
  844. * Binds a texture to the engine to be used as output of the shader.
  845. * @param channel Name of the output variable.
  846. * @param texture Texture to bind.
  847. */
  848. Effect.prototype._bindTexture = function (channel, texture) {
  849. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  850. };
  851. /**
  852. * Sets a texture on the engine to be used in the shader.
  853. * @param channel Name of the sampler variable.
  854. * @param texture Texture to set.
  855. */
  856. Effect.prototype.setTexture = function (channel, texture) {
  857. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  858. };
  859. /**
  860. * Sets an array of textures on the engine to be used in the shader.
  861. * @param channel Name of the variable.
  862. * @param textures Textures to set.
  863. */
  864. Effect.prototype.setTextureArray = function (channel, textures) {
  865. if (this._samplers.indexOf(channel + "Ex") === -1) {
  866. var initialPos = this._samplers.indexOf(channel);
  867. for (var index = 1; index < textures.length; index++) {
  868. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  869. }
  870. }
  871. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  872. };
  873. /**
  874. * Sets a texture to be the input of the specified post process. (To use the output, pass in the next post process in the pipeline)
  875. * @param channel Name of the sampler variable.
  876. * @param postProcess Post process to get the input texture from.
  877. */
  878. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  879. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  880. };
  881. /** @ignore */
  882. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  883. var cache = this._valueCache[uniformName];
  884. var flag = matrix.updateFlag;
  885. if (cache !== undefined && cache === flag) {
  886. return false;
  887. }
  888. this._valueCache[uniformName] = flag;
  889. return true;
  890. };
  891. /** @ignore */
  892. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  893. var cache = this._valueCache[uniformName];
  894. if (!cache) {
  895. cache = [x, y];
  896. this._valueCache[uniformName] = cache;
  897. return true;
  898. }
  899. var changed = false;
  900. if (cache[0] !== x) {
  901. cache[0] = x;
  902. changed = true;
  903. }
  904. if (cache[1] !== y) {
  905. cache[1] = y;
  906. changed = true;
  907. }
  908. return changed;
  909. };
  910. /** @ignore */
  911. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  912. var cache = this._valueCache[uniformName];
  913. if (!cache) {
  914. cache = [x, y, z];
  915. this._valueCache[uniformName] = cache;
  916. return true;
  917. }
  918. var changed = false;
  919. if (cache[0] !== x) {
  920. cache[0] = x;
  921. changed = true;
  922. }
  923. if (cache[1] !== y) {
  924. cache[1] = y;
  925. changed = true;
  926. }
  927. if (cache[2] !== z) {
  928. cache[2] = z;
  929. changed = true;
  930. }
  931. return changed;
  932. };
  933. /** @ignore */
  934. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  935. var cache = this._valueCache[uniformName];
  936. if (!cache) {
  937. cache = [x, y, z, w];
  938. this._valueCache[uniformName] = cache;
  939. return true;
  940. }
  941. var changed = false;
  942. if (cache[0] !== x) {
  943. cache[0] = x;
  944. changed = true;
  945. }
  946. if (cache[1] !== y) {
  947. cache[1] = y;
  948. changed = true;
  949. }
  950. if (cache[2] !== z) {
  951. cache[2] = z;
  952. changed = true;
  953. }
  954. if (cache[3] !== w) {
  955. cache[3] = w;
  956. changed = true;
  957. }
  958. return changed;
  959. };
  960. /**
  961. * Binds a buffer to a uniform.
  962. * @param buffer Buffer to bind.
  963. * @param name Name of the uniform variable to bind to.
  964. */
  965. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  966. var bufferName = this._uniformBuffersNames[name];
  967. if (bufferName === undefined || Effect._baseCache[bufferName] === buffer) {
  968. return;
  969. }
  970. Effect._baseCache[bufferName] = buffer;
  971. this._engine.bindUniformBufferBase(buffer, bufferName);
  972. };
  973. /**
  974. * Binds block to a uniform.
  975. * @param blockName Name of the block to bind.
  976. * @param index Index to bind.
  977. */
  978. Effect.prototype.bindUniformBlock = function (blockName, index) {
  979. this._engine.bindUniformBlock(this._program, blockName, index);
  980. };
  981. /**
  982. * Sets an interger value on a uniform variable.
  983. * @param uniformName Name of the variable.
  984. * @param value Value to be set.
  985. * @returns this effect.
  986. */
  987. Effect.prototype.setInt = function (uniformName, value) {
  988. var cache = this._valueCache[uniformName];
  989. if (cache !== undefined && cache === value)
  990. return this;
  991. this._valueCache[uniformName] = value;
  992. this._engine.setInt(this.getUniform(uniformName), value);
  993. return this;
  994. };
  995. /**
  996. * Sets an int array on a uniform variable.
  997. * @param uniformName Name of the variable.
  998. * @param array array to be set.
  999. * @returns this effect.
  1000. */
  1001. Effect.prototype.setIntArray = function (uniformName, array) {
  1002. this._valueCache[uniformName] = null;
  1003. this._engine.setIntArray(this.getUniform(uniformName), array);
  1004. return this;
  1005. };
  1006. /**
  1007. * 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)
  1008. * @param uniformName Name of the variable.
  1009. * @param array array to be set.
  1010. * @returns this effect.
  1011. */
  1012. Effect.prototype.setIntArray2 = function (uniformName, array) {
  1013. this._valueCache[uniformName] = null;
  1014. this._engine.setIntArray2(this.getUniform(uniformName), array);
  1015. return this;
  1016. };
  1017. /**
  1018. * 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)
  1019. * @param uniformName Name of the variable.
  1020. * @param array array to be set.
  1021. * @returns this effect.
  1022. */
  1023. Effect.prototype.setIntArray3 = function (uniformName, array) {
  1024. this._valueCache[uniformName] = null;
  1025. this._engine.setIntArray3(this.getUniform(uniformName), array);
  1026. return this;
  1027. };
  1028. /**
  1029. * 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)
  1030. * @param uniformName Name of the variable.
  1031. * @param array array to be set.
  1032. * @returns this effect.
  1033. */
  1034. Effect.prototype.setIntArray4 = function (uniformName, array) {
  1035. this._valueCache[uniformName] = null;
  1036. this._engine.setIntArray4(this.getUniform(uniformName), array);
  1037. return this;
  1038. };
  1039. /**
  1040. * Sets an float array on a uniform variable.
  1041. * @param uniformName Name of the variable.
  1042. * @param array array to be set.
  1043. * @returns this effect.
  1044. */
  1045. Effect.prototype.setFloatArray = function (uniformName, array) {
  1046. this._valueCache[uniformName] = null;
  1047. this._engine.setFloatArray(this.getUniform(uniformName), array);
  1048. return this;
  1049. };
  1050. /**
  1051. * 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)
  1052. * @param uniformName Name of the variable.
  1053. * @param array array to be set.
  1054. * @returns this effect.
  1055. */
  1056. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  1057. this._valueCache[uniformName] = null;
  1058. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  1059. return this;
  1060. };
  1061. /**
  1062. * 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)
  1063. * @param uniformName Name of the variable.
  1064. * @param array array to be set.
  1065. * @returns this effect.
  1066. */
  1067. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  1068. this._valueCache[uniformName] = null;
  1069. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  1070. return this;
  1071. };
  1072. /**
  1073. * 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)
  1074. * @param uniformName Name of the variable.
  1075. * @param array array to be set.
  1076. * @returns this effect.
  1077. */
  1078. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  1079. this._valueCache[uniformName] = null;
  1080. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  1081. return this;
  1082. };
  1083. /**
  1084. * Sets an array on a uniform variable.
  1085. * @param uniformName Name of the variable.
  1086. * @param array array to be set.
  1087. * @returns this effect.
  1088. */
  1089. Effect.prototype.setArray = function (uniformName, array) {
  1090. this._valueCache[uniformName] = null;
  1091. this._engine.setArray(this.getUniform(uniformName), array);
  1092. return this;
  1093. };
  1094. /**
  1095. * 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)
  1096. * @param uniformName Name of the variable.
  1097. * @param array array to be set.
  1098. * @returns this effect.
  1099. */
  1100. Effect.prototype.setArray2 = function (uniformName, array) {
  1101. this._valueCache[uniformName] = null;
  1102. this._engine.setArray2(this.getUniform(uniformName), array);
  1103. return this;
  1104. };
  1105. /**
  1106. * 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)
  1107. * @param uniformName Name of the variable.
  1108. * @param array array to be set.
  1109. * @returns this effect.
  1110. */
  1111. Effect.prototype.setArray3 = function (uniformName, array) {
  1112. this._valueCache[uniformName] = null;
  1113. this._engine.setArray3(this.getUniform(uniformName), array);
  1114. return this;
  1115. };
  1116. /**
  1117. * 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)
  1118. * @param uniformName Name of the variable.
  1119. * @param array array to be set.
  1120. * @returns this effect.
  1121. */
  1122. Effect.prototype.setArray4 = function (uniformName, array) {
  1123. this._valueCache[uniformName] = null;
  1124. this._engine.setArray4(this.getUniform(uniformName), array);
  1125. return this;
  1126. };
  1127. /**
  1128. * Sets matrices on a uniform variable.
  1129. * @param uniformName Name of the variable.
  1130. * @param matrices matrices to be set.
  1131. * @returns this effect.
  1132. */
  1133. Effect.prototype.setMatrices = function (uniformName, matrices) {
  1134. if (!matrices) {
  1135. return this;
  1136. }
  1137. this._valueCache[uniformName] = null;
  1138. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  1139. return this;
  1140. };
  1141. /**
  1142. * Sets matrix on a uniform variable.
  1143. * @param uniformName Name of the variable.
  1144. * @param matrix matrix to be set.
  1145. * @returns this effect.
  1146. */
  1147. Effect.prototype.setMatrix = function (uniformName, matrix) {
  1148. if (this._cacheMatrix(uniformName, matrix)) {
  1149. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  1150. }
  1151. return this;
  1152. };
  1153. /**
  1154. * 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)
  1155. * @param uniformName Name of the variable.
  1156. * @param matrix matrix to be set.
  1157. * @returns this effect.
  1158. */
  1159. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  1160. this._valueCache[uniformName] = null;
  1161. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  1162. return this;
  1163. };
  1164. /**
  1165. * Sets a 2x2 matrix on a uniform variable. (Speicified as [1,2,3,4] will result in [1,2][3,4] matrix)
  1166. * @param uniformName Name of the variable.
  1167. * @param matrix matrix to be set.
  1168. * @returns this effect.
  1169. */
  1170. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  1171. this._valueCache[uniformName] = null;
  1172. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  1173. return this;
  1174. };
  1175. /**
  1176. * Sets a float on a uniform variable.
  1177. * @param uniformName Name of the variable.
  1178. * @param value value to be set.
  1179. * @returns this effect.
  1180. */
  1181. Effect.prototype.setFloat = function (uniformName, value) {
  1182. var cache = this._valueCache[uniformName];
  1183. if (cache !== undefined && cache === value)
  1184. return this;
  1185. this._valueCache[uniformName] = value;
  1186. this._engine.setFloat(this.getUniform(uniformName), value);
  1187. return this;
  1188. };
  1189. /**
  1190. * Sets a boolean on a uniform variable.
  1191. * @param uniformName Name of the variable.
  1192. * @param bool value to be set.
  1193. * @returns this effect.
  1194. */
  1195. Effect.prototype.setBool = function (uniformName, bool) {
  1196. var cache = this._valueCache[uniformName];
  1197. if (cache !== undefined && cache === bool)
  1198. return this;
  1199. this._valueCache[uniformName] = bool;
  1200. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  1201. return this;
  1202. };
  1203. /**
  1204. * Sets a Vector2 on a uniform variable.
  1205. * @param uniformName Name of the variable.
  1206. * @param vector2 vector2 to be set.
  1207. * @returns this effect.
  1208. */
  1209. Effect.prototype.setVector2 = function (uniformName, vector2) {
  1210. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  1211. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  1212. }
  1213. return this;
  1214. };
  1215. /**
  1216. * Sets a float2 on a uniform variable.
  1217. * @param uniformName Name of the variable.
  1218. * @param x First float in float2.
  1219. * @param y Second float in float2.
  1220. * @returns this effect.
  1221. */
  1222. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  1223. if (this._cacheFloat2(uniformName, x, y)) {
  1224. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  1225. }
  1226. return this;
  1227. };
  1228. /**
  1229. * Sets a Vector3 on a uniform variable.
  1230. * @param uniformName Name of the variable.
  1231. * @param vector3 Value to be set.
  1232. * @returns this effect.
  1233. */
  1234. Effect.prototype.setVector3 = function (uniformName, vector3) {
  1235. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  1236. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  1237. }
  1238. return this;
  1239. };
  1240. /**
  1241. * Sets a float3 on a uniform variable.
  1242. * @param uniformName Name of the variable.
  1243. * @param x First float in float3.
  1244. * @param y Second float in float3.
  1245. * @param z Third float in float3.
  1246. * @returns this effect.
  1247. */
  1248. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  1249. if (this._cacheFloat3(uniformName, x, y, z)) {
  1250. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  1251. }
  1252. return this;
  1253. };
  1254. /**
  1255. * Sets a Vector4 on a uniform variable.
  1256. * @param uniformName Name of the variable.
  1257. * @param vector4 Value to be set.
  1258. * @returns this effect.
  1259. */
  1260. Effect.prototype.setVector4 = function (uniformName, vector4) {
  1261. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  1262. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  1263. }
  1264. return this;
  1265. };
  1266. /**
  1267. * Sets a float4 on a uniform variable.
  1268. * @param uniformName Name of the variable.
  1269. * @param x First float in float4.
  1270. * @param y Second float in float4.
  1271. * @param z Third float in float4.
  1272. * @param w Fourth float in float4.
  1273. * @returns this effect.
  1274. */
  1275. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  1276. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  1277. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  1278. }
  1279. return this;
  1280. };
  1281. /**
  1282. * Sets a Color3 on a uniform variable.
  1283. * @param uniformName Name of the variable.
  1284. * @param color3 Value to be set.
  1285. * @returns this effect.
  1286. */
  1287. Effect.prototype.setColor3 = function (uniformName, color3) {
  1288. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  1289. this._engine.setColor3(this.getUniform(uniformName), color3);
  1290. }
  1291. return this;
  1292. };
  1293. /**
  1294. * Sets a Color4 on a uniform variable.
  1295. * @param uniformName Name of the variable.
  1296. * @param color3 Value to be set.
  1297. * @param alpha Alpha value to be set.
  1298. * @returns this effect.
  1299. */
  1300. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  1301. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  1302. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  1303. }
  1304. return this;
  1305. };
  1306. /**
  1307. * Sets a Color4 on a uniform variable
  1308. * @param uniformName defines the name of the variable
  1309. * @param color4 defines the value to be set
  1310. * @returns this effect.
  1311. */
  1312. Effect.prototype.setDirectColor4 = function (uniformName, color4) {
  1313. if (this._cacheFloat4(uniformName, color4.r, color4.g, color4.b, color4.a)) {
  1314. this._engine.setDirectColor4(this.getUniform(uniformName), color4);
  1315. }
  1316. return this;
  1317. };
  1318. /**
  1319. * Resets the cache of effects.
  1320. */
  1321. Effect.ResetCache = function () {
  1322. Effect._baseCache = {};
  1323. };
  1324. Effect._uniqueIdSeed = 0;
  1325. Effect._baseCache = {};
  1326. Effect._sourceCache = {};
  1327. // Statics
  1328. /**
  1329. * Store of each shader (The can be looked up using effect.key)
  1330. */
  1331. Effect.ShadersStore = {};
  1332. /**
  1333. * Store of each included file for a shader (The can be looked up using effect.key)
  1334. */
  1335. Effect.IncludesShadersStore = {};
  1336. return Effect;
  1337. }());
  1338. BABYLON.Effect = Effect;
  1339. })(BABYLON || (BABYLON = {}));
  1340. //# sourceMappingURL=babylon.effect.js.map
  1341. //# sourceMappingURL=babylon.types.js.map
  1342. var BABYLON;
  1343. (function (BABYLON) {
  1344. var KeyboardEventTypes = /** @class */ (function () {
  1345. function KeyboardEventTypes() {
  1346. }
  1347. Object.defineProperty(KeyboardEventTypes, "KEYDOWN", {
  1348. get: function () {
  1349. return KeyboardEventTypes._KEYDOWN;
  1350. },
  1351. enumerable: true,
  1352. configurable: true
  1353. });
  1354. Object.defineProperty(KeyboardEventTypes, "KEYUP", {
  1355. get: function () {
  1356. return KeyboardEventTypes._KEYUP;
  1357. },
  1358. enumerable: true,
  1359. configurable: true
  1360. });
  1361. KeyboardEventTypes._KEYDOWN = 0x01;
  1362. KeyboardEventTypes._KEYUP = 0x02;
  1363. return KeyboardEventTypes;
  1364. }());
  1365. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  1366. var KeyboardInfo = /** @class */ (function () {
  1367. function KeyboardInfo(type, event) {
  1368. this.type = type;
  1369. this.event = event;
  1370. }
  1371. return KeyboardInfo;
  1372. }());
  1373. BABYLON.KeyboardInfo = KeyboardInfo;
  1374. /**
  1375. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  1376. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  1377. */
  1378. var KeyboardInfoPre = /** @class */ (function (_super) {
  1379. __extends(KeyboardInfoPre, _super);
  1380. function KeyboardInfoPre(type, event) {
  1381. var _this = _super.call(this, type, event) || this;
  1382. _this.skipOnPointerObservable = false;
  1383. return _this;
  1384. }
  1385. return KeyboardInfoPre;
  1386. }(KeyboardInfo));
  1387. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  1388. })(BABYLON || (BABYLON = {}));
  1389. //# sourceMappingURL=babylon.keyboardEvents.js.map
  1390. var BABYLON;
  1391. (function (BABYLON) {
  1392. var PointerEventTypes = /** @class */ (function () {
  1393. function PointerEventTypes() {
  1394. }
  1395. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  1396. get: function () {
  1397. return PointerEventTypes._POINTERDOWN;
  1398. },
  1399. enumerable: true,
  1400. configurable: true
  1401. });
  1402. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  1403. get: function () {
  1404. return PointerEventTypes._POINTERUP;
  1405. },
  1406. enumerable: true,
  1407. configurable: true
  1408. });
  1409. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  1410. get: function () {
  1411. return PointerEventTypes._POINTERMOVE;
  1412. },
  1413. enumerable: true,
  1414. configurable: true
  1415. });
  1416. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  1417. get: function () {
  1418. return PointerEventTypes._POINTERWHEEL;
  1419. },
  1420. enumerable: true,
  1421. configurable: true
  1422. });
  1423. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  1424. get: function () {
  1425. return PointerEventTypes._POINTERPICK;
  1426. },
  1427. enumerable: true,
  1428. configurable: true
  1429. });
  1430. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  1431. get: function () {
  1432. return PointerEventTypes._POINTERTAP;
  1433. },
  1434. enumerable: true,
  1435. configurable: true
  1436. });
  1437. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  1438. get: function () {
  1439. return PointerEventTypes._POINTERDOUBLETAP;
  1440. },
  1441. enumerable: true,
  1442. configurable: true
  1443. });
  1444. PointerEventTypes._POINTERDOWN = 0x01;
  1445. PointerEventTypes._POINTERUP = 0x02;
  1446. PointerEventTypes._POINTERMOVE = 0x04;
  1447. PointerEventTypes._POINTERWHEEL = 0x08;
  1448. PointerEventTypes._POINTERPICK = 0x10;
  1449. PointerEventTypes._POINTERTAP = 0x20;
  1450. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  1451. return PointerEventTypes;
  1452. }());
  1453. BABYLON.PointerEventTypes = PointerEventTypes;
  1454. var PointerInfoBase = /** @class */ (function () {
  1455. function PointerInfoBase(type, event) {
  1456. this.type = type;
  1457. this.event = event;
  1458. }
  1459. return PointerInfoBase;
  1460. }());
  1461. BABYLON.PointerInfoBase = PointerInfoBase;
  1462. /**
  1463. * This class is used to store pointer related info for the onPrePointerObservable event.
  1464. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  1465. */
  1466. var PointerInfoPre = /** @class */ (function (_super) {
  1467. __extends(PointerInfoPre, _super);
  1468. function PointerInfoPre(type, event, localX, localY) {
  1469. var _this = _super.call(this, type, event) || this;
  1470. _this.skipOnPointerObservable = false;
  1471. _this.localPosition = new BABYLON.Vector2(localX, localY);
  1472. return _this;
  1473. }
  1474. return PointerInfoPre;
  1475. }(PointerInfoBase));
  1476. BABYLON.PointerInfoPre = PointerInfoPre;
  1477. /**
  1478. * This type contains all the data related to a pointer event in Babylon.js.
  1479. * 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.
  1480. */
  1481. var PointerInfo = /** @class */ (function (_super) {
  1482. __extends(PointerInfo, _super);
  1483. function PointerInfo(type, event, pickInfo) {
  1484. var _this = _super.call(this, type, event) || this;
  1485. _this.pickInfo = pickInfo;
  1486. return _this;
  1487. }
  1488. return PointerInfo;
  1489. }(PointerInfoBase));
  1490. BABYLON.PointerInfo = PointerInfo;
  1491. })(BABYLON || (BABYLON = {}));
  1492. //# sourceMappingURL=babylon.pointerEvents.js.map
  1493. var BABYLON;
  1494. (function (BABYLON) {
  1495. BABYLON.ToGammaSpace = 1 / 2.2;
  1496. BABYLON.ToLinearSpace = 2.2;
  1497. BABYLON.Epsilon = 0.001;
  1498. /**
  1499. * Class used to hold a RBG color
  1500. */
  1501. var Color3 = /** @class */ (function () {
  1502. /**
  1503. * Creates a new Color3 object from red, green, blue values, all between 0 and 1
  1504. * @param r defines the red component (between 0 and 1, default is 0)
  1505. * @param g defines the green component (between 0 and 1, default is 0)
  1506. * @param b defines the blue component (between 0 and 1, default is 0)
  1507. */
  1508. function Color3(
  1509. /**
  1510. * Defines the red component (between 0 and 1, default is 0)
  1511. */
  1512. r,
  1513. /**
  1514. * Defines the green component (between 0 and 1, default is 0)
  1515. */
  1516. g,
  1517. /**
  1518. * Defines the blue component (between 0 and 1, default is 0)
  1519. */
  1520. b) {
  1521. if (r === void 0) { r = 0; }
  1522. if (g === void 0) { g = 0; }
  1523. if (b === void 0) { b = 0; }
  1524. this.r = r;
  1525. this.g = g;
  1526. this.b = b;
  1527. }
  1528. /**
  1529. * Creates a string with the Color3 current values
  1530. * @returns the string representation of the Color3 object
  1531. */
  1532. Color3.prototype.toString = function () {
  1533. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  1534. };
  1535. /**
  1536. * Returns the string "Color3"
  1537. * @returns "Color3"
  1538. */
  1539. Color3.prototype.getClassName = function () {
  1540. return "Color3";
  1541. };
  1542. /**
  1543. * Compute the Color3 hash code
  1544. * @returns an unique number that can be used to hash Color3 objects
  1545. */
  1546. Color3.prototype.getHashCode = function () {
  1547. var hash = this.r || 0;
  1548. hash = (hash * 397) ^ (this.g || 0);
  1549. hash = (hash * 397) ^ (this.b || 0);
  1550. return hash;
  1551. };
  1552. // Operators
  1553. /**
  1554. * Stores in the passed array from the passed starting index the red, green, blue values as successive elements
  1555. * @param array defines the array where to store the r,g,b components
  1556. * @param index defines an optional index in the target array to define where to start storing values
  1557. * @returns the current Color3 object
  1558. */
  1559. Color3.prototype.toArray = function (array, index) {
  1560. if (index === undefined) {
  1561. index = 0;
  1562. }
  1563. array[index] = this.r;
  1564. array[index + 1] = this.g;
  1565. array[index + 2] = this.b;
  1566. return this;
  1567. };
  1568. /**
  1569. * Returns a new {BABYLON.Color4} object from the current Color3 and the passed alpha
  1570. * @param alpha defines the alpha component on the new {BABYLON.Color4} object (default is 1)
  1571. * @returns a new {BABYLON.Color4} object
  1572. */
  1573. Color3.prototype.toColor4 = function (alpha) {
  1574. if (alpha === void 0) { alpha = 1; }
  1575. return new Color4(this.r, this.g, this.b, alpha);
  1576. };
  1577. /**
  1578. * Returns a new array populated with 3 numeric elements : red, green and blue values
  1579. * @returns the new array
  1580. */
  1581. Color3.prototype.asArray = function () {
  1582. var result = new Array();
  1583. this.toArray(result, 0);
  1584. return result;
  1585. };
  1586. /**
  1587. * Returns the luminance value
  1588. * @returns a float value
  1589. */
  1590. Color3.prototype.toLuminance = function () {
  1591. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  1592. };
  1593. /**
  1594. * Multiply each Color3 rgb values by the passed Color3 rgb values in a new Color3 object
  1595. * @param otherColor defines the second operand
  1596. * @returns the new Color3 object
  1597. */
  1598. Color3.prototype.multiply = function (otherColor) {
  1599. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  1600. };
  1601. /**
  1602. * Multiply the rgb values of the Color3 and the passed Color3 and stores the result in the object "result"
  1603. * @param otherColor defines the second operand
  1604. * @param result defines the Color3 object where to store the result
  1605. * @returns the current Color3
  1606. */
  1607. Color3.prototype.multiplyToRef = function (otherColor, result) {
  1608. result.r = this.r * otherColor.r;
  1609. result.g = this.g * otherColor.g;
  1610. result.b = this.b * otherColor.b;
  1611. return this;
  1612. };
  1613. /**
  1614. * Determines equality between Color3 objects
  1615. * @param otherColor defines the second operand
  1616. * @returns true if the rgb values are equal to the passed ones
  1617. */
  1618. Color3.prototype.equals = function (otherColor) {
  1619. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  1620. };
  1621. /**
  1622. * Determines equality between the current Color3 object and a set of r,b,g values
  1623. * @param r defines the red component to check
  1624. * @param g defines the green component to check
  1625. * @param b defines the blue component to check
  1626. * @returns true if the rgb values are equal to the passed ones
  1627. */
  1628. Color3.prototype.equalsFloats = function (r, g, b) {
  1629. return this.r === r && this.g === g && this.b === b;
  1630. };
  1631. /**
  1632. * Multiplies in place each rgb value by scale
  1633. * @param scale defines the scaling factor
  1634. * @returns the updated Color3.
  1635. */
  1636. Color3.prototype.scale = function (scale) {
  1637. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  1638. };
  1639. /**
  1640. * Multiplies the rgb values by scale and stores the result into "result"
  1641. * @param scale defines the scaling factor
  1642. * @param result defines the Color3 object where to store the result
  1643. * @returns the unmodified current Color3.
  1644. */
  1645. Color3.prototype.scaleToRef = function (scale, result) {
  1646. result.r = this.r * scale;
  1647. result.g = this.g * scale;
  1648. result.b = this.b * scale;
  1649. return this;
  1650. };
  1651. /**
  1652. * Clamps the rgb values by the min and max values and stores the result into "result"
  1653. * @param min defines minimum clamping value (default is 0)
  1654. * @param max defines maximum clamping value (default is 1)
  1655. * @param result defines color to store the result into
  1656. * @returns the original Color3
  1657. */
  1658. Color3.prototype.clampToRef = function (min, max, result) {
  1659. if (min === void 0) { min = 0; }
  1660. if (max === void 0) { max = 1; }
  1661. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1662. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1663. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1664. return this;
  1665. };
  1666. /**
  1667. * Creates a new Color3 set with the added values of the current Color3 and of the passed one
  1668. * @param otherColor defines the second operand
  1669. * @returns the new Color3
  1670. */
  1671. Color3.prototype.add = function (otherColor) {
  1672. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  1673. };
  1674. /**
  1675. * Stores the result of the addition of the current Color3 and passed one rgb values into "result"
  1676. * @param otherColor defines the second operand
  1677. * @param result defines Color3 object to store the result into
  1678. * @returns the unmodified current Color3
  1679. */
  1680. Color3.prototype.addToRef = function (otherColor, result) {
  1681. result.r = this.r + otherColor.r;
  1682. result.g = this.g + otherColor.g;
  1683. result.b = this.b + otherColor.b;
  1684. return this;
  1685. };
  1686. /**
  1687. * Returns a new Color3 set with the subtracted values of the passed one from the current Color3
  1688. * @param otherColor defines the second operand
  1689. * @returns the new Color3
  1690. */
  1691. Color3.prototype.subtract = function (otherColor) {
  1692. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  1693. };
  1694. /**
  1695. * Stores the result of the subtraction of passed one from the current Color3 rgb values into "result"
  1696. * @param otherColor defines the second operand
  1697. * @param result defines Color3 object to store the result into
  1698. * @returns the unmodified current Color3
  1699. */
  1700. Color3.prototype.subtractToRef = function (otherColor, result) {
  1701. result.r = this.r - otherColor.r;
  1702. result.g = this.g - otherColor.g;
  1703. result.b = this.b - otherColor.b;
  1704. return this;
  1705. };
  1706. /**
  1707. * Copy the current object
  1708. * @returns a new Color3 copied the current one
  1709. */
  1710. Color3.prototype.clone = function () {
  1711. return new Color3(this.r, this.g, this.b);
  1712. };
  1713. /**
  1714. * Copies the rgb values from the source in the current Color3
  1715. * @param source defines the source Color3 object
  1716. * @returns the updated Color3 object
  1717. */
  1718. Color3.prototype.copyFrom = function (source) {
  1719. this.r = source.r;
  1720. this.g = source.g;
  1721. this.b = source.b;
  1722. return this;
  1723. };
  1724. /**
  1725. * Updates the Color3 rgb values from the passed floats
  1726. * @param r defines the red component to read from
  1727. * @param g defines the green component to read from
  1728. * @param b defines the blue component to read from
  1729. * @returns the current Color3 object
  1730. */
  1731. Color3.prototype.copyFromFloats = function (r, g, b) {
  1732. this.r = r;
  1733. this.g = g;
  1734. this.b = b;
  1735. return this;
  1736. };
  1737. /**
  1738. * Updates the Color3 rgb values from the passed floats
  1739. * @param r defines the red component to read from
  1740. * @param g defines the green component to read from
  1741. * @param b defines the blue component to read from
  1742. * @returns the current Color3 object
  1743. */
  1744. Color3.prototype.set = function (r, g, b) {
  1745. return this.copyFromFloats(r, g, b);
  1746. };
  1747. /**
  1748. * Compute the Color3 hexadecimal code as a string
  1749. * @returns a string containing the hexadecimal representation of the Color3 object
  1750. */
  1751. Color3.prototype.toHexString = function () {
  1752. var intR = (this.r * 255) | 0;
  1753. var intG = (this.g * 255) | 0;
  1754. var intB = (this.b * 255) | 0;
  1755. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  1756. };
  1757. /**
  1758. * Computes a new Color3 converted from the current one to linear space
  1759. * @returns a new Color3 object
  1760. */
  1761. Color3.prototype.toLinearSpace = function () {
  1762. var convertedColor = new Color3();
  1763. this.toLinearSpaceToRef(convertedColor);
  1764. return convertedColor;
  1765. };
  1766. /**
  1767. * Converts the Color3 values to linear space and stores the result in "convertedColor"
  1768. * @param convertedColor defines the Color3 object where to store the linear space version
  1769. * @returns the unmodified Color3
  1770. */
  1771. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  1772. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1773. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1774. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1775. return this;
  1776. };
  1777. /**
  1778. * Computes a new Color3 converted from the current one to gamma space
  1779. * @returns a new Color3 object
  1780. */
  1781. Color3.prototype.toGammaSpace = function () {
  1782. var convertedColor = new Color3();
  1783. this.toGammaSpaceToRef(convertedColor);
  1784. return convertedColor;
  1785. };
  1786. /**
  1787. * Converts the Color3 values to gamma space and stores the result in "convertedColor"
  1788. * @param convertedColor defines the Color3 object where to store the gamma space version
  1789. * @returns the unmodified Color3
  1790. */
  1791. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  1792. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1793. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1794. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1795. return this;
  1796. };
  1797. // Statics
  1798. /**
  1799. * Creates a new Color3 from the string containing valid hexadecimal values
  1800. * @param hex defines a string containing valid hexadecimal values
  1801. * @returns a new Color3 object
  1802. */
  1803. Color3.FromHexString = function (hex) {
  1804. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  1805. return new Color3(0, 0, 0);
  1806. }
  1807. var r = parseInt(hex.substring(1, 3), 16);
  1808. var g = parseInt(hex.substring(3, 5), 16);
  1809. var b = parseInt(hex.substring(5, 7), 16);
  1810. return Color3.FromInts(r, g, b);
  1811. };
  1812. /**
  1813. * Creates a new Vector3 from the starting index of the passed array
  1814. * @param array defines the source array
  1815. * @param offset defines an offset in the source array
  1816. * @returns a new Color3 object
  1817. */
  1818. Color3.FromArray = function (array, offset) {
  1819. if (offset === void 0) { offset = 0; }
  1820. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  1821. };
  1822. /**
  1823. * Creates a new Color3 from integer values (< 256)
  1824. * @param r defines the red component to read from (value between 0 and 255)
  1825. * @param g defines the green component to read from (value between 0 and 255)
  1826. * @param b defines the blue component to read from (value between 0 and 255)
  1827. * @returns a new Color3 object
  1828. */
  1829. Color3.FromInts = function (r, g, b) {
  1830. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  1831. };
  1832. /**
  1833. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  1834. * @param start defines the start Color3 value
  1835. * @param end defines the end Color3 value
  1836. * @param amount defines the gradient value between start and end
  1837. * @returns a new Color3 object
  1838. */
  1839. Color3.Lerp = function (start, end, amount) {
  1840. var r = start.r + ((end.r - start.r) * amount);
  1841. var g = start.g + ((end.g - start.g) * amount);
  1842. var b = start.b + ((end.b - start.b) * amount);
  1843. return new Color3(r, g, b);
  1844. };
  1845. /**
  1846. * Returns a Color3 value containing a red color
  1847. * @returns a new Color3 object
  1848. */
  1849. Color3.Red = function () { return new Color3(1, 0, 0); };
  1850. /**
  1851. * Returns a Color3 value containing a green color
  1852. * @returns a new Color3 object
  1853. */
  1854. Color3.Green = function () { return new Color3(0, 1, 0); };
  1855. /**
  1856. * Returns a Color3 value containing a blue color
  1857. * @returns a new Color3 object
  1858. */
  1859. Color3.Blue = function () { return new Color3(0, 0, 1); };
  1860. /**
  1861. * Returns a Color3 value containing a black color
  1862. * @returns a new Color3 object
  1863. */
  1864. Color3.Black = function () { return new Color3(0, 0, 0); };
  1865. /**
  1866. * Returns a Color3 value containing a white color
  1867. * @returns a new Color3 object
  1868. */
  1869. Color3.White = function () { return new Color3(1, 1, 1); };
  1870. /**
  1871. * Returns a Color3 value containing a purple color
  1872. * @returns a new Color3 object
  1873. */
  1874. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  1875. /**
  1876. * Returns a Color3 value containing a magenta color
  1877. * @returns a new Color3 object
  1878. */
  1879. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  1880. /**
  1881. * Returns a Color3 value containing a yellow color
  1882. * @returns a new Color3 object
  1883. */
  1884. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  1885. /**
  1886. * Returns a Color3 value containing a gray color
  1887. * @returns a new Color3 object
  1888. */
  1889. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  1890. /**
  1891. * Returns a Color3 value containing a teal color
  1892. * @returns a new Color3 object
  1893. */
  1894. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  1895. /**
  1896. * Returns a Color3 value containing a random color
  1897. * @returns a new Color3 object
  1898. */
  1899. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  1900. return Color3;
  1901. }());
  1902. BABYLON.Color3 = Color3;
  1903. /**
  1904. * Class used to hold a RBGA color
  1905. */
  1906. var Color4 = /** @class */ (function () {
  1907. /**
  1908. * Creates a new Color4 object from red, green, blue values, all between 0 and 1
  1909. * @param r defines the red component (between 0 and 1, default is 0)
  1910. * @param g defines the green component (between 0 and 1, default is 0)
  1911. * @param b defines the blue component (between 0 and 1, default is 0)
  1912. * @param a defines the alpha component (between 0 and 1, default is 1)
  1913. */
  1914. function Color4(
  1915. /**
  1916. * Defines the red component (between 0 and 1, default is 0)
  1917. */
  1918. r,
  1919. /**
  1920. * Defines the green component (between 0 and 1, default is 0)
  1921. */
  1922. g,
  1923. /**
  1924. * Defines the blue component (between 0 and 1, default is 0)
  1925. */
  1926. b,
  1927. /**
  1928. * Defines the alpha component (between 0 and 1, default is 1)
  1929. */
  1930. a) {
  1931. if (r === void 0) { r = 0; }
  1932. if (g === void 0) { g = 0; }
  1933. if (b === void 0) { b = 0; }
  1934. if (a === void 0) { a = 1; }
  1935. this.r = r;
  1936. this.g = g;
  1937. this.b = b;
  1938. this.a = a;
  1939. }
  1940. // Operators
  1941. /**
  1942. * Adds in place the passed Color4 values to the current Color4 object
  1943. * @param right defines the second operand
  1944. * @returns the current updated Color4 object
  1945. */
  1946. Color4.prototype.addInPlace = function (right) {
  1947. this.r += right.r;
  1948. this.g += right.g;
  1949. this.b += right.b;
  1950. this.a += right.a;
  1951. return this;
  1952. };
  1953. /**
  1954. * Creates a new array populated with 4 numeric elements : red, green, blue, alpha values
  1955. * @returns the new array
  1956. */
  1957. Color4.prototype.asArray = function () {
  1958. var result = new Array();
  1959. this.toArray(result, 0);
  1960. return result;
  1961. };
  1962. /**
  1963. * Stores from the starting index in the passed array the Color4 successive values
  1964. * @param array defines the array where to store the r,g,b components
  1965. * @param index defines an optional index in the target array to define where to start storing values
  1966. * @returns the current Color4 object
  1967. */
  1968. Color4.prototype.toArray = function (array, index) {
  1969. if (index === undefined) {
  1970. index = 0;
  1971. }
  1972. array[index] = this.r;
  1973. array[index + 1] = this.g;
  1974. array[index + 2] = this.b;
  1975. array[index + 3] = this.a;
  1976. return this;
  1977. };
  1978. /**
  1979. * Creates a new Color4 set with the added values of the current Color4 and of the passed one
  1980. * @param right defines the second operand
  1981. * @returns a new Color4 object
  1982. */
  1983. Color4.prototype.add = function (right) {
  1984. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  1985. };
  1986. /**
  1987. * Creates a new Color4 set with the subtracted values of the passed one from the current Color4
  1988. * @param right defines the second operand
  1989. * @returns a new Color4 object
  1990. */
  1991. Color4.prototype.subtract = function (right) {
  1992. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  1993. };
  1994. /**
  1995. * Subtracts the passed ones from the current Color4 values and stores the results in "result"
  1996. * @param right defines the second operand
  1997. * @param result defines the Color4 object where to store the result
  1998. * @returns the current Color4 object
  1999. */
  2000. Color4.prototype.subtractToRef = function (right, result) {
  2001. result.r = this.r - right.r;
  2002. result.g = this.g - right.g;
  2003. result.b = this.b - right.b;
  2004. result.a = this.a - right.a;
  2005. return this;
  2006. };
  2007. /**
  2008. * Creates a new Color4 with the current Color4 values multiplied by scale
  2009. * @param scale defines the scaling factor to apply
  2010. * @returns a new Color4 object
  2011. */
  2012. Color4.prototype.scale = function (scale) {
  2013. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  2014. };
  2015. /**
  2016. * Multiplies the current Color4 values by scale and stores the result in "result"
  2017. * @param scale defines the scaling factor to apply
  2018. * @param result defines the Color4 object where to store the result
  2019. * @returns the current Color4.
  2020. */
  2021. Color4.prototype.scaleToRef = function (scale, result) {
  2022. result.r = this.r * scale;
  2023. result.g = this.g * scale;
  2024. result.b = this.b * scale;
  2025. result.a = this.a * scale;
  2026. return this;
  2027. };
  2028. /**
  2029. * Clamps the rgb values by the min and max values and stores the result into "result"
  2030. * @param min defines minimum clamping value (default is 0)
  2031. * @param max defines maximum clamping value (default is 1)
  2032. * @param result defines color to store the result into.
  2033. * @returns the cuurent Color4
  2034. */
  2035. Color4.prototype.clampToRef = function (min, max, result) {
  2036. if (min === void 0) { min = 0; }
  2037. if (max === void 0) { max = 1; }
  2038. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  2039. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  2040. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  2041. result.a = BABYLON.Scalar.Clamp(this.a, min, max);
  2042. return this;
  2043. };
  2044. /**
  2045. * Multipy an Color4 value by another and return a new Color4 object
  2046. * @param color defines the Color4 value to multiply by
  2047. * @returns a new Color4 object
  2048. */
  2049. Color4.prototype.multiply = function (color) {
  2050. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  2051. };
  2052. /**
  2053. * Multipy a Color4 value by another and push the result in a reference value
  2054. * @param color defines the Color4 value to multiply by
  2055. * @param result defines the Color4 to fill the result in
  2056. * @returns the result Color4
  2057. */
  2058. Color4.prototype.multiplyToRef = function (color, result) {
  2059. result.r = this.r * color.r;
  2060. result.g = this.g * color.g;
  2061. result.b = this.b * color.b;
  2062. result.a = this.a * color.a;
  2063. return result;
  2064. };
  2065. /**
  2066. * Creates a string with the Color4 current values
  2067. * @returns the string representation of the Color4 object
  2068. */
  2069. Color4.prototype.toString = function () {
  2070. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  2071. };
  2072. /**
  2073. * Returns the string "Color4"
  2074. * @returns "Color4"
  2075. */
  2076. Color4.prototype.getClassName = function () {
  2077. return "Color4";
  2078. };
  2079. /**
  2080. * Compute the Color4 hash code
  2081. * @returns an unique number that can be used to hash Color4 objects
  2082. */
  2083. Color4.prototype.getHashCode = function () {
  2084. var hash = this.r || 0;
  2085. hash = (hash * 397) ^ (this.g || 0);
  2086. hash = (hash * 397) ^ (this.b || 0);
  2087. hash = (hash * 397) ^ (this.a || 0);
  2088. return hash;
  2089. };
  2090. /**
  2091. * Creates a new Color4 copied from the current one
  2092. * @returns a new Color4 object
  2093. */
  2094. Color4.prototype.clone = function () {
  2095. return new Color4(this.r, this.g, this.b, this.a);
  2096. };
  2097. /**
  2098. * Copies the passed Color4 values into the current one
  2099. * @param source defines the source Color4 object
  2100. * @returns the current updated Color4 object
  2101. */
  2102. Color4.prototype.copyFrom = function (source) {
  2103. this.r = source.r;
  2104. this.g = source.g;
  2105. this.b = source.b;
  2106. this.a = source.a;
  2107. return this;
  2108. };
  2109. /**
  2110. * Copies the passed float values into the current one
  2111. * @param r defines the red component to read from
  2112. * @param g defines the green component to read from
  2113. * @param b defines the blue component to read from
  2114. * @param a defines the alpha component to read from
  2115. * @returns the current updated Color4 object
  2116. */
  2117. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  2118. this.r = r;
  2119. this.g = g;
  2120. this.b = b;
  2121. this.a = a;
  2122. return this;
  2123. };
  2124. /**
  2125. * Copies the passed float values into the current one
  2126. * @param r defines the red component to read from
  2127. * @param g defines the green component to read from
  2128. * @param b defines the blue component to read from
  2129. * @param a defines the alpha component to read from
  2130. * @returns the current updated Color4 object
  2131. */
  2132. Color4.prototype.set = function (r, g, b, a) {
  2133. return this.copyFromFloats(r, g, b, a);
  2134. };
  2135. /**
  2136. * Compute the Color4 hexadecimal code as a string
  2137. * @returns a string containing the hexadecimal representation of the Color4 object
  2138. */
  2139. Color4.prototype.toHexString = function () {
  2140. var intR = (this.r * 255) | 0;
  2141. var intG = (this.g * 255) | 0;
  2142. var intB = (this.b * 255) | 0;
  2143. var intA = (this.a * 255) | 0;
  2144. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  2145. };
  2146. /**
  2147. * Computes a new Color4 converted from the current one to linear space
  2148. * @returns a new Color4 object
  2149. */
  2150. Color4.prototype.toLinearSpace = function () {
  2151. var convertedColor = new Color4();
  2152. this.toLinearSpaceToRef(convertedColor);
  2153. return convertedColor;
  2154. };
  2155. /**
  2156. * Converts the Color4 values to linear space and stores the result in "convertedColor"
  2157. * @param convertedColor defines the Color4 object where to store the linear space version
  2158. * @returns the unmodified Color4
  2159. */
  2160. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  2161. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  2162. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  2163. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  2164. convertedColor.a = this.a;
  2165. return this;
  2166. };
  2167. /**
  2168. * Computes a new Color4 converted from the current one to gamma space
  2169. * @returns a new Color4 object
  2170. */
  2171. Color4.prototype.toGammaSpace = function () {
  2172. var convertedColor = new Color4();
  2173. this.toGammaSpaceToRef(convertedColor);
  2174. return convertedColor;
  2175. };
  2176. /**
  2177. * Converts the Color4 values to gamma space and stores the result in "convertedColor"
  2178. * @param convertedColor defines the Color4 object where to store the gamma space version
  2179. * @returns the unmodified Color4
  2180. */
  2181. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  2182. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  2183. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  2184. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  2185. convertedColor.a = this.a;
  2186. return this;
  2187. };
  2188. // Statics
  2189. /**
  2190. * Creates a new Color4 from the string containing valid hexadecimal values
  2191. * @param hex defines a string containing valid hexadecimal values
  2192. * @returns a new Color4 object
  2193. */
  2194. Color4.FromHexString = function (hex) {
  2195. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  2196. return new Color4(0.0, 0.0, 0.0, 0.0);
  2197. }
  2198. var r = parseInt(hex.substring(1, 3), 16);
  2199. var g = parseInt(hex.substring(3, 5), 16);
  2200. var b = parseInt(hex.substring(5, 7), 16);
  2201. var a = parseInt(hex.substring(7, 9), 16);
  2202. return Color4.FromInts(r, g, b, a);
  2203. };
  2204. /**
  2205. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2206. * @param left defines the start value
  2207. * @param right defines the end value
  2208. * @param amount defines the gradient factor
  2209. * @returns a new Color4 object
  2210. */
  2211. Color4.Lerp = function (left, right, amount) {
  2212. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  2213. Color4.LerpToRef(left, right, amount, result);
  2214. return result;
  2215. };
  2216. /**
  2217. * Set the passed "result" with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2218. * @param left defines the start value
  2219. * @param right defines the end value
  2220. * @param amount defines the gradient factor
  2221. * @param result defines the Color4 object where to store data
  2222. */
  2223. Color4.LerpToRef = function (left, right, amount, result) {
  2224. result.r = left.r + (right.r - left.r) * amount;
  2225. result.g = left.g + (right.g - left.g) * amount;
  2226. result.b = left.b + (right.b - left.b) * amount;
  2227. result.a = left.a + (right.a - left.a) * amount;
  2228. };
  2229. /**
  2230. * Creates a new Color4 from the starting index element of the passed array
  2231. * @param array defines the source array to read from
  2232. * @param offset defines the offset in the source array
  2233. * @returns a new Color4 object
  2234. */
  2235. Color4.FromArray = function (array, offset) {
  2236. if (offset === void 0) { offset = 0; }
  2237. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2238. };
  2239. /**
  2240. * Creates a new Color3 from integer values (< 256)
  2241. * @param r defines the red component to read from (value between 0 and 255)
  2242. * @param g defines the green component to read from (value between 0 and 255)
  2243. * @param b defines the blue component to read from (value between 0 and 255)
  2244. * @param a defines the alpha component to read from (value between 0 and 255)
  2245. * @returns a new Color3 object
  2246. */
  2247. Color4.FromInts = function (r, g, b, a) {
  2248. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  2249. };
  2250. /**
  2251. * Check the content of a given array and convert it to an array containing RGBA data
  2252. * If the original array was already containing count * 4 values then it is returned directly
  2253. * @param colors defines the array to check
  2254. * @param count defines the number of RGBA data to expect
  2255. * @returns an array containing count * 4 values (RGBA)
  2256. */
  2257. Color4.CheckColors4 = function (colors, count) {
  2258. // Check if color3 was used
  2259. if (colors.length === count * 3) {
  2260. var colors4 = [];
  2261. for (var index = 0; index < colors.length; index += 3) {
  2262. var newIndex = (index / 3) * 4;
  2263. colors4[newIndex] = colors[index];
  2264. colors4[newIndex + 1] = colors[index + 1];
  2265. colors4[newIndex + 2] = colors[index + 2];
  2266. colors4[newIndex + 3] = 1.0;
  2267. }
  2268. return colors4;
  2269. }
  2270. return colors;
  2271. };
  2272. return Color4;
  2273. }());
  2274. BABYLON.Color4 = Color4;
  2275. var Vector2 = /** @class */ (function () {
  2276. /**
  2277. * Creates a new Vector2 from the passed x and y coordinates.
  2278. */
  2279. function Vector2(x, y) {
  2280. this.x = x;
  2281. this.y = y;
  2282. }
  2283. /**
  2284. * Returns a string with the Vector2 coordinates.
  2285. */
  2286. Vector2.prototype.toString = function () {
  2287. return "{X: " + this.x + " Y:" + this.y + "}";
  2288. };
  2289. /**
  2290. * Returns the string "Vector2"
  2291. */
  2292. Vector2.prototype.getClassName = function () {
  2293. return "Vector2";
  2294. };
  2295. /**
  2296. * Returns the Vector2 hash code as a number.
  2297. */
  2298. Vector2.prototype.getHashCode = function () {
  2299. var hash = this.x || 0;
  2300. hash = (hash * 397) ^ (this.y || 0);
  2301. return hash;
  2302. };
  2303. // Operators
  2304. /**
  2305. * Sets the Vector2 coordinates in the passed array or Float32Array from the passed index.
  2306. * Returns the Vector2.
  2307. */
  2308. Vector2.prototype.toArray = function (array, index) {
  2309. if (index === void 0) { index = 0; }
  2310. array[index] = this.x;
  2311. array[index + 1] = this.y;
  2312. return this;
  2313. };
  2314. /**
  2315. * Returns a new array with 2 elements : the Vector2 coordinates.
  2316. */
  2317. Vector2.prototype.asArray = function () {
  2318. var result = new Array();
  2319. this.toArray(result, 0);
  2320. return result;
  2321. };
  2322. /**
  2323. * Sets the Vector2 coordinates with the passed Vector2 coordinates.
  2324. * Returns the updated Vector2.
  2325. */
  2326. Vector2.prototype.copyFrom = function (source) {
  2327. this.x = source.x;
  2328. this.y = source.y;
  2329. return this;
  2330. };
  2331. /**
  2332. * Sets the Vector2 coordinates with the passed floats.
  2333. * Returns the updated Vector2.
  2334. */
  2335. Vector2.prototype.copyFromFloats = function (x, y) {
  2336. this.x = x;
  2337. this.y = y;
  2338. return this;
  2339. };
  2340. /**
  2341. * Sets the Vector2 coordinates with the passed floats.
  2342. * Returns the updated Vector2.
  2343. */
  2344. Vector2.prototype.set = function (x, y) {
  2345. return this.copyFromFloats(x, y);
  2346. };
  2347. /**
  2348. * Returns a new Vector2 set with the addition of the current Vector2 and the passed one coordinates.
  2349. */
  2350. Vector2.prototype.add = function (otherVector) {
  2351. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2352. };
  2353. /**
  2354. * Sets the "result" coordinates with the addition of the current Vector2 and the passed one coordinates.
  2355. * Returns the Vector2.
  2356. */
  2357. Vector2.prototype.addToRef = function (otherVector, result) {
  2358. result.x = this.x + otherVector.x;
  2359. result.y = this.y + otherVector.y;
  2360. return this;
  2361. };
  2362. /**
  2363. * Set the Vector2 coordinates by adding the passed Vector2 coordinates.
  2364. * Returns the updated Vector2.
  2365. */
  2366. Vector2.prototype.addInPlace = function (otherVector) {
  2367. this.x += otherVector.x;
  2368. this.y += otherVector.y;
  2369. return this;
  2370. };
  2371. /**
  2372. * Returns a new Vector2 by adding the current Vector2 coordinates to the passed Vector3 x, y coordinates.
  2373. */
  2374. Vector2.prototype.addVector3 = function (otherVector) {
  2375. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2376. };
  2377. /**
  2378. * Returns a new Vector2 set with the subtracted coordinates of the passed one from the current Vector2.
  2379. */
  2380. Vector2.prototype.subtract = function (otherVector) {
  2381. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  2382. };
  2383. /**
  2384. * Sets the "result" coordinates with the subtraction of the passed one from the current Vector2 coordinates.
  2385. * Returns the Vector2.
  2386. */
  2387. Vector2.prototype.subtractToRef = function (otherVector, result) {
  2388. result.x = this.x - otherVector.x;
  2389. result.y = this.y - otherVector.y;
  2390. return this;
  2391. };
  2392. /**
  2393. * Sets the current Vector2 coordinates by subtracting from it the passed one coordinates.
  2394. * Returns the updated Vector2.
  2395. */
  2396. Vector2.prototype.subtractInPlace = function (otherVector) {
  2397. this.x -= otherVector.x;
  2398. this.y -= otherVector.y;
  2399. return this;
  2400. };
  2401. /**
  2402. * Multiplies in place the current Vector2 coordinates by the passed ones.
  2403. * Returns the updated Vector2.
  2404. */
  2405. Vector2.prototype.multiplyInPlace = function (otherVector) {
  2406. this.x *= otherVector.x;
  2407. this.y *= otherVector.y;
  2408. return this;
  2409. };
  2410. /**
  2411. * Returns a new Vector2 set with the multiplication of the current Vector2 and the passed one coordinates.
  2412. */
  2413. Vector2.prototype.multiply = function (otherVector) {
  2414. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  2415. };
  2416. /**
  2417. * Sets "result" coordinates with the multiplication of the current Vector2 and the passed one coordinates.
  2418. * Returns the Vector2.
  2419. */
  2420. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  2421. result.x = this.x * otherVector.x;
  2422. result.y = this.y * otherVector.y;
  2423. return this;
  2424. };
  2425. /**
  2426. * Returns a new Vector2 set with the Vector2 coordinates multiplied by the passed floats.
  2427. */
  2428. Vector2.prototype.multiplyByFloats = function (x, y) {
  2429. return new Vector2(this.x * x, this.y * y);
  2430. };
  2431. /**
  2432. * Returns a new Vector2 set with the Vector2 coordinates divided by the passed one coordinates.
  2433. */
  2434. Vector2.prototype.divide = function (otherVector) {
  2435. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  2436. };
  2437. /**
  2438. * Sets the "result" coordinates with the Vector2 divided by the passed one coordinates.
  2439. * Returns the Vector2.
  2440. */
  2441. Vector2.prototype.divideToRef = function (otherVector, result) {
  2442. result.x = this.x / otherVector.x;
  2443. result.y = this.y / otherVector.y;
  2444. return this;
  2445. };
  2446. /**
  2447. * Divides the current Vector3 coordinates by the passed ones.
  2448. * Returns the updated Vector3.
  2449. */
  2450. Vector2.prototype.divideInPlace = function (otherVector) {
  2451. return this.divideToRef(otherVector, this);
  2452. };
  2453. /**
  2454. * Returns a new Vector2 with current Vector2 negated coordinates.
  2455. */
  2456. Vector2.prototype.negate = function () {
  2457. return new Vector2(-this.x, -this.y);
  2458. };
  2459. /**
  2460. * Multiply the Vector2 coordinates by scale.
  2461. * Returns the updated Vector2.
  2462. */
  2463. Vector2.prototype.scaleInPlace = function (scale) {
  2464. this.x *= scale;
  2465. this.y *= scale;
  2466. return this;
  2467. };
  2468. /**
  2469. * Returns a new Vector2 scaled by "scale" from the current Vector2.
  2470. */
  2471. Vector2.prototype.scale = function (scale) {
  2472. return new Vector2(this.x * scale, this.y * scale);
  2473. };
  2474. /**
  2475. * Boolean : True if the passed vector coordinates strictly equal the current Vector2 ones.
  2476. */
  2477. Vector2.prototype.equals = function (otherVector) {
  2478. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  2479. };
  2480. /**
  2481. * Boolean : True if the passed vector coordinates are close to the current ones by a distance of epsilon.
  2482. */
  2483. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2484. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2485. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  2486. };
  2487. // Properties
  2488. /**
  2489. * Returns the vector length (float).
  2490. */
  2491. Vector2.prototype.length = function () {
  2492. return Math.sqrt(this.x * this.x + this.y * this.y);
  2493. };
  2494. /**
  2495. * Returns the vector squared length (float);
  2496. */
  2497. Vector2.prototype.lengthSquared = function () {
  2498. return (this.x * this.x + this.y * this.y);
  2499. };
  2500. // Methods
  2501. /**
  2502. * Normalize the vector.
  2503. * Returns the updated Vector2.
  2504. */
  2505. Vector2.prototype.normalize = function () {
  2506. var len = this.length();
  2507. if (len === 0)
  2508. return this;
  2509. var num = 1.0 / len;
  2510. this.x *= num;
  2511. this.y *= num;
  2512. return this;
  2513. };
  2514. /**
  2515. * Returns a new Vector2 copied from the Vector2.
  2516. */
  2517. Vector2.prototype.clone = function () {
  2518. return new Vector2(this.x, this.y);
  2519. };
  2520. // Statics
  2521. /**
  2522. * Returns a new Vector2(0, 0)
  2523. */
  2524. Vector2.Zero = function () {
  2525. return new Vector2(0, 0);
  2526. };
  2527. /**
  2528. * Returns a new Vector2(1, 1)
  2529. */
  2530. Vector2.One = function () {
  2531. return new Vector2(1, 1);
  2532. };
  2533. /**
  2534. * Returns a new Vector2 set from the passed index element of the passed array.
  2535. */
  2536. Vector2.FromArray = function (array, offset) {
  2537. if (offset === void 0) { offset = 0; }
  2538. return new Vector2(array[offset], array[offset + 1]);
  2539. };
  2540. /**
  2541. * Sets "result" from the passed index element of the passed array.
  2542. */
  2543. Vector2.FromArrayToRef = function (array, offset, result) {
  2544. result.x = array[offset];
  2545. result.y = array[offset + 1];
  2546. };
  2547. /**
  2548. * Retuns a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the passed four Vector2.
  2549. */
  2550. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  2551. var squared = amount * amount;
  2552. var cubed = amount * squared;
  2553. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  2554. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  2555. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  2556. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  2557. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  2558. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  2559. return new Vector2(x, y);
  2560. };
  2561. /**
  2562. * 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".
  2563. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  2564. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate.
  2565. */
  2566. Vector2.Clamp = function (value, min, max) {
  2567. var x = value.x;
  2568. x = (x > max.x) ? max.x : x;
  2569. x = (x < min.x) ? min.x : x;
  2570. var y = value.y;
  2571. y = (y > max.y) ? max.y : y;
  2572. y = (y < min.y) ? min.y : y;
  2573. return new Vector2(x, y);
  2574. };
  2575. /**
  2576. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2".
  2577. */
  2578. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2579. var squared = amount * amount;
  2580. var cubed = amount * squared;
  2581. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2582. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2583. var part3 = (cubed - (2.0 * squared)) + amount;
  2584. var part4 = cubed - squared;
  2585. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2586. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2587. return new Vector2(x, y);
  2588. };
  2589. /**
  2590. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  2591. */
  2592. Vector2.Lerp = function (start, end, amount) {
  2593. var x = start.x + ((end.x - start.x) * amount);
  2594. var y = start.y + ((end.y - start.y) * amount);
  2595. return new Vector2(x, y);
  2596. };
  2597. /**
  2598. * Returns the dot product (float) of the vector "left" and the vector "right".
  2599. */
  2600. Vector2.Dot = function (left, right) {
  2601. return left.x * right.x + left.y * right.y;
  2602. };
  2603. /**
  2604. * Returns a new Vector2 equal to the normalized passed vector.
  2605. */
  2606. Vector2.Normalize = function (vector) {
  2607. var newVector = vector.clone();
  2608. newVector.normalize();
  2609. return newVector;
  2610. };
  2611. /**
  2612. * Returns a new Vecto2 set with the minimal coordinate values from the "left" and "right" vectors.
  2613. */
  2614. Vector2.Minimize = function (left, right) {
  2615. var x = (left.x < right.x) ? left.x : right.x;
  2616. var y = (left.y < right.y) ? left.y : right.y;
  2617. return new Vector2(x, y);
  2618. };
  2619. /**
  2620. * Returns a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors.
  2621. */
  2622. Vector2.Maximize = function (left, right) {
  2623. var x = (left.x > right.x) ? left.x : right.x;
  2624. var y = (left.y > right.y) ? left.y : right.y;
  2625. return new Vector2(x, y);
  2626. };
  2627. /**
  2628. * Returns a new Vecto2 set with the transformed coordinates of the passed vector by the passed transformation matrix.
  2629. */
  2630. Vector2.Transform = function (vector, transformation) {
  2631. var r = Vector2.Zero();
  2632. Vector2.TransformToRef(vector, transformation, r);
  2633. return r;
  2634. };
  2635. /**
  2636. * Transforms the passed vector coordinates by the passed transformation matrix and stores the result in the vector "result" coordinates.
  2637. */
  2638. Vector2.TransformToRef = function (vector, transformation, result) {
  2639. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  2640. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  2641. result.x = x;
  2642. result.y = y;
  2643. };
  2644. /**
  2645. * Boolean : True if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  2646. */
  2647. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  2648. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  2649. var sign = a < 0 ? -1 : 1;
  2650. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  2651. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  2652. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  2653. };
  2654. /**
  2655. * Returns the distance (float) between the vectors "value1" and "value2".
  2656. */
  2657. Vector2.Distance = function (value1, value2) {
  2658. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  2659. };
  2660. /**
  2661. * Returns the squared distance (float) between the vectors "value1" and "value2".
  2662. */
  2663. Vector2.DistanceSquared = function (value1, value2) {
  2664. var x = value1.x - value2.x;
  2665. var y = value1.y - value2.y;
  2666. return (x * x) + (y * y);
  2667. };
  2668. /**
  2669. * Returns a new Vecto2 located at the center of the vectors "value1" and "value2".
  2670. */
  2671. Vector2.Center = function (value1, value2) {
  2672. var center = value1.add(value2);
  2673. center.scaleInPlace(0.5);
  2674. return center;
  2675. };
  2676. /**
  2677. * Returns the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  2678. */
  2679. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  2680. var l2 = Vector2.DistanceSquared(segA, segB);
  2681. if (l2 === 0.0) {
  2682. return Vector2.Distance(p, segA);
  2683. }
  2684. var v = segB.subtract(segA);
  2685. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  2686. var proj = segA.add(v.multiplyByFloats(t, t));
  2687. return Vector2.Distance(p, proj);
  2688. };
  2689. return Vector2;
  2690. }());
  2691. BABYLON.Vector2 = Vector2;
  2692. /**
  2693. * Classed used to store (x,y,z) vector representation
  2694. * A Vector3 is the main object used in 3D geometry
  2695. * It can represent etiher the coordinates of a point the space, either a direction
  2696. * Reminder: Babylon.js uses a left handed forward facing system
  2697. */
  2698. var Vector3 = /** @class */ (function () {
  2699. /**
  2700. * Creates a new Vector3 object from the passed x, y, z (floats) coordinates.
  2701. * @param x defines the first coordinates (on X axis)
  2702. * @param y defines the second coordinates (on Y axis)
  2703. * @param z defines the third coordinates (on Z axis)
  2704. */
  2705. function Vector3(
  2706. /**
  2707. * Defines the first coordinates (on X axis)
  2708. */
  2709. x,
  2710. /**
  2711. * Defines the second coordinates (on Y axis)
  2712. */
  2713. y,
  2714. /**
  2715. * Defines the third coordinates (on Z axis)
  2716. */
  2717. z) {
  2718. this.x = x;
  2719. this.y = y;
  2720. this.z = z;
  2721. }
  2722. /**
  2723. * Creates a string representation of the Vector3
  2724. * @returns a string with the Vector3 coordinates.
  2725. */
  2726. Vector3.prototype.toString = function () {
  2727. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  2728. };
  2729. /**
  2730. * Gets the class name
  2731. * @returns the string "Vector3"
  2732. */
  2733. Vector3.prototype.getClassName = function () {
  2734. return "Vector3";
  2735. };
  2736. /**
  2737. * Creates the Vector3 hash code
  2738. * @returns a number which tends to be unique between Vector3 instances
  2739. */
  2740. Vector3.prototype.getHashCode = function () {
  2741. var hash = this.x || 0;
  2742. hash = (hash * 397) ^ (this.y || 0);
  2743. hash = (hash * 397) ^ (this.z || 0);
  2744. return hash;
  2745. };
  2746. // Operators
  2747. /**
  2748. * Creates an array containing three elements : the coordinates of the Vector3
  2749. * @returns a new array of numbers
  2750. */
  2751. Vector3.prototype.asArray = function () {
  2752. var result = [];
  2753. this.toArray(result, 0);
  2754. return result;
  2755. };
  2756. /**
  2757. * Populates the passed array or Float32Array from the passed index with the successive coordinates of the Vector3
  2758. * @param array defines the destination array
  2759. * @param index defines the offset in the destination array
  2760. * @returns the current Vector3
  2761. */
  2762. Vector3.prototype.toArray = function (array, index) {
  2763. if (index === void 0) { index = 0; }
  2764. array[index] = this.x;
  2765. array[index + 1] = this.y;
  2766. array[index + 2] = this.z;
  2767. return this;
  2768. };
  2769. /**
  2770. * Converts the current Vector3 into a quaternion (considering that the Vector3 contains Euler angles representation of a rotation)
  2771. * @returns a new Quaternion object, computed from the Vector3 coordinates
  2772. */
  2773. Vector3.prototype.toQuaternion = function () {
  2774. var result = new Quaternion(0.0, 0.0, 0.0, 1.0);
  2775. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  2776. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  2777. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  2778. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  2779. var cosy = Math.cos(this.y * 0.5);
  2780. var siny = Math.sin(this.y * 0.5);
  2781. result.x = coszMinusx * siny;
  2782. result.y = -sinzMinusx * siny;
  2783. result.z = sinxPlusz * cosy;
  2784. result.w = cosxPlusz * cosy;
  2785. return result;
  2786. };
  2787. /**
  2788. * Adds the passed vector to the current Vector3
  2789. * @param otherVector defines the second operand
  2790. * @returns the current updated Vector3
  2791. */
  2792. Vector3.prototype.addInPlace = function (otherVector) {
  2793. this.x += otherVector.x;
  2794. this.y += otherVector.y;
  2795. this.z += otherVector.z;
  2796. return this;
  2797. };
  2798. /**
  2799. * Gets a new Vector3, result of the addition the current Vector3 and the passed vector
  2800. * @param otherVector defines the second operand
  2801. * @returns the resulting Vector3
  2802. */
  2803. Vector3.prototype.add = function (otherVector) {
  2804. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  2805. };
  2806. /**
  2807. * Adds the current Vector3 to the passed one and stores the result in the vector "result"
  2808. * @param otherVector defines the second operand
  2809. * @param result defines the Vector3 object where to store the result
  2810. * @returns the current Vector3
  2811. */
  2812. Vector3.prototype.addToRef = function (otherVector, result) {
  2813. result.x = this.x + otherVector.x;
  2814. result.y = this.y + otherVector.y;
  2815. result.z = this.z + otherVector.z;
  2816. return this;
  2817. };
  2818. /**
  2819. * Subtract the passed vector from the current Vector3
  2820. * @param otherVector defines the second operand
  2821. * @returns the current updated Vector3
  2822. */
  2823. Vector3.prototype.subtractInPlace = function (otherVector) {
  2824. this.x -= otherVector.x;
  2825. this.y -= otherVector.y;
  2826. this.z -= otherVector.z;
  2827. return this;
  2828. };
  2829. /**
  2830. * Returns a new Vector3, result of the subtraction of the passed vector from the current Vector3
  2831. * @param otherVector defines the second operand
  2832. * @returns the resulting Vector3
  2833. */
  2834. Vector3.prototype.subtract = function (otherVector) {
  2835. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  2836. };
  2837. /**
  2838. * Subtracts the passed vector from the current Vector3 and stores the result in the vector "result".
  2839. * @param otherVector defines the second operand
  2840. * @param result defines the Vector3 object where to store the result
  2841. * @returns the current Vector3
  2842. */
  2843. Vector3.prototype.subtractToRef = function (otherVector, result) {
  2844. result.x = this.x - otherVector.x;
  2845. result.y = this.y - otherVector.y;
  2846. result.z = this.z - otherVector.z;
  2847. return this;
  2848. };
  2849. /**
  2850. * Returns a new Vector3 set with the subtraction of the passed floats from the current Vector3 coordinates
  2851. * @param x defines the x coordinate of the operand
  2852. * @param y defines the y coordinate of the operand
  2853. * @param z defines the z coordinate of the operand
  2854. * @returns the resulting Vector3
  2855. */
  2856. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  2857. return new Vector3(this.x - x, this.y - y, this.z - z);
  2858. };
  2859. /**
  2860. * Subtracts the passed floats from the current Vector3 coordinates and set the passed vector "result" with this result
  2861. * @param x defines the x coordinate of the operand
  2862. * @param y defines the y coordinate of the operand
  2863. * @param z defines the z coordinate of the operand
  2864. * @param result defines the Vector3 object where to store the result
  2865. * @returns the current Vector3
  2866. */
  2867. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  2868. result.x = this.x - x;
  2869. result.y = this.y - y;
  2870. result.z = this.z - z;
  2871. return this;
  2872. };
  2873. /**
  2874. * Gets a new Vector3 set with the current Vector3 negated coordinates
  2875. * @returns a new Vector3
  2876. */
  2877. Vector3.prototype.negate = function () {
  2878. return new Vector3(-this.x, -this.y, -this.z);
  2879. };
  2880. /**
  2881. * Multiplies the Vector3 coordinates by the float "scale"
  2882. * @param scale defines the multiplier factor
  2883. * @returns the current updated Vector3
  2884. */
  2885. Vector3.prototype.scaleInPlace = function (scale) {
  2886. this.x *= scale;
  2887. this.y *= scale;
  2888. this.z *= scale;
  2889. return this;
  2890. };
  2891. /**
  2892. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale"
  2893. * @param scale defines the multiplier factor
  2894. * @returns a new Vector3
  2895. */
  2896. Vector3.prototype.scale = function (scale) {
  2897. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  2898. };
  2899. /**
  2900. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the passed vector "result" coordinates
  2901. * @param scale defines the multiplier factor
  2902. * @param result defines the Vector3 object where to store the result
  2903. * @returns the current Vector3
  2904. */
  2905. Vector3.prototype.scaleToRef = function (scale, result) {
  2906. result.x = this.x * scale;
  2907. result.y = this.y * scale;
  2908. result.z = this.z * scale;
  2909. return this;
  2910. };
  2911. /**
  2912. * Returns true if the current Vector3 and the passed vector coordinates are strictly equal
  2913. * @param otherVector defines the second operand
  2914. * @returns true if both vectors are equals
  2915. */
  2916. Vector3.prototype.equals = function (otherVector) {
  2917. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  2918. };
  2919. /**
  2920. * Returns true if the current Vector3 and the passed vector coordinates are distant less than epsilon
  2921. * @param otherVector defines the second operand
  2922. * @param epsilon defines the minimal distance to define values as equals
  2923. * @returns true if both vectors are distant less than epsilon
  2924. */
  2925. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2926. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2927. 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);
  2928. };
  2929. /**
  2930. * Returns true if the current Vector3 coordinates equals the passed floats
  2931. * @param x defines the x coordinate of the operand
  2932. * @param y defines the y coordinate of the operand
  2933. * @param z defines the z coordinate of the operand
  2934. * @returns true if both vectors are equals
  2935. */
  2936. Vector3.prototype.equalsToFloats = function (x, y, z) {
  2937. return this.x === x && this.y === y && this.z === z;
  2938. };
  2939. /**
  2940. * Multiplies the current Vector3 coordinates by the passed ones
  2941. * @param otherVector defines the second operand
  2942. * @returns the current updated Vector3
  2943. */
  2944. Vector3.prototype.multiplyInPlace = function (otherVector) {
  2945. this.x *= otherVector.x;
  2946. this.y *= otherVector.y;
  2947. this.z *= otherVector.z;
  2948. return this;
  2949. };
  2950. /**
  2951. * Returns a new Vector3, result of the multiplication of the current Vector3 by the passed vector
  2952. * @param otherVector defines the second operand
  2953. * @returns the new Vector3
  2954. */
  2955. Vector3.prototype.multiply = function (otherVector) {
  2956. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  2957. };
  2958. /**
  2959. * Multiplies the current Vector3 by the passed one and stores the result in the passed vector "result"
  2960. * @param otherVector defines the second operand
  2961. * @param result defines the Vector3 object where to store the result
  2962. * @returns the current Vector3
  2963. */
  2964. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  2965. result.x = this.x * otherVector.x;
  2966. result.y = this.y * otherVector.y;
  2967. result.z = this.z * otherVector.z;
  2968. return this;
  2969. };
  2970. /**
  2971. * Returns a new Vector3 set with the result of the mulliplication of the current Vector3 coordinates by the passed floats
  2972. * @param x defines the x coordinate of the operand
  2973. * @param y defines the y coordinate of the operand
  2974. * @param z defines the z coordinate of the operand
  2975. * @returns the new Vector3
  2976. */
  2977. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  2978. return new Vector3(this.x * x, this.y * y, this.z * z);
  2979. };
  2980. /**
  2981. * Returns a new Vector3 set with the result of the division of the current Vector3 coordinates by the passed ones
  2982. * @param otherVector defines the second operand
  2983. * @returns the new Vector3
  2984. */
  2985. Vector3.prototype.divide = function (otherVector) {
  2986. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  2987. };
  2988. /**
  2989. * Divides the current Vector3 coordinates by the passed ones and stores the result in the passed vector "result"
  2990. * @param otherVector defines the second operand
  2991. * @param result defines the Vector3 object where to store the result
  2992. * @returns the current Vector3
  2993. */
  2994. Vector3.prototype.divideToRef = function (otherVector, result) {
  2995. result.x = this.x / otherVector.x;
  2996. result.y = this.y / otherVector.y;
  2997. result.z = this.z / otherVector.z;
  2998. return this;
  2999. };
  3000. /**
  3001. * Divides the current Vector3 coordinates by the passed ones.
  3002. * @param otherVector defines the second operand
  3003. * @returns the current updated Vector3
  3004. */
  3005. Vector3.prototype.divideInPlace = function (otherVector) {
  3006. return this.divideToRef(otherVector, this);
  3007. };
  3008. /**
  3009. * Updates the current Vector3 with the minimal coordinate values between its and the passed vector ones
  3010. * @param other defines the second operand
  3011. * @returns the current updated Vector3
  3012. */
  3013. Vector3.prototype.minimizeInPlace = function (other) {
  3014. if (other.x < this.x)
  3015. this.x = other.x;
  3016. if (other.y < this.y)
  3017. this.y = other.y;
  3018. if (other.z < this.z)
  3019. this.z = other.z;
  3020. return this;
  3021. };
  3022. /**
  3023. * Updates the current Vector3 with the maximal coordinate values between its and the passed vector ones.
  3024. * @param other defines the second operand
  3025. * @returns the current updated Vector3
  3026. */
  3027. Vector3.prototype.maximizeInPlace = function (other) {
  3028. if (other.x > this.x)
  3029. this.x = other.x;
  3030. if (other.y > this.y)
  3031. this.y = other.y;
  3032. if (other.z > this.z)
  3033. this.z = other.z;
  3034. return this;
  3035. };
  3036. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  3037. /**
  3038. * Gets a boolean indicating that the vector is non uniform meaning x, y or z are not all the same
  3039. */
  3040. get: function () {
  3041. var absX = Math.abs(this.x);
  3042. var absY = Math.abs(this.y);
  3043. if (absX !== absY) {
  3044. return true;
  3045. }
  3046. var absZ = Math.abs(this.z);
  3047. if (absX !== absZ) {
  3048. return true;
  3049. }
  3050. if (absY !== absZ) {
  3051. return true;
  3052. }
  3053. return false;
  3054. },
  3055. enumerable: true,
  3056. configurable: true
  3057. });
  3058. // Properties
  3059. /**
  3060. * Gets the length of the Vector3
  3061. * @returns the length of the Vecto3
  3062. */
  3063. Vector3.prototype.length = function () {
  3064. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  3065. };
  3066. /**
  3067. * Gets the squared length of the Vector3
  3068. * @returns squared length of the Vector3
  3069. */
  3070. Vector3.prototype.lengthSquared = function () {
  3071. return (this.x * this.x + this.y * this.y + this.z * this.z);
  3072. };
  3073. /**
  3074. * Normalize the current Vector3.
  3075. * Please note that this is an in place operation.
  3076. * @returns the current updated Vector3
  3077. */
  3078. Vector3.prototype.normalize = function () {
  3079. var len = this.length();
  3080. if (len === 0 || len === 1.0)
  3081. return this;
  3082. var num = 1.0 / len;
  3083. this.x *= num;
  3084. this.y *= num;
  3085. this.z *= num;
  3086. return this;
  3087. };
  3088. /**
  3089. * Normalize the current Vector3 to a new vector
  3090. * @returns the new Vector3
  3091. */
  3092. Vector3.prototype.normalizeToNew = function () {
  3093. var normalized = new Vector3(0, 0, 0);
  3094. this.normalizeToRef(normalized);
  3095. return normalized;
  3096. };
  3097. /**
  3098. * Normalize the current Vector3 to the reference
  3099. * @param reference define the Vector3 to update
  3100. * @returns the updated Vector3
  3101. */
  3102. Vector3.prototype.normalizeToRef = function (reference) {
  3103. var len = this.length();
  3104. if (len === 0 || len === 1.0) {
  3105. reference.set(this.x, this.y, this.z);
  3106. return reference;
  3107. }
  3108. var scale = 1.0 / len;
  3109. this.scaleToRef(scale, reference);
  3110. return reference;
  3111. };
  3112. /**
  3113. * Creates a new Vector3 copied from the current Vector3
  3114. * @returns the new Vector3
  3115. */
  3116. Vector3.prototype.clone = function () {
  3117. return new Vector3(this.x, this.y, this.z);
  3118. };
  3119. /**
  3120. * Copies the passed vector coordinates to the current Vector3 ones
  3121. * @param source defines the source Vector3
  3122. * @returns the current updated Vector3
  3123. */
  3124. Vector3.prototype.copyFrom = function (source) {
  3125. this.x = source.x;
  3126. this.y = source.y;
  3127. this.z = source.z;
  3128. return this;
  3129. };
  3130. /**
  3131. * Copies the passed floats to the current Vector3 coordinates
  3132. * @param x defines the x coordinate of the operand
  3133. * @param y defines the y coordinate of the operand
  3134. * @param z defines the z coordinate of the operand
  3135. * @returns the current updated Vector3
  3136. */
  3137. Vector3.prototype.copyFromFloats = function (x, y, z) {
  3138. this.x = x;
  3139. this.y = y;
  3140. this.z = z;
  3141. return this;
  3142. };
  3143. /**
  3144. * Copies the passed floats to the current Vector3 coordinates
  3145. * @param x defines the x coordinate of the operand
  3146. * @param y defines the y coordinate of the operand
  3147. * @param z defines the z coordinate of the operand
  3148. * @returns the current updated Vector3
  3149. */
  3150. Vector3.prototype.set = function (x, y, z) {
  3151. return this.copyFromFloats(x, y, z);
  3152. };
  3153. // Statics
  3154. /**
  3155. * Get the clip factor between two vectors
  3156. * @param vector0 defines the first operand
  3157. * @param vector1 defines the second operand
  3158. * @param axis defines the axis to use
  3159. * @param size defines the size along the axis
  3160. * @returns the clip factor
  3161. */
  3162. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  3163. var d0 = Vector3.Dot(vector0, axis) - size;
  3164. var d1 = Vector3.Dot(vector1, axis) - size;
  3165. var s = d0 / (d0 - d1);
  3166. return s;
  3167. };
  3168. /**
  3169. * Get angle between two vectors
  3170. * @param vector0 angle between vector0 and vector1
  3171. * @param vector1 angle between vector0 and vector1
  3172. * @param normal direction of the normal
  3173. * @return the angle between vector0 and vector1
  3174. */
  3175. Vector3.GetAngleBetweenVectors = function (vector0, vector1, normal) {
  3176. var v0 = vector0.clone().normalize();
  3177. var v1 = vector1.clone().normalize();
  3178. var dot = Vector3.Dot(v0, v1);
  3179. var n = Vector3.Cross(v0, v1);
  3180. if (Vector3.Dot(n, normal) > 0) {
  3181. return Math.acos(dot);
  3182. }
  3183. return -Math.acos(dot);
  3184. };
  3185. /**
  3186. * Returns a new Vector3 set from the index "offset" of the passed array
  3187. * @param array defines the source array
  3188. * @param offset defines the offset in the source array
  3189. * @returns the new Vector3
  3190. */
  3191. Vector3.FromArray = function (array, offset) {
  3192. if (!offset) {
  3193. offset = 0;
  3194. }
  3195. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  3196. };
  3197. /**
  3198. * Returns a new Vector3 set from the index "offset" of the passed Float32Array
  3199. * This function is deprecated. Use FromArray instead
  3200. * @param array defines the source array
  3201. * @param offset defines the offset in the source array
  3202. * @returns the new Vector3
  3203. */
  3204. Vector3.FromFloatArray = function (array, offset) {
  3205. return Vector3.FromArray(array, offset);
  3206. };
  3207. /**
  3208. * Sets the passed vector "result" with the element values from the index "offset" of the passed array
  3209. * @param array defines the source array
  3210. * @param offset defines the offset in the source array
  3211. * @param result defines the Vector3 where to store the result
  3212. */
  3213. Vector3.FromArrayToRef = function (array, offset, result) {
  3214. result.x = array[offset];
  3215. result.y = array[offset + 1];
  3216. result.z = array[offset + 2];
  3217. };
  3218. /**
  3219. * Sets the passed vector "result" with the element values from the index "offset" of the passed Float32Array
  3220. * This function is deprecated. Use FromArrayToRef instead.
  3221. * @param array defines the source array
  3222. * @param offset defines the offset in the source array
  3223. * @param result defines the Vector3 where to store the result
  3224. */
  3225. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  3226. return Vector3.FromArrayToRef(array, offset, result);
  3227. };
  3228. /**
  3229. * Sets the passed vector "result" with the passed floats.
  3230. * @param x defines the x coordinate of the source
  3231. * @param y defines the y coordinate of the source
  3232. * @param z defines the z coordinate of the source
  3233. * @param result defines the Vector3 where to store the result
  3234. */
  3235. Vector3.FromFloatsToRef = function (x, y, z, result) {
  3236. result.x = x;
  3237. result.y = y;
  3238. result.z = z;
  3239. };
  3240. /**
  3241. * Returns a new Vector3 set to (0.0, 0.0, 0.0)
  3242. * @returns a new empty Vector3
  3243. */
  3244. Vector3.Zero = function () {
  3245. return new Vector3(0.0, 0.0, 0.0);
  3246. };
  3247. /**
  3248. * Returns a new Vector3 set to (1.0, 1.0, 1.0)
  3249. * @returns a new unit Vector3
  3250. */
  3251. Vector3.One = function () {
  3252. return new Vector3(1.0, 1.0, 1.0);
  3253. };
  3254. /**
  3255. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  3256. * @returns a new up Vector3
  3257. */
  3258. Vector3.Up = function () {
  3259. return new Vector3(0.0, 1.0, 0.0);
  3260. };
  3261. /**
  3262. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  3263. * @returns a new forward Vector3
  3264. */
  3265. Vector3.Forward = function () {
  3266. return new Vector3(0.0, 0.0, 1.0);
  3267. };
  3268. /**
  3269. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  3270. * @returns a new right Vector3
  3271. */
  3272. Vector3.Right = function () {
  3273. return new Vector3(1.0, 0.0, 0.0);
  3274. };
  3275. /**
  3276. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  3277. * @returns a new left Vector3
  3278. */
  3279. Vector3.Left = function () {
  3280. return new Vector3(-1.0, 0.0, 0.0);
  3281. };
  3282. /**
  3283. * Returns a new Vector3 set with the result of the transformation by the passed matrix of the passed vector.
  3284. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3285. * @param vector defines the Vector3 to transform
  3286. * @param transformation defines the transformation matrix
  3287. * @returns the transformed Vector3
  3288. */
  3289. Vector3.TransformCoordinates = function (vector, transformation) {
  3290. var result = Vector3.Zero();
  3291. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  3292. return result;
  3293. };
  3294. /**
  3295. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed vector
  3296. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3297. * @param vector defines the Vector3 to transform
  3298. * @param transformation defines the transformation matrix
  3299. * @param result defines the Vector3 where to store the result
  3300. */
  3301. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  3302. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  3303. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  3304. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  3305. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  3306. result.x = x / w;
  3307. result.y = y / w;
  3308. result.z = z / w;
  3309. };
  3310. /**
  3311. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed floats (x, y, z)
  3312. * This method computes tranformed coordinates only, not transformed direction vectors
  3313. * @param x define the x coordinate of the source vector
  3314. * @param y define the y coordinate of the source vector
  3315. * @param z define the z coordinate of the source vector
  3316. * @param transformation defines the transformation matrix
  3317. * @param result defines the Vector3 where to store the result
  3318. */
  3319. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  3320. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  3321. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  3322. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  3323. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  3324. result.x = rx / rw;
  3325. result.y = ry / rw;
  3326. result.z = rz / rw;
  3327. };
  3328. /**
  3329. * Returns a new Vector3 set with the result of the normal transformation by the passed matrix of the passed vector
  3330. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3331. * @param vector defines the Vector3 to transform
  3332. * @param transformation defines the transformation matrix
  3333. * @returns the new Vector3
  3334. */
  3335. Vector3.TransformNormal = function (vector, transformation) {
  3336. var result = Vector3.Zero();
  3337. Vector3.TransformNormalToRef(vector, transformation, result);
  3338. return result;
  3339. };
  3340. /**
  3341. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector
  3342. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3343. * @param vector defines the Vector3 to transform
  3344. * @param transformation defines the transformation matrix
  3345. * @param result defines the Vector3 where to store the result
  3346. */
  3347. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  3348. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3349. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3350. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3351. result.x = x;
  3352. result.y = y;
  3353. result.z = z;
  3354. };
  3355. /**
  3356. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z)
  3357. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3358. * @param x define the x coordinate of the source vector
  3359. * @param y define the y coordinate of the source vector
  3360. * @param z define the z coordinate of the source vector
  3361. * @param transformation defines the transformation matrix
  3362. * @param result defines the Vector3 where to store the result
  3363. */
  3364. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  3365. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  3366. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  3367. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  3368. };
  3369. /**
  3370. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4"
  3371. * @param value1 defines the first control point
  3372. * @param value2 defines the second control point
  3373. * @param value3 defines the third control point
  3374. * @param value4 defines the fourth control point
  3375. * @param amount defines the amount on the spline to use
  3376. * @returns the new Vector3
  3377. */
  3378. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  3379. var squared = amount * amount;
  3380. var cubed = amount * squared;
  3381. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  3382. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  3383. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  3384. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  3385. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  3386. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  3387. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  3388. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  3389. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  3390. return new Vector3(x, y, z);
  3391. };
  3392. /**
  3393. * 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"
  3394. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one
  3395. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one
  3396. * @param value defines the current value
  3397. * @param min defines the lower range value
  3398. * @param max defines the upper range value
  3399. * @returns the new Vector3
  3400. */
  3401. Vector3.Clamp = function (value, min, max) {
  3402. var x = value.x;
  3403. x = (x > max.x) ? max.x : x;
  3404. x = (x < min.x) ? min.x : x;
  3405. var y = value.y;
  3406. y = (y > max.y) ? max.y : y;
  3407. y = (y < min.y) ? min.y : y;
  3408. var z = value.z;
  3409. z = (z > max.z) ? max.z : z;
  3410. z = (z < min.z) ? min.z : z;
  3411. return new Vector3(x, y, z);
  3412. };
  3413. /**
  3414. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2"
  3415. * @param value1 defines the first control point
  3416. * @param tangent1 defines the first tangent vector
  3417. * @param value2 defines the second control point
  3418. * @param tangent2 defines the second tangent vector
  3419. * @param amount defines the amount on the interpolation spline (between 0 and 1)
  3420. * @returns the new Vector3
  3421. */
  3422. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  3423. var squared = amount * amount;
  3424. var cubed = amount * squared;
  3425. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  3426. var part2 = (-2.0 * cubed) + (3.0 * squared);
  3427. var part3 = (cubed - (2.0 * squared)) + amount;
  3428. var part4 = cubed - squared;
  3429. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  3430. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  3431. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  3432. return new Vector3(x, y, z);
  3433. };
  3434. /**
  3435. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end"
  3436. * @param start defines the start value
  3437. * @param end defines the end value
  3438. * @param amount max defines amount between both (between 0 and 1)
  3439. * @returns the new Vector3
  3440. */
  3441. Vector3.Lerp = function (start, end, amount) {
  3442. var result = new Vector3(0, 0, 0);
  3443. Vector3.LerpToRef(start, end, amount, result);
  3444. return result;
  3445. };
  3446. /**
  3447. * Sets the passed vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end"
  3448. * @param start defines the start value
  3449. * @param end defines the end value
  3450. * @param amount max defines amount between both (between 0 and 1)
  3451. * @param result defines the Vector3 where to store the result
  3452. */
  3453. Vector3.LerpToRef = function (start, end, amount, result) {
  3454. result.x = start.x + ((end.x - start.x) * amount);
  3455. result.y = start.y + ((end.y - start.y) * amount);
  3456. result.z = start.z + ((end.z - start.z) * amount);
  3457. };
  3458. /**
  3459. * Returns the dot product (float) between the vectors "left" and "right"
  3460. * @param left defines the left operand
  3461. * @param right defines the right operand
  3462. * @returns the dot product
  3463. */
  3464. Vector3.Dot = function (left, right) {
  3465. return (left.x * right.x + left.y * right.y + left.z * right.z);
  3466. };
  3467. /**
  3468. * Returns a new Vector3 as the cross product of the vectors "left" and "right"
  3469. * The cross product is then orthogonal to both "left" and "right"
  3470. * @param left defines the left operand
  3471. * @param right defines the right operand
  3472. * @returns the cross product
  3473. */
  3474. Vector3.Cross = function (left, right) {
  3475. var result = Vector3.Zero();
  3476. Vector3.CrossToRef(left, right, result);
  3477. return result;
  3478. };
  3479. /**
  3480. * Sets the passed vector "result" with the cross product of "left" and "right"
  3481. * The cross product is then orthogonal to both "left" and "right"
  3482. * @param left defines the left operand
  3483. * @param right defines the right operand
  3484. * @param result defines the Vector3 where to store the result
  3485. */
  3486. Vector3.CrossToRef = function (left, right, result) {
  3487. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  3488. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  3489. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  3490. result.copyFrom(MathTmp.Vector3[0]);
  3491. };
  3492. /**
  3493. * Returns a new Vector3 as the normalization of the passed vector
  3494. * @param vector defines the Vector3 to normalize
  3495. * @returns the new Vector3
  3496. */
  3497. Vector3.Normalize = function (vector) {
  3498. var result = Vector3.Zero();
  3499. Vector3.NormalizeToRef(vector, result);
  3500. return result;
  3501. };
  3502. /**
  3503. * Sets the passed vector "result" with the normalization of the passed first vector
  3504. * @param vector defines the Vector3 to normalize
  3505. * @param result defines the Vector3 where to store the result
  3506. */
  3507. Vector3.NormalizeToRef = function (vector, result) {
  3508. result.copyFrom(vector);
  3509. result.normalize();
  3510. };
  3511. /**
  3512. * Project a Vector3 onto screen space
  3513. * @param vector defines the Vector3 to project
  3514. * @param world defines the world matrix to use
  3515. * @param transform defines the transform (view x projection) matrix to use
  3516. * @param viewport defines the screen viewport to use
  3517. * @returns the new Vector3
  3518. */
  3519. Vector3.Project = function (vector, world, transform, viewport) {
  3520. var cw = viewport.width;
  3521. var ch = viewport.height;
  3522. var cx = viewport.x;
  3523. var cy = viewport.y;
  3524. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  3525. 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);
  3526. var matrix = MathTmp.Matrix[0];
  3527. world.multiplyToRef(transform, matrix);
  3528. matrix.multiplyToRef(viewportMatrix, matrix);
  3529. return Vector3.TransformCoordinates(vector, matrix);
  3530. };
  3531. /**
  3532. * Unproject from screen space to object space
  3533. * @param source defines the screen space Vector3 to use
  3534. * @param viewportWidth defines the current width of the viewport
  3535. * @param viewportHeight defines the current height of the viewport
  3536. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3537. * @param transform defines the transform (view x projection) matrix to use
  3538. * @returns the new Vector3
  3539. */
  3540. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  3541. var matrix = MathTmp.Matrix[0];
  3542. world.multiplyToRef(transform, matrix);
  3543. matrix.invert();
  3544. source.x = source.x / viewportWidth * 2 - 1;
  3545. source.y = -(source.y / viewportHeight * 2 - 1);
  3546. var vector = Vector3.TransformCoordinates(source, matrix);
  3547. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  3548. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3549. vector = vector.scale(1.0 / num);
  3550. }
  3551. return vector;
  3552. };
  3553. /**
  3554. * Unproject from screen space to object space
  3555. * @param source defines the screen space Vector3 to use
  3556. * @param viewportWidth defines the current width of the viewport
  3557. * @param viewportHeight defines the current height of the viewport
  3558. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3559. * @param view defines the view matrix to use
  3560. * @param projection defines the projection matrix to use
  3561. * @returns the new Vector3
  3562. */
  3563. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  3564. var result = Vector3.Zero();
  3565. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  3566. return result;
  3567. };
  3568. /**
  3569. * Unproject from screen space to object space
  3570. * @param source defines the screen space Vector3 to use
  3571. * @param viewportWidth defines the current width of the viewport
  3572. * @param viewportHeight defines the current height of the viewport
  3573. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3574. * @param view defines the view matrix to use
  3575. * @param projection defines the projection matrix to use
  3576. * @param result defines the Vector3 where to store the result
  3577. */
  3578. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  3579. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  3580. };
  3581. /**
  3582. * Unproject from screen space to object space
  3583. * @param sourceX defines the screen space x coordinate to use
  3584. * @param sourceY defines the screen space y coordinate to use
  3585. * @param sourceZ defines the screen space z coordinate to use
  3586. * @param viewportWidth defines the current width of the viewport
  3587. * @param viewportHeight defines the current height of the viewport
  3588. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3589. * @param view defines the view matrix to use
  3590. * @param projection defines the projection matrix to use
  3591. * @param result defines the Vector3 where to store the result
  3592. */
  3593. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  3594. var matrix = MathTmp.Matrix[0];
  3595. world.multiplyToRef(view, matrix);
  3596. matrix.multiplyToRef(projection, matrix);
  3597. matrix.invert();
  3598. var screenSource = MathTmp.Vector3[0];
  3599. screenSource.x = sourceX / viewportWidth * 2 - 1;
  3600. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  3601. screenSource.z = 2 * sourceZ - 1.0;
  3602. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  3603. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  3604. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3605. result.scaleInPlace(1.0 / num);
  3606. }
  3607. };
  3608. /**
  3609. * Gets the minimal coordinate values between two Vector3
  3610. * @param left defines the first operand
  3611. * @param right defines the second operand
  3612. * @returns the new Vector3
  3613. */
  3614. Vector3.Minimize = function (left, right) {
  3615. var min = left.clone();
  3616. min.minimizeInPlace(right);
  3617. return min;
  3618. };
  3619. /**
  3620. * Gets the maximal coordinate values between two Vector3
  3621. * @param left defines the first operand
  3622. * @param right defines the second operand
  3623. * @returns the new Vector3
  3624. */
  3625. Vector3.Maximize = function (left, right) {
  3626. var max = left.clone();
  3627. max.maximizeInPlace(right);
  3628. return max;
  3629. };
  3630. /**
  3631. * Returns the distance between the vectors "value1" and "value2"
  3632. * @param value1 defines the first operand
  3633. * @param value2 defines the second operand
  3634. * @returns the distance
  3635. */
  3636. Vector3.Distance = function (value1, value2) {
  3637. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  3638. };
  3639. /**
  3640. * Returns the squared distance between the vectors "value1" and "value2"
  3641. * @param value1 defines the first operand
  3642. * @param value2 defines the second operand
  3643. * @returns the squared distance
  3644. */
  3645. Vector3.DistanceSquared = function (value1, value2) {
  3646. var x = value1.x - value2.x;
  3647. var y = value1.y - value2.y;
  3648. var z = value1.z - value2.z;
  3649. return (x * x) + (y * y) + (z * z);
  3650. };
  3651. /**
  3652. * Returns a new Vector3 located at the center between "value1" and "value2"
  3653. * @param value1 defines the first operand
  3654. * @param value2 defines the second operand
  3655. * @returns the new Vector3
  3656. */
  3657. Vector3.Center = function (value1, value2) {
  3658. var center = value1.add(value2);
  3659. center.scaleInPlace(0.5);
  3660. return center;
  3661. };
  3662. /**
  3663. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  3664. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  3665. * to something in order to rotate it from its local system to the given target system
  3666. * Note: axis1, axis2 and axis3 are normalized during this operation
  3667. * @param axis1 defines the first axis
  3668. * @param axis2 defines the second axis
  3669. * @param axis3 defines the third axis
  3670. * @returns a new Vector3
  3671. */
  3672. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  3673. var rotation = Vector3.Zero();
  3674. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  3675. return rotation;
  3676. };
  3677. /**
  3678. * The same than RotationFromAxis but updates the passed ref Vector3 parameter instead of returning a new Vector3
  3679. * @param axis1 defines the first axis
  3680. * @param axis2 defines the second axis
  3681. * @param axis3 defines the third axis
  3682. * @param ref defines the Vector3 where to store the result
  3683. */
  3684. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  3685. var quat = MathTmp.Quaternion[0];
  3686. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  3687. quat.toEulerAnglesToRef(ref);
  3688. };
  3689. return Vector3;
  3690. }());
  3691. BABYLON.Vector3 = Vector3;
  3692. //Vector4 class created for EulerAngle class conversion to Quaternion
  3693. var Vector4 = /** @class */ (function () {
  3694. /**
  3695. * Creates a Vector4 object from the passed floats.
  3696. */
  3697. function Vector4(x, y, z, w) {
  3698. this.x = x;
  3699. this.y = y;
  3700. this.z = z;
  3701. this.w = w;
  3702. }
  3703. /**
  3704. * Returns the string with the Vector4 coordinates.
  3705. */
  3706. Vector4.prototype.toString = function () {
  3707. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  3708. };
  3709. /**
  3710. * Returns the string "Vector4".
  3711. */
  3712. Vector4.prototype.getClassName = function () {
  3713. return "Vector4";
  3714. };
  3715. /**
  3716. * Returns the Vector4 hash code.
  3717. */
  3718. Vector4.prototype.getHashCode = function () {
  3719. var hash = this.x || 0;
  3720. hash = (hash * 397) ^ (this.y || 0);
  3721. hash = (hash * 397) ^ (this.z || 0);
  3722. hash = (hash * 397) ^ (this.w || 0);
  3723. return hash;
  3724. };
  3725. // Operators
  3726. /**
  3727. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  3728. */
  3729. Vector4.prototype.asArray = function () {
  3730. var result = new Array();
  3731. this.toArray(result, 0);
  3732. return result;
  3733. };
  3734. /**
  3735. * Populates the passed array from the passed index with the Vector4 coordinates.
  3736. * Returns the Vector4.
  3737. */
  3738. Vector4.prototype.toArray = function (array, index) {
  3739. if (index === undefined) {
  3740. index = 0;
  3741. }
  3742. array[index] = this.x;
  3743. array[index + 1] = this.y;
  3744. array[index + 2] = this.z;
  3745. array[index + 3] = this.w;
  3746. return this;
  3747. };
  3748. /**
  3749. * Adds the passed vector to the current Vector4.
  3750. * Returns the updated Vector4.
  3751. */
  3752. Vector4.prototype.addInPlace = function (otherVector) {
  3753. this.x += otherVector.x;
  3754. this.y += otherVector.y;
  3755. this.z += otherVector.z;
  3756. this.w += otherVector.w;
  3757. return this;
  3758. };
  3759. /**
  3760. * Returns a new Vector4 as the result of the addition of the current Vector4 and the passed one.
  3761. */
  3762. Vector4.prototype.add = function (otherVector) {
  3763. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  3764. };
  3765. /**
  3766. * Updates the passed vector "result" with the result of the addition of the current Vector4 and the passed one.
  3767. * Returns the current Vector4.
  3768. */
  3769. Vector4.prototype.addToRef = function (otherVector, result) {
  3770. result.x = this.x + otherVector.x;
  3771. result.y = this.y + otherVector.y;
  3772. result.z = this.z + otherVector.z;
  3773. result.w = this.w + otherVector.w;
  3774. return this;
  3775. };
  3776. /**
  3777. * Subtract in place the passed vector from the current Vector4.
  3778. * Returns the updated Vector4.
  3779. */
  3780. Vector4.prototype.subtractInPlace = function (otherVector) {
  3781. this.x -= otherVector.x;
  3782. this.y -= otherVector.y;
  3783. this.z -= otherVector.z;
  3784. this.w -= otherVector.w;
  3785. return this;
  3786. };
  3787. /**
  3788. * Returns a new Vector4 with the result of the subtraction of the passed vector from the current Vector4.
  3789. */
  3790. Vector4.prototype.subtract = function (otherVector) {
  3791. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  3792. };
  3793. /**
  3794. * Sets the passed vector "result" with the result of the subtraction of the passed vector from the current Vector4.
  3795. * Returns the current Vector4.
  3796. */
  3797. Vector4.prototype.subtractToRef = function (otherVector, result) {
  3798. result.x = this.x - otherVector.x;
  3799. result.y = this.y - otherVector.y;
  3800. result.z = this.z - otherVector.z;
  3801. result.w = this.w - otherVector.w;
  3802. return this;
  3803. };
  3804. /**
  3805. * Returns a new Vector4 set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  3806. */
  3807. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  3808. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  3809. };
  3810. /**
  3811. * Sets the passed vector "result" set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  3812. * Returns the current Vector4.
  3813. */
  3814. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  3815. result.x = this.x - x;
  3816. result.y = this.y - y;
  3817. result.z = this.z - z;
  3818. result.w = this.w - w;
  3819. return this;
  3820. };
  3821. /**
  3822. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  3823. */
  3824. Vector4.prototype.negate = function () {
  3825. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  3826. };
  3827. /**
  3828. * Multiplies the current Vector4 coordinates by scale (float).
  3829. * Returns the updated Vector4.
  3830. */
  3831. Vector4.prototype.scaleInPlace = function (scale) {
  3832. this.x *= scale;
  3833. this.y *= scale;
  3834. this.z *= scale;
  3835. this.w *= scale;
  3836. return this;
  3837. };
  3838. /**
  3839. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  3840. */
  3841. Vector4.prototype.scale = function (scale) {
  3842. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  3843. };
  3844. /**
  3845. * Sets the passed vector "result" with the current Vector4 coordinates multiplied by scale (float).
  3846. * Returns the current Vector4.
  3847. */
  3848. Vector4.prototype.scaleToRef = function (scale, result) {
  3849. result.x = this.x * scale;
  3850. result.y = this.y * scale;
  3851. result.z = this.z * scale;
  3852. result.w = this.w * scale;
  3853. return this;
  3854. };
  3855. /**
  3856. * Boolean : True if the current Vector4 coordinates are stricly equal to the passed ones.
  3857. */
  3858. Vector4.prototype.equals = function (otherVector) {
  3859. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  3860. };
  3861. /**
  3862. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the passed vector ones.
  3863. */
  3864. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  3865. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  3866. return otherVector
  3867. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  3868. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  3869. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  3870. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  3871. };
  3872. /**
  3873. * Boolean : True if the passed floats are strictly equal to the current Vector4 coordinates.
  3874. */
  3875. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  3876. return this.x === x && this.y === y && this.z === z && this.w === w;
  3877. };
  3878. /**
  3879. * Multiplies in place the current Vector4 by the passed one.
  3880. * Returns the updated Vector4.
  3881. */
  3882. Vector4.prototype.multiplyInPlace = function (otherVector) {
  3883. this.x *= otherVector.x;
  3884. this.y *= otherVector.y;
  3885. this.z *= otherVector.z;
  3886. this.w *= otherVector.w;
  3887. return this;
  3888. };
  3889. /**
  3890. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the passed one.
  3891. */
  3892. Vector4.prototype.multiply = function (otherVector) {
  3893. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  3894. };
  3895. /**
  3896. * Updates the passed vector "result" with the multiplication result of the current Vector4 and the passed one.
  3897. * Returns the current Vector4.
  3898. */
  3899. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  3900. result.x = this.x * otherVector.x;
  3901. result.y = this.y * otherVector.y;
  3902. result.z = this.z * otherVector.z;
  3903. result.w = this.w * otherVector.w;
  3904. return this;
  3905. };
  3906. /**
  3907. * Returns a new Vector4 set with the multiplication result of the passed floats and the current Vector4 coordinates.
  3908. */
  3909. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  3910. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  3911. };
  3912. /**
  3913. * Returns a new Vector4 set with the division result of the current Vector4 by the passed one.
  3914. */
  3915. Vector4.prototype.divide = function (otherVector) {
  3916. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  3917. };
  3918. /**
  3919. * Updates the passed vector "result" with the division result of the current Vector4 by the passed one.
  3920. * Returns the current Vector4.
  3921. */
  3922. Vector4.prototype.divideToRef = function (otherVector, result) {
  3923. result.x = this.x / otherVector.x;
  3924. result.y = this.y / otherVector.y;
  3925. result.z = this.z / otherVector.z;
  3926. result.w = this.w / otherVector.w;
  3927. return this;
  3928. };
  3929. /**
  3930. * Divides the current Vector3 coordinates by the passed ones.
  3931. * @returns the updated Vector3.
  3932. */
  3933. Vector4.prototype.divideInPlace = function (otherVector) {
  3934. return this.divideToRef(otherVector, this);
  3935. };
  3936. /**
  3937. * Updates the Vector4 coordinates with the minimum values between its own and the passed vector ones
  3938. * @param other defines the second operand
  3939. * @returns the current updated Vector4
  3940. */
  3941. Vector4.prototype.minimizeInPlace = function (other) {
  3942. if (other.x < this.x)
  3943. this.x = other.x;
  3944. if (other.y < this.y)
  3945. this.y = other.y;
  3946. if (other.z < this.z)
  3947. this.z = other.z;
  3948. if (other.w < this.w)
  3949. this.w = other.w;
  3950. return this;
  3951. };
  3952. /**
  3953. * Updates the Vector4 coordinates with the maximum values between its own and the passed vector ones
  3954. * @param other defines the second operand
  3955. * @returns the current updated Vector4
  3956. */
  3957. Vector4.prototype.maximizeInPlace = function (other) {
  3958. if (other.x > this.x)
  3959. this.x = other.x;
  3960. if (other.y > this.y)
  3961. this.y = other.y;
  3962. if (other.z > this.z)
  3963. this.z = other.z;
  3964. if (other.w > this.w)
  3965. this.w = other.w;
  3966. return this;
  3967. };
  3968. // Properties
  3969. /**
  3970. * Returns the Vector4 length (float).
  3971. */
  3972. Vector4.prototype.length = function () {
  3973. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  3974. };
  3975. /**
  3976. * Returns the Vector4 squared length (float).
  3977. */
  3978. Vector4.prototype.lengthSquared = function () {
  3979. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  3980. };
  3981. // Methods
  3982. /**
  3983. * Normalizes in place the Vector4.
  3984. * Returns the updated Vector4.
  3985. */
  3986. Vector4.prototype.normalize = function () {
  3987. var len = this.length();
  3988. if (len === 0)
  3989. return this;
  3990. var num = 1.0 / len;
  3991. this.x *= num;
  3992. this.y *= num;
  3993. this.z *= num;
  3994. this.w *= num;
  3995. return this;
  3996. };
  3997. /**
  3998. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  3999. */
  4000. Vector4.prototype.toVector3 = function () {
  4001. return new Vector3(this.x, this.y, this.z);
  4002. };
  4003. /**
  4004. * Returns a new Vector4 copied from the current one.
  4005. */
  4006. Vector4.prototype.clone = function () {
  4007. return new Vector4(this.x, this.y, this.z, this.w);
  4008. };
  4009. /**
  4010. * Updates the current Vector4 with the passed one coordinates.
  4011. * Returns the updated Vector4.
  4012. */
  4013. Vector4.prototype.copyFrom = function (source) {
  4014. this.x = source.x;
  4015. this.y = source.y;
  4016. this.z = source.z;
  4017. this.w = source.w;
  4018. return this;
  4019. };
  4020. /**
  4021. * Updates the current Vector4 coordinates with the passed floats.
  4022. * Returns the updated Vector4.
  4023. */
  4024. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  4025. this.x = x;
  4026. this.y = y;
  4027. this.z = z;
  4028. this.w = w;
  4029. return this;
  4030. };
  4031. /**
  4032. * Updates the current Vector4 coordinates with the passed floats.
  4033. * Returns the updated Vector4.
  4034. */
  4035. Vector4.prototype.set = function (x, y, z, w) {
  4036. return this.copyFromFloats(x, y, z, w);
  4037. };
  4038. // Statics
  4039. /**
  4040. * Returns a new Vector4 set from the starting index of the passed array.
  4041. */
  4042. Vector4.FromArray = function (array, offset) {
  4043. if (!offset) {
  4044. offset = 0;
  4045. }
  4046. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4047. };
  4048. /**
  4049. * Updates the passed vector "result" from the starting index of the passed array.
  4050. */
  4051. Vector4.FromArrayToRef = function (array, offset, result) {
  4052. result.x = array[offset];
  4053. result.y = array[offset + 1];
  4054. result.z = array[offset + 2];
  4055. result.w = array[offset + 3];
  4056. };
  4057. /**
  4058. * Updates the passed vector "result" from the starting index of the passed Float32Array.
  4059. */
  4060. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  4061. Vector4.FromArrayToRef(array, offset, result);
  4062. };
  4063. /**
  4064. * Updates the passed vector "result" coordinates from the passed floats.
  4065. */
  4066. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  4067. result.x = x;
  4068. result.y = y;
  4069. result.z = z;
  4070. result.w = w;
  4071. };
  4072. /**
  4073. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  4074. */
  4075. Vector4.Zero = function () {
  4076. return new Vector4(0.0, 0.0, 0.0, 0.0);
  4077. };
  4078. /**
  4079. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  4080. */
  4081. Vector4.One = function () {
  4082. return new Vector4(1.0, 1.0, 1.0, 1.0);
  4083. };
  4084. /**
  4085. * Returns a new normalized Vector4 from the passed one.
  4086. */
  4087. Vector4.Normalize = function (vector) {
  4088. var result = Vector4.Zero();
  4089. Vector4.NormalizeToRef(vector, result);
  4090. return result;
  4091. };
  4092. /**
  4093. * Updates the passed vector "result" from the normalization of the passed one.
  4094. */
  4095. Vector4.NormalizeToRef = function (vector, result) {
  4096. result.copyFrom(vector);
  4097. result.normalize();
  4098. };
  4099. Vector4.Minimize = function (left, right) {
  4100. var min = left.clone();
  4101. min.minimizeInPlace(right);
  4102. return min;
  4103. };
  4104. Vector4.Maximize = function (left, right) {
  4105. var max = left.clone();
  4106. max.maximizeInPlace(right);
  4107. return max;
  4108. };
  4109. /**
  4110. * Returns the distance (float) between the vectors "value1" and "value2".
  4111. */
  4112. Vector4.Distance = function (value1, value2) {
  4113. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  4114. };
  4115. /**
  4116. * Returns the squared distance (float) between the vectors "value1" and "value2".
  4117. */
  4118. Vector4.DistanceSquared = function (value1, value2) {
  4119. var x = value1.x - value2.x;
  4120. var y = value1.y - value2.y;
  4121. var z = value1.z - value2.z;
  4122. var w = value1.w - value2.w;
  4123. return (x * x) + (y * y) + (z * z) + (w * w);
  4124. };
  4125. /**
  4126. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  4127. */
  4128. Vector4.Center = function (value1, value2) {
  4129. var center = value1.add(value2);
  4130. center.scaleInPlace(0.5);
  4131. return center;
  4132. };
  4133. /**
  4134. * Returns a new Vector4 set with the result of the normal transformation by the passed matrix of the passed vector.
  4135. * This methods computes transformed normalized direction vectors only.
  4136. */
  4137. Vector4.TransformNormal = function (vector, transformation) {
  4138. var result = Vector4.Zero();
  4139. Vector4.TransformNormalToRef(vector, transformation, result);
  4140. return result;
  4141. };
  4142. /**
  4143. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  4144. * This methods computes transformed normalized direction vectors only.
  4145. */
  4146. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  4147. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  4148. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  4149. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  4150. result.x = x;
  4151. result.y = y;
  4152. result.z = z;
  4153. result.w = vector.w;
  4154. };
  4155. /**
  4156. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z, w).
  4157. * This methods computes transformed normalized direction vectors only.
  4158. */
  4159. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  4160. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  4161. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  4162. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  4163. result.w = w;
  4164. };
  4165. return Vector4;
  4166. }());
  4167. BABYLON.Vector4 = Vector4;
  4168. var Size = /** @class */ (function () {
  4169. /**
  4170. * Creates a Size object from the passed width and height (floats).
  4171. */
  4172. function Size(width, height) {
  4173. this.width = width;
  4174. this.height = height;
  4175. }
  4176. // Returns a string with the Size width and height.
  4177. Size.prototype.toString = function () {
  4178. return "{W: " + this.width + ", H: " + this.height + "}";
  4179. };
  4180. /**
  4181. * Returns the string "Size"
  4182. */
  4183. Size.prototype.getClassName = function () {
  4184. return "Size";
  4185. };
  4186. /**
  4187. * Returns the Size hash code.
  4188. */
  4189. Size.prototype.getHashCode = function () {
  4190. var hash = this.width || 0;
  4191. hash = (hash * 397) ^ (this.height || 0);
  4192. return hash;
  4193. };
  4194. /**
  4195. * Updates the current size from the passed one.
  4196. * Returns the updated Size.
  4197. */
  4198. Size.prototype.copyFrom = function (src) {
  4199. this.width = src.width;
  4200. this.height = src.height;
  4201. };
  4202. /**
  4203. * Updates in place the current Size from the passed floats.
  4204. * Returns the updated Size.
  4205. */
  4206. Size.prototype.copyFromFloats = function (width, height) {
  4207. this.width = width;
  4208. this.height = height;
  4209. return this;
  4210. };
  4211. /**
  4212. * Updates in place the current Size from the passed floats.
  4213. * Returns the updated Size.
  4214. */
  4215. Size.prototype.set = function (width, height) {
  4216. return this.copyFromFloats(width, height);
  4217. };
  4218. /**
  4219. * Returns a new Size set with the multiplication result of the current Size and the passed floats.
  4220. */
  4221. Size.prototype.multiplyByFloats = function (w, h) {
  4222. return new Size(this.width * w, this.height * h);
  4223. };
  4224. /**
  4225. * Returns a new Size copied from the passed one.
  4226. */
  4227. Size.prototype.clone = function () {
  4228. return new Size(this.width, this.height);
  4229. };
  4230. /**
  4231. * Boolean : True if the current Size and the passed one width and height are strictly equal.
  4232. */
  4233. Size.prototype.equals = function (other) {
  4234. if (!other) {
  4235. return false;
  4236. }
  4237. return (this.width === other.width) && (this.height === other.height);
  4238. };
  4239. Object.defineProperty(Size.prototype, "surface", {
  4240. /**
  4241. * Returns the surface of the Size : width * height (float).
  4242. */
  4243. get: function () {
  4244. return this.width * this.height;
  4245. },
  4246. enumerable: true,
  4247. configurable: true
  4248. });
  4249. /**
  4250. * Returns a new Size set to (0.0, 0.0)
  4251. */
  4252. Size.Zero = function () {
  4253. return new Size(0.0, 0.0);
  4254. };
  4255. /**
  4256. * Returns a new Size set as the addition result of the current Size and the passed one.
  4257. */
  4258. Size.prototype.add = function (otherSize) {
  4259. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  4260. return r;
  4261. };
  4262. /**
  4263. * Returns a new Size set as the subtraction result of the passed one from the current Size.
  4264. */
  4265. Size.prototype.subtract = function (otherSize) {
  4266. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  4267. return r;
  4268. };
  4269. /**
  4270. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  4271. */
  4272. Size.Lerp = function (start, end, amount) {
  4273. var w = start.width + ((end.width - start.width) * amount);
  4274. var h = start.height + ((end.height - start.height) * amount);
  4275. return new Size(w, h);
  4276. };
  4277. return Size;
  4278. }());
  4279. BABYLON.Size = Size;
  4280. var Quaternion = /** @class */ (function () {
  4281. /**
  4282. * Creates a new Quaternion from the passed floats.
  4283. */
  4284. function Quaternion(x, y, z, w) {
  4285. if (x === void 0) { x = 0.0; }
  4286. if (y === void 0) { y = 0.0; }
  4287. if (z === void 0) { z = 0.0; }
  4288. if (w === void 0) { w = 1.0; }
  4289. this.x = x;
  4290. this.y = y;
  4291. this.z = z;
  4292. this.w = w;
  4293. }
  4294. /**
  4295. * Returns a string with the Quaternion coordinates.
  4296. */
  4297. Quaternion.prototype.toString = function () {
  4298. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  4299. };
  4300. /**
  4301. * Returns the string "Quaternion".
  4302. */
  4303. Quaternion.prototype.getClassName = function () {
  4304. return "Quaternion";
  4305. };
  4306. /**
  4307. * Returns the Quaternion hash code.
  4308. */
  4309. Quaternion.prototype.getHashCode = function () {
  4310. var hash = this.x || 0;
  4311. hash = (hash * 397) ^ (this.y || 0);
  4312. hash = (hash * 397) ^ (this.z || 0);
  4313. hash = (hash * 397) ^ (this.w || 0);
  4314. return hash;
  4315. };
  4316. /**
  4317. * Returns a new array populated with 4 elements : the Quaternion coordinates.
  4318. */
  4319. Quaternion.prototype.asArray = function () {
  4320. return [this.x, this.y, this.z, this.w];
  4321. };
  4322. /**
  4323. * Boolean : True if the current Quaterion and the passed one coordinates are strictly equal.
  4324. */
  4325. Quaternion.prototype.equals = function (otherQuaternion) {
  4326. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  4327. };
  4328. /**
  4329. * Returns a new Quaternion copied from the current one.
  4330. */
  4331. Quaternion.prototype.clone = function () {
  4332. return new Quaternion(this.x, this.y, this.z, this.w);
  4333. };
  4334. /**
  4335. * Updates the current Quaternion from the passed one coordinates.
  4336. * Returns the updated Quaterion.
  4337. */
  4338. Quaternion.prototype.copyFrom = function (other) {
  4339. this.x = other.x;
  4340. this.y = other.y;
  4341. this.z = other.z;
  4342. this.w = other.w;
  4343. return this;
  4344. };
  4345. /**
  4346. * Updates the current Quaternion from the passed float coordinates.
  4347. * Returns the updated Quaterion.
  4348. */
  4349. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  4350. this.x = x;
  4351. this.y = y;
  4352. this.z = z;
  4353. this.w = w;
  4354. return this;
  4355. };
  4356. /**
  4357. * Updates the current Quaternion from the passed float coordinates.
  4358. * Returns the updated Quaterion.
  4359. */
  4360. Quaternion.prototype.set = function (x, y, z, w) {
  4361. return this.copyFromFloats(x, y, z, w);
  4362. };
  4363. /**
  4364. * Returns a new Quaternion as the addition result of the passed one and the current Quaternion.
  4365. */
  4366. Quaternion.prototype.add = function (other) {
  4367. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  4368. };
  4369. /**
  4370. * Returns a new Quaternion as the subtraction result of the passed one from the current Quaternion.
  4371. */
  4372. Quaternion.prototype.subtract = function (other) {
  4373. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  4374. };
  4375. /**
  4376. * Returns a new Quaternion set by multiplying the current Quaterion coordinates by the float "scale".
  4377. */
  4378. Quaternion.prototype.scale = function (value) {
  4379. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  4380. };
  4381. /**
  4382. * Returns a new Quaternion set as the quaternion mulplication result of the current one with the passed one "q1".
  4383. */
  4384. Quaternion.prototype.multiply = function (q1) {
  4385. var result = new Quaternion(0, 0, 0, 1.0);
  4386. this.multiplyToRef(q1, result);
  4387. return result;
  4388. };
  4389. /**
  4390. * Sets the passed "result" as the quaternion mulplication result of the current one with the passed one "q1".
  4391. * Returns the current Quaternion.
  4392. */
  4393. Quaternion.prototype.multiplyToRef = function (q1, result) {
  4394. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  4395. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  4396. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  4397. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  4398. result.copyFromFloats(x, y, z, w);
  4399. return this;
  4400. };
  4401. /**
  4402. * Updates the current Quaternion with the quaternion mulplication result of itself with the passed one "q1".
  4403. * Returns the updated Quaternion.
  4404. */
  4405. Quaternion.prototype.multiplyInPlace = function (q1) {
  4406. this.multiplyToRef(q1, this);
  4407. return this;
  4408. };
  4409. /**
  4410. * Sets the passed "ref" with the conjugation of the current Quaternion.
  4411. * Returns the current Quaternion.
  4412. */
  4413. Quaternion.prototype.conjugateToRef = function (ref) {
  4414. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  4415. return this;
  4416. };
  4417. /**
  4418. * Conjugates in place the current Quaternion.
  4419. * Returns the updated Quaternion.
  4420. */
  4421. Quaternion.prototype.conjugateInPlace = function () {
  4422. this.x *= -1;
  4423. this.y *= -1;
  4424. this.z *= -1;
  4425. return this;
  4426. };
  4427. /**
  4428. * Returns a new Quaternion as the conjugate of the current Quaternion.
  4429. */
  4430. Quaternion.prototype.conjugate = function () {
  4431. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  4432. return result;
  4433. };
  4434. /**
  4435. * Returns the Quaternion length (float).
  4436. */
  4437. Quaternion.prototype.length = function () {
  4438. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  4439. };
  4440. /**
  4441. * Normalize in place the current Quaternion.
  4442. * Returns the updated Quaternion.
  4443. */
  4444. Quaternion.prototype.normalize = function () {
  4445. var length = 1.0 / this.length();
  4446. this.x *= length;
  4447. this.y *= length;
  4448. this.z *= length;
  4449. this.w *= length;
  4450. return this;
  4451. };
  4452. /**
  4453. * Returns a new Vector3 set with the Euler angles translated from the current Quaternion
  4454. * @param order is a reserved parameter and is ignore for now
  4455. * @returns the new Vector3
  4456. */
  4457. Quaternion.prototype.toEulerAngles = function (order) {
  4458. if (order === void 0) { order = "YZX"; }
  4459. var result = Vector3.Zero();
  4460. this.toEulerAnglesToRef(result, order);
  4461. return result;
  4462. };
  4463. /**
  4464. * Sets the passed vector3 "result" with the Euler angles translated from the current Quaternion
  4465. * @param result defines the vector which will be filled with the Euler angles
  4466. * @param order is a reserved parameter and is ignore for now
  4467. * @returns the current Quaternion
  4468. */
  4469. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  4470. if (order === void 0) { order = "YZX"; }
  4471. var qz = this.z;
  4472. var qx = this.x;
  4473. var qy = this.y;
  4474. var qw = this.w;
  4475. var sqw = qw * qw;
  4476. var sqz = qz * qz;
  4477. var sqx = qx * qx;
  4478. var sqy = qy * qy;
  4479. var zAxisY = qy * qz - qx * qw;
  4480. var limit = .4999999;
  4481. if (zAxisY < -limit) {
  4482. result.y = 2 * Math.atan2(qy, qw);
  4483. result.x = Math.PI / 2;
  4484. result.z = 0;
  4485. }
  4486. else if (zAxisY > limit) {
  4487. result.y = 2 * Math.atan2(qy, qw);
  4488. result.x = -Math.PI / 2;
  4489. result.z = 0;
  4490. }
  4491. else {
  4492. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  4493. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  4494. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  4495. }
  4496. return this;
  4497. };
  4498. /**
  4499. * Updates the passed rotation matrix with the current Quaternion values.
  4500. * Returns the current Quaternion.
  4501. */
  4502. Quaternion.prototype.toRotationMatrix = function (result) {
  4503. var xx = this.x * this.x;
  4504. var yy = this.y * this.y;
  4505. var zz = this.z * this.z;
  4506. var xy = this.x * this.y;
  4507. var zw = this.z * this.w;
  4508. var zx = this.z * this.x;
  4509. var yw = this.y * this.w;
  4510. var yz = this.y * this.z;
  4511. var xw = this.x * this.w;
  4512. result.m[0] = 1.0 - (2.0 * (yy + zz));
  4513. result.m[1] = 2.0 * (xy + zw);
  4514. result.m[2] = 2.0 * (zx - yw);
  4515. result.m[3] = 0;
  4516. result.m[4] = 2.0 * (xy - zw);
  4517. result.m[5] = 1.0 - (2.0 * (zz + xx));
  4518. result.m[6] = 2.0 * (yz + xw);
  4519. result.m[7] = 0;
  4520. result.m[8] = 2.0 * (zx + yw);
  4521. result.m[9] = 2.0 * (yz - xw);
  4522. result.m[10] = 1.0 - (2.0 * (yy + xx));
  4523. result.m[11] = 0;
  4524. result.m[12] = 0;
  4525. result.m[13] = 0;
  4526. result.m[14] = 0;
  4527. result.m[15] = 1.0;
  4528. result._markAsUpdated();
  4529. return this;
  4530. };
  4531. /**
  4532. * Updates the current Quaternion from the passed rotation matrix values.
  4533. * Returns the updated Quaternion.
  4534. */
  4535. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  4536. Quaternion.FromRotationMatrixToRef(matrix, this);
  4537. return this;
  4538. };
  4539. // Statics
  4540. /**
  4541. * Returns a new Quaternion set from the passed rotation matrix values.
  4542. */
  4543. Quaternion.FromRotationMatrix = function (matrix) {
  4544. var result = new Quaternion();
  4545. Quaternion.FromRotationMatrixToRef(matrix, result);
  4546. return result;
  4547. };
  4548. /**
  4549. * Updates the passed quaternion "result" with the passed rotation matrix values.
  4550. */
  4551. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  4552. var data = matrix.m;
  4553. var m11 = data[0], m12 = data[4], m13 = data[8];
  4554. var m21 = data[1], m22 = data[5], m23 = data[9];
  4555. var m31 = data[2], m32 = data[6], m33 = data[10];
  4556. var trace = m11 + m22 + m33;
  4557. var s;
  4558. if (trace > 0) {
  4559. s = 0.5 / Math.sqrt(trace + 1.0);
  4560. result.w = 0.25 / s;
  4561. result.x = (m32 - m23) * s;
  4562. result.y = (m13 - m31) * s;
  4563. result.z = (m21 - m12) * s;
  4564. }
  4565. else if (m11 > m22 && m11 > m33) {
  4566. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  4567. result.w = (m32 - m23) / s;
  4568. result.x = 0.25 * s;
  4569. result.y = (m12 + m21) / s;
  4570. result.z = (m13 + m31) / s;
  4571. }
  4572. else if (m22 > m33) {
  4573. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  4574. result.w = (m13 - m31) / s;
  4575. result.x = (m12 + m21) / s;
  4576. result.y = 0.25 * s;
  4577. result.z = (m23 + m32) / s;
  4578. }
  4579. else {
  4580. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  4581. result.w = (m21 - m12) / s;
  4582. result.x = (m13 + m31) / s;
  4583. result.y = (m23 + m32) / s;
  4584. result.z = 0.25 * s;
  4585. }
  4586. };
  4587. /**
  4588. * Returns a new Quaternion set to (0.0, 0.0, 0.0).
  4589. */
  4590. Quaternion.Zero = function () {
  4591. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  4592. };
  4593. /**
  4594. * Returns a new Quaternion as the inverted current Quaternion.
  4595. */
  4596. Quaternion.Inverse = function (q) {
  4597. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  4598. };
  4599. /**
  4600. * Returns the identity Quaternion.
  4601. */
  4602. Quaternion.Identity = function () {
  4603. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  4604. };
  4605. Quaternion.IsIdentity = function (quaternion) {
  4606. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  4607. };
  4608. /**
  4609. * Returns a new Quaternion set from the passed axis (Vector3) and angle in radians (float).
  4610. */
  4611. Quaternion.RotationAxis = function (axis, angle) {
  4612. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  4613. };
  4614. /**
  4615. * Sets the passed quaternion "result" from the passed axis (Vector3) and angle in radians (float).
  4616. */
  4617. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  4618. var sin = Math.sin(angle / 2);
  4619. axis.normalize();
  4620. result.w = Math.cos(angle / 2);
  4621. result.x = axis.x * sin;
  4622. result.y = axis.y * sin;
  4623. result.z = axis.z * sin;
  4624. return result;
  4625. };
  4626. /**
  4627. * Retuns a new Quaternion set from the starting index of the passed array.
  4628. */
  4629. Quaternion.FromArray = function (array, offset) {
  4630. if (!offset) {
  4631. offset = 0;
  4632. }
  4633. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4634. };
  4635. /**
  4636. * Returns a new Quaternion set from the passed Euler float angles (y, x, z).
  4637. */
  4638. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  4639. var q = new Quaternion();
  4640. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  4641. return q;
  4642. };
  4643. /**
  4644. * Sets the passed quaternion "result" from the passed float Euler angles (y, x, z).
  4645. */
  4646. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  4647. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  4648. var halfRoll = roll * 0.5;
  4649. var halfPitch = pitch * 0.5;
  4650. var halfYaw = yaw * 0.5;
  4651. var sinRoll = Math.sin(halfRoll);
  4652. var cosRoll = Math.cos(halfRoll);
  4653. var sinPitch = Math.sin(halfPitch);
  4654. var cosPitch = Math.cos(halfPitch);
  4655. var sinYaw = Math.sin(halfYaw);
  4656. var cosYaw = Math.cos(halfYaw);
  4657. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  4658. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  4659. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  4660. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  4661. };
  4662. /**
  4663. * Returns a new Quaternion from the passed float Euler angles expressed in z-x-z orientation
  4664. */
  4665. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  4666. var result = new Quaternion();
  4667. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  4668. return result;
  4669. };
  4670. /**
  4671. * Sets the passed quaternion "result" from the passed float Euler angles expressed in z-x-z orientation
  4672. */
  4673. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  4674. // Produces a quaternion from Euler angles in the z-x-z orientation
  4675. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  4676. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  4677. var halfBeta = beta * 0.5;
  4678. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4679. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4680. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4681. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4682. };
  4683. /**
  4684. * Returns a new Quaternion as the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  4685. * cf to Vector3.RotationFromAxis() documentation.
  4686. * Note : axis1, axis2 and axis3 are normalized during this operation.
  4687. */
  4688. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3, ref) {
  4689. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  4690. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  4691. return quat;
  4692. };
  4693. /**
  4694. * Sets the passed quaternion "ref" with the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  4695. * cf to Vector3.RotationFromAxis() documentation.
  4696. * Note : axis1, axis2 and axis3 are normalized during this operation.
  4697. */
  4698. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  4699. var rotMat = MathTmp.Matrix[0];
  4700. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  4701. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  4702. };
  4703. Quaternion.Slerp = function (left, right, amount) {
  4704. var result = Quaternion.Identity();
  4705. Quaternion.SlerpToRef(left, right, amount, result);
  4706. return result;
  4707. };
  4708. Quaternion.SlerpToRef = function (left, right, amount, result) {
  4709. var num2;
  4710. var num3;
  4711. var num = amount;
  4712. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  4713. var flag = false;
  4714. if (num4 < 0) {
  4715. flag = true;
  4716. num4 = -num4;
  4717. }
  4718. if (num4 > 0.999999) {
  4719. num3 = 1 - num;
  4720. num2 = flag ? -num : num;
  4721. }
  4722. else {
  4723. var num5 = Math.acos(num4);
  4724. var num6 = (1.0 / Math.sin(num5));
  4725. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  4726. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  4727. }
  4728. result.x = (num3 * left.x) + (num2 * right.x);
  4729. result.y = (num3 * left.y) + (num2 * right.y);
  4730. result.z = (num3 * left.z) + (num2 * right.z);
  4731. result.w = (num3 * left.w) + (num2 * right.w);
  4732. };
  4733. /**
  4734. * Returns a new Quaternion located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  4735. */
  4736. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  4737. var squared = amount * amount;
  4738. var cubed = amount * squared;
  4739. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  4740. var part2 = (-2.0 * cubed) + (3.0 * squared);
  4741. var part3 = (cubed - (2.0 * squared)) + amount;
  4742. var part4 = cubed - squared;
  4743. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  4744. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  4745. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  4746. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  4747. return new Quaternion(x, y, z, w);
  4748. };
  4749. return Quaternion;
  4750. }());
  4751. BABYLON.Quaternion = Quaternion;
  4752. var Matrix = /** @class */ (function () {
  4753. function Matrix() {
  4754. this._isIdentity = false;
  4755. this._isIdentityDirty = true;
  4756. this.m = new Float32Array(16);
  4757. this._markAsUpdated();
  4758. }
  4759. Matrix.prototype._markAsUpdated = function () {
  4760. this.updateFlag = Matrix._updateFlagSeed++;
  4761. this._isIdentityDirty = true;
  4762. };
  4763. // Properties
  4764. /**
  4765. * Boolean : True is the matrix is the identity matrix
  4766. */
  4767. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  4768. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  4769. if (this._isIdentityDirty) {
  4770. this._isIdentityDirty = false;
  4771. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  4772. this._isIdentity = false;
  4773. }
  4774. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  4775. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  4776. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  4777. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  4778. this._isIdentity = false;
  4779. }
  4780. else {
  4781. this._isIdentity = true;
  4782. }
  4783. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  4784. this._isIdentity = false;
  4785. }
  4786. }
  4787. return this._isIdentity;
  4788. };
  4789. /**
  4790. * Returns the matrix determinant (float).
  4791. */
  4792. Matrix.prototype.determinant = function () {
  4793. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  4794. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  4795. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  4796. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  4797. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  4798. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  4799. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  4800. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  4801. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  4802. };
  4803. // Methods
  4804. /**
  4805. * Returns the matrix underlying array.
  4806. */
  4807. Matrix.prototype.toArray = function () {
  4808. return this.m;
  4809. };
  4810. /**
  4811. * Returns the matrix underlying array.
  4812. */
  4813. Matrix.prototype.asArray = function () {
  4814. return this.toArray();
  4815. };
  4816. /**
  4817. * Inverts in place the Matrix.
  4818. * Returns the Matrix inverted.
  4819. */
  4820. Matrix.prototype.invert = function () {
  4821. this.invertToRef(this);
  4822. return this;
  4823. };
  4824. /**
  4825. * Sets all the matrix elements to zero.
  4826. * Returns the Matrix.
  4827. */
  4828. Matrix.prototype.reset = function () {
  4829. for (var index = 0; index < 16; index++) {
  4830. this.m[index] = 0.0;
  4831. }
  4832. this._markAsUpdated();
  4833. return this;
  4834. };
  4835. /**
  4836. * Returns a new Matrix as the addition result of the current Matrix and the passed one.
  4837. */
  4838. Matrix.prototype.add = function (other) {
  4839. var result = new Matrix();
  4840. this.addToRef(other, result);
  4841. return result;
  4842. };
  4843. /**
  4844. * Sets the passed matrix "result" with the ddition result of the current Matrix and the passed one.
  4845. * Returns the Matrix.
  4846. */
  4847. Matrix.prototype.addToRef = function (other, result) {
  4848. for (var index = 0; index < 16; index++) {
  4849. result.m[index] = this.m[index] + other.m[index];
  4850. }
  4851. result._markAsUpdated();
  4852. return this;
  4853. };
  4854. /**
  4855. * Adds in place the passed matrix to the current Matrix.
  4856. * Returns the updated Matrix.
  4857. */
  4858. Matrix.prototype.addToSelf = function (other) {
  4859. for (var index = 0; index < 16; index++) {
  4860. this.m[index] += other.m[index];
  4861. }
  4862. this._markAsUpdated();
  4863. return this;
  4864. };
  4865. /**
  4866. * Sets the passed matrix with the current inverted Matrix.
  4867. * Returns the unmodified current Matrix.
  4868. */
  4869. Matrix.prototype.invertToRef = function (other) {
  4870. var l1 = this.m[0];
  4871. var l2 = this.m[1];
  4872. var l3 = this.m[2];
  4873. var l4 = this.m[3];
  4874. var l5 = this.m[4];
  4875. var l6 = this.m[5];
  4876. var l7 = this.m[6];
  4877. var l8 = this.m[7];
  4878. var l9 = this.m[8];
  4879. var l10 = this.m[9];
  4880. var l11 = this.m[10];
  4881. var l12 = this.m[11];
  4882. var l13 = this.m[12];
  4883. var l14 = this.m[13];
  4884. var l15 = this.m[14];
  4885. var l16 = this.m[15];
  4886. var l17 = (l11 * l16) - (l12 * l15);
  4887. var l18 = (l10 * l16) - (l12 * l14);
  4888. var l19 = (l10 * l15) - (l11 * l14);
  4889. var l20 = (l9 * l16) - (l12 * l13);
  4890. var l21 = (l9 * l15) - (l11 * l13);
  4891. var l22 = (l9 * l14) - (l10 * l13);
  4892. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  4893. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  4894. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  4895. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  4896. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  4897. var l28 = (l7 * l16) - (l8 * l15);
  4898. var l29 = (l6 * l16) - (l8 * l14);
  4899. var l30 = (l6 * l15) - (l7 * l14);
  4900. var l31 = (l5 * l16) - (l8 * l13);
  4901. var l32 = (l5 * l15) - (l7 * l13);
  4902. var l33 = (l5 * l14) - (l6 * l13);
  4903. var l34 = (l7 * l12) - (l8 * l11);
  4904. var l35 = (l6 * l12) - (l8 * l10);
  4905. var l36 = (l6 * l11) - (l7 * l10);
  4906. var l37 = (l5 * l12) - (l8 * l9);
  4907. var l38 = (l5 * l11) - (l7 * l9);
  4908. var l39 = (l5 * l10) - (l6 * l9);
  4909. other.m[0] = l23 * l27;
  4910. other.m[4] = l24 * l27;
  4911. other.m[8] = l25 * l27;
  4912. other.m[12] = l26 * l27;
  4913. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  4914. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  4915. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  4916. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  4917. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  4918. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  4919. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  4920. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  4921. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  4922. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  4923. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  4924. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  4925. other._markAsUpdated();
  4926. return this;
  4927. };
  4928. /**
  4929. * Inserts the translation vector (using 3 x floats) in the current Matrix.
  4930. * Returns the updated Matrix.
  4931. */
  4932. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  4933. this.m[12] = x;
  4934. this.m[13] = y;
  4935. this.m[14] = z;
  4936. this._markAsUpdated();
  4937. return this;
  4938. };
  4939. /**
  4940. * Inserts the translation vector in the current Matrix.
  4941. * Returns the updated Matrix.
  4942. */
  4943. Matrix.prototype.setTranslation = function (vector3) {
  4944. this.m[12] = vector3.x;
  4945. this.m[13] = vector3.y;
  4946. this.m[14] = vector3.z;
  4947. this._markAsUpdated();
  4948. return this;
  4949. };
  4950. /**
  4951. * Returns a new Vector3 as the extracted translation from the Matrix.
  4952. */
  4953. Matrix.prototype.getTranslation = function () {
  4954. return new Vector3(this.m[12], this.m[13], this.m[14]);
  4955. };
  4956. /**
  4957. * Fill a Vector3 with the extracted translation from the Matrix.
  4958. */
  4959. Matrix.prototype.getTranslationToRef = function (result) {
  4960. result.x = this.m[12];
  4961. result.y = this.m[13];
  4962. result.z = this.m[14];
  4963. return this;
  4964. };
  4965. /**
  4966. * Remove rotation and scaling part from the Matrix.
  4967. * Returns the updated Matrix.
  4968. */
  4969. Matrix.prototype.removeRotationAndScaling = function () {
  4970. this.setRowFromFloats(0, 1, 0, 0, 0);
  4971. this.setRowFromFloats(1, 0, 1, 0, 0);
  4972. this.setRowFromFloats(2, 0, 0, 1, 0);
  4973. return this;
  4974. };
  4975. /**
  4976. * Returns a new Matrix set with the multiplication result of the current Matrix and the passed one.
  4977. */
  4978. Matrix.prototype.multiply = function (other) {
  4979. var result = new Matrix();
  4980. this.multiplyToRef(other, result);
  4981. return result;
  4982. };
  4983. /**
  4984. * Updates the current Matrix from the passed one values.
  4985. * Returns the updated Matrix.
  4986. */
  4987. Matrix.prototype.copyFrom = function (other) {
  4988. for (var index = 0; index < 16; index++) {
  4989. this.m[index] = other.m[index];
  4990. }
  4991. this._markAsUpdated();
  4992. return this;
  4993. };
  4994. /**
  4995. * Populates the passed array from the starting index with the Matrix values.
  4996. * Returns the Matrix.
  4997. */
  4998. Matrix.prototype.copyToArray = function (array, offset) {
  4999. if (offset === void 0) { offset = 0; }
  5000. for (var index = 0; index < 16; index++) {
  5001. array[offset + index] = this.m[index];
  5002. }
  5003. return this;
  5004. };
  5005. /**
  5006. * Sets the passed matrix "result" with the multiplication result of the current Matrix and the passed one.
  5007. */
  5008. Matrix.prototype.multiplyToRef = function (other, result) {
  5009. this.multiplyToArray(other, result.m, 0);
  5010. result._markAsUpdated();
  5011. return this;
  5012. };
  5013. /**
  5014. * Sets the Float32Array "result" from the passed index "offset" with the multiplication result of the current Matrix and the passed one.
  5015. */
  5016. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  5017. var tm0 = this.m[0];
  5018. var tm1 = this.m[1];
  5019. var tm2 = this.m[2];
  5020. var tm3 = this.m[3];
  5021. var tm4 = this.m[4];
  5022. var tm5 = this.m[5];
  5023. var tm6 = this.m[6];
  5024. var tm7 = this.m[7];
  5025. var tm8 = this.m[8];
  5026. var tm9 = this.m[9];
  5027. var tm10 = this.m[10];
  5028. var tm11 = this.m[11];
  5029. var tm12 = this.m[12];
  5030. var tm13 = this.m[13];
  5031. var tm14 = this.m[14];
  5032. var tm15 = this.m[15];
  5033. var om0 = other.m[0];
  5034. var om1 = other.m[1];
  5035. var om2 = other.m[2];
  5036. var om3 = other.m[3];
  5037. var om4 = other.m[4];
  5038. var om5 = other.m[5];
  5039. var om6 = other.m[6];
  5040. var om7 = other.m[7];
  5041. var om8 = other.m[8];
  5042. var om9 = other.m[9];
  5043. var om10 = other.m[10];
  5044. var om11 = other.m[11];
  5045. var om12 = other.m[12];
  5046. var om13 = other.m[13];
  5047. var om14 = other.m[14];
  5048. var om15 = other.m[15];
  5049. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  5050. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  5051. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  5052. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  5053. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  5054. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  5055. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  5056. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  5057. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  5058. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  5059. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  5060. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  5061. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  5062. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  5063. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  5064. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  5065. return this;
  5066. };
  5067. /**
  5068. * Boolean : True is the current Matrix and the passed one values are strictly equal.
  5069. */
  5070. Matrix.prototype.equals = function (value) {
  5071. return value &&
  5072. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  5073. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  5074. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  5075. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  5076. };
  5077. /**
  5078. * Returns a new Matrix from the current Matrix.
  5079. */
  5080. Matrix.prototype.clone = function () {
  5081. 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]);
  5082. };
  5083. /**
  5084. * Returns the string "Matrix"
  5085. */
  5086. Matrix.prototype.getClassName = function () {
  5087. return "Matrix";
  5088. };
  5089. /**
  5090. * Returns the Matrix hash code.
  5091. */
  5092. Matrix.prototype.getHashCode = function () {
  5093. var hash = this.m[0] || 0;
  5094. for (var i = 1; i < 16; i++) {
  5095. hash = (hash * 397) ^ (this.m[i] || 0);
  5096. }
  5097. return hash;
  5098. };
  5099. /**
  5100. * Decomposes the current Matrix into :
  5101. * - a scale vector3 passed as a reference to update,
  5102. * - a rotation quaternion passed as a reference to update,
  5103. * - a translation vector3 passed as a reference to update.
  5104. * Returns the true if operation was successful.
  5105. */
  5106. Matrix.prototype.decompose = function (scale, rotation, translation) {
  5107. translation.x = this.m[12];
  5108. translation.y = this.m[13];
  5109. translation.z = this.m[14];
  5110. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  5111. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  5112. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  5113. if (this.determinant() <= 0) {
  5114. scale.y *= -1;
  5115. }
  5116. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  5117. rotation.x = 0;
  5118. rotation.y = 0;
  5119. rotation.z = 0;
  5120. rotation.w = 1;
  5121. return false;
  5122. }
  5123. 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]);
  5124. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  5125. return true;
  5126. };
  5127. /**
  5128. * Writes to the given matrix a normal matrix, computed from this one (using values from identity matrix for fourth row and column).
  5129. * @param ref matrix to store the result
  5130. */
  5131. Matrix.prototype.toNormalMatrix = function (ref) {
  5132. this.invertToRef(ref);
  5133. ref.transpose();
  5134. var m = ref.m;
  5135. 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);
  5136. };
  5137. /**
  5138. * Returns a new Matrix as the extracted rotation matrix from the current one.
  5139. */
  5140. Matrix.prototype.getRotationMatrix = function () {
  5141. var result = Matrix.Identity();
  5142. this.getRotationMatrixToRef(result);
  5143. return result;
  5144. };
  5145. /**
  5146. * Extracts the rotation matrix from the current one and sets it as the passed "result".
  5147. * Returns the current Matrix.
  5148. */
  5149. Matrix.prototype.getRotationMatrixToRef = function (result) {
  5150. var m = this.m;
  5151. var xs = m[0] * m[1] * m[2] * m[3] < 0 ? -1 : 1;
  5152. var ys = m[4] * m[5] * m[6] * m[7] < 0 ? -1 : 1;
  5153. var zs = m[8] * m[9] * m[10] * m[11] < 0 ? -1 : 1;
  5154. var sx = xs * Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  5155. var sy = ys * Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  5156. var sz = zs * Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  5157. 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);
  5158. return this;
  5159. };
  5160. // Statics
  5161. /**
  5162. * Returns a new Matrix set from the starting index of the passed array.
  5163. */
  5164. Matrix.FromArray = function (array, offset) {
  5165. var result = new Matrix();
  5166. if (!offset) {
  5167. offset = 0;
  5168. }
  5169. Matrix.FromArrayToRef(array, offset, result);
  5170. return result;
  5171. };
  5172. /**
  5173. * Sets the passed "result" matrix from the starting index of the passed array.
  5174. */
  5175. Matrix.FromArrayToRef = function (array, offset, result) {
  5176. for (var index = 0; index < 16; index++) {
  5177. result.m[index] = array[index + offset];
  5178. }
  5179. result._markAsUpdated();
  5180. };
  5181. /**
  5182. * Sets the passed "result" matrix from the starting index of the passed Float32Array by multiplying each element by the float "scale".
  5183. */
  5184. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  5185. for (var index = 0; index < 16; index++) {
  5186. result.m[index] = array[index + offset] * scale;
  5187. }
  5188. result._markAsUpdated();
  5189. };
  5190. /**
  5191. * Sets the passed matrix "result" with the 16 passed floats.
  5192. */
  5193. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  5194. result.m[0] = initialM11;
  5195. result.m[1] = initialM12;
  5196. result.m[2] = initialM13;
  5197. result.m[3] = initialM14;
  5198. result.m[4] = initialM21;
  5199. result.m[5] = initialM22;
  5200. result.m[6] = initialM23;
  5201. result.m[7] = initialM24;
  5202. result.m[8] = initialM31;
  5203. result.m[9] = initialM32;
  5204. result.m[10] = initialM33;
  5205. result.m[11] = initialM34;
  5206. result.m[12] = initialM41;
  5207. result.m[13] = initialM42;
  5208. result.m[14] = initialM43;
  5209. result.m[15] = initialM44;
  5210. result._markAsUpdated();
  5211. };
  5212. /**
  5213. * Returns the index-th row of the current matrix as a new Vector4.
  5214. */
  5215. Matrix.prototype.getRow = function (index) {
  5216. if (index < 0 || index > 3) {
  5217. return null;
  5218. }
  5219. var i = index * 4;
  5220. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  5221. };
  5222. /**
  5223. * Sets the index-th row of the current matrix with the passed Vector4 values.
  5224. * Returns the updated Matrix.
  5225. */
  5226. Matrix.prototype.setRow = function (index, row) {
  5227. if (index < 0 || index > 3) {
  5228. return this;
  5229. }
  5230. var i = index * 4;
  5231. this.m[i + 0] = row.x;
  5232. this.m[i + 1] = row.y;
  5233. this.m[i + 2] = row.z;
  5234. this.m[i + 3] = row.w;
  5235. this._markAsUpdated();
  5236. return this;
  5237. };
  5238. /**
  5239. * Compute the transpose of the matrix.
  5240. * Returns a new Matrix.
  5241. */
  5242. Matrix.prototype.transpose = function () {
  5243. return Matrix.Transpose(this);
  5244. };
  5245. /**
  5246. * Compute the transpose of the matrix.
  5247. * Returns the current matrix.
  5248. */
  5249. Matrix.prototype.transposeToRef = function (result) {
  5250. Matrix.TransposeToRef(this, result);
  5251. return this;
  5252. };
  5253. /**
  5254. * Sets the index-th row of the current matrix with the passed 4 x float values.
  5255. * Returns the updated Matrix.
  5256. */
  5257. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  5258. if (index < 0 || index > 3) {
  5259. return this;
  5260. }
  5261. var i = index * 4;
  5262. this.m[i + 0] = x;
  5263. this.m[i + 1] = y;
  5264. this.m[i + 2] = z;
  5265. this.m[i + 3] = w;
  5266. this._markAsUpdated();
  5267. return this;
  5268. };
  5269. Object.defineProperty(Matrix, "IdentityReadOnly", {
  5270. /**
  5271. * Static identity matrix to be used as readonly matrix
  5272. * Must not be updated.
  5273. */
  5274. get: function () {
  5275. return Matrix._identityReadOnly;
  5276. },
  5277. enumerable: true,
  5278. configurable: true
  5279. });
  5280. /**
  5281. * Returns a new Matrix set from the 16 passed floats.
  5282. */
  5283. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  5284. var result = new Matrix();
  5285. result.m[0] = initialM11;
  5286. result.m[1] = initialM12;
  5287. result.m[2] = initialM13;
  5288. result.m[3] = initialM14;
  5289. result.m[4] = initialM21;
  5290. result.m[5] = initialM22;
  5291. result.m[6] = initialM23;
  5292. result.m[7] = initialM24;
  5293. result.m[8] = initialM31;
  5294. result.m[9] = initialM32;
  5295. result.m[10] = initialM33;
  5296. result.m[11] = initialM34;
  5297. result.m[12] = initialM41;
  5298. result.m[13] = initialM42;
  5299. result.m[14] = initialM43;
  5300. result.m[15] = initialM44;
  5301. return result;
  5302. };
  5303. /**
  5304. * Returns a new Matrix composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  5305. */
  5306. Matrix.Compose = function (scale, rotation, translation) {
  5307. var result = Matrix.Identity();
  5308. Matrix.ComposeToRef(scale, rotation, translation, result);
  5309. return result;
  5310. };
  5311. /**
  5312. * Update a Matrix with values composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  5313. */
  5314. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  5315. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  5316. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  5317. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  5318. result.setTranslation(translation);
  5319. };
  5320. /**
  5321. * Returns a new indentity Matrix.
  5322. */
  5323. Matrix.Identity = function () {
  5324. 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);
  5325. };
  5326. /**
  5327. * Sets the passed "result" as an identity matrix.
  5328. */
  5329. Matrix.IdentityToRef = function (result) {
  5330. 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);
  5331. };
  5332. /**
  5333. * Returns a new zero Matrix.
  5334. */
  5335. Matrix.Zero = function () {
  5336. 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);
  5337. };
  5338. /**
  5339. * Returns a new rotation matrix for "angle" radians around the X axis.
  5340. */
  5341. Matrix.RotationX = function (angle) {
  5342. var result = new Matrix();
  5343. Matrix.RotationXToRef(angle, result);
  5344. return result;
  5345. };
  5346. /**
  5347. * Returns a new Matrix as the passed inverted one.
  5348. */
  5349. Matrix.Invert = function (source) {
  5350. var result = new Matrix();
  5351. source.invertToRef(result);
  5352. return result;
  5353. };
  5354. /**
  5355. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the X axis.
  5356. */
  5357. Matrix.RotationXToRef = function (angle, result) {
  5358. var s = Math.sin(angle);
  5359. var c = Math.cos(angle);
  5360. result.m[0] = 1.0;
  5361. result.m[15] = 1.0;
  5362. result.m[5] = c;
  5363. result.m[10] = c;
  5364. result.m[9] = -s;
  5365. result.m[6] = s;
  5366. result.m[1] = 0.0;
  5367. result.m[2] = 0.0;
  5368. result.m[3] = 0.0;
  5369. result.m[4] = 0.0;
  5370. result.m[7] = 0.0;
  5371. result.m[8] = 0.0;
  5372. result.m[11] = 0.0;
  5373. result.m[12] = 0.0;
  5374. result.m[13] = 0.0;
  5375. result.m[14] = 0.0;
  5376. result._markAsUpdated();
  5377. };
  5378. /**
  5379. * Returns a new rotation matrix for "angle" radians around the Y axis.
  5380. */
  5381. Matrix.RotationY = function (angle) {
  5382. var result = new Matrix();
  5383. Matrix.RotationYToRef(angle, result);
  5384. return result;
  5385. };
  5386. /**
  5387. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Y axis.
  5388. */
  5389. Matrix.RotationYToRef = function (angle, result) {
  5390. var s = Math.sin(angle);
  5391. var c = Math.cos(angle);
  5392. result.m[5] = 1.0;
  5393. result.m[15] = 1.0;
  5394. result.m[0] = c;
  5395. result.m[2] = -s;
  5396. result.m[8] = s;
  5397. result.m[10] = c;
  5398. result.m[1] = 0.0;
  5399. result.m[3] = 0.0;
  5400. result.m[4] = 0.0;
  5401. result.m[6] = 0.0;
  5402. result.m[7] = 0.0;
  5403. result.m[9] = 0.0;
  5404. result.m[11] = 0.0;
  5405. result.m[12] = 0.0;
  5406. result.m[13] = 0.0;
  5407. result.m[14] = 0.0;
  5408. result._markAsUpdated();
  5409. };
  5410. /**
  5411. * Returns a new rotation matrix for "angle" radians around the Z axis.
  5412. */
  5413. Matrix.RotationZ = function (angle) {
  5414. var result = new Matrix();
  5415. Matrix.RotationZToRef(angle, result);
  5416. return result;
  5417. };
  5418. /**
  5419. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Z axis.
  5420. */
  5421. Matrix.RotationZToRef = function (angle, result) {
  5422. var s = Math.sin(angle);
  5423. var c = Math.cos(angle);
  5424. result.m[10] = 1.0;
  5425. result.m[15] = 1.0;
  5426. result.m[0] = c;
  5427. result.m[1] = s;
  5428. result.m[4] = -s;
  5429. result.m[5] = c;
  5430. result.m[2] = 0.0;
  5431. result.m[3] = 0.0;
  5432. result.m[6] = 0.0;
  5433. result.m[7] = 0.0;
  5434. result.m[8] = 0.0;
  5435. result.m[9] = 0.0;
  5436. result.m[11] = 0.0;
  5437. result.m[12] = 0.0;
  5438. result.m[13] = 0.0;
  5439. result.m[14] = 0.0;
  5440. result._markAsUpdated();
  5441. };
  5442. /**
  5443. * Returns a new rotation matrix for "angle" radians around the passed axis.
  5444. */
  5445. Matrix.RotationAxis = function (axis, angle) {
  5446. var result = Matrix.Zero();
  5447. Matrix.RotationAxisToRef(axis, angle, result);
  5448. return result;
  5449. };
  5450. /**
  5451. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the passed axis.
  5452. */
  5453. Matrix.RotationAxisToRef = function (axis, angle, result) {
  5454. var s = Math.sin(-angle);
  5455. var c = Math.cos(-angle);
  5456. var c1 = 1 - c;
  5457. axis.normalize();
  5458. result.m[0] = (axis.x * axis.x) * c1 + c;
  5459. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  5460. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  5461. result.m[3] = 0.0;
  5462. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  5463. result.m[5] = (axis.y * axis.y) * c1 + c;
  5464. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  5465. result.m[7] = 0.0;
  5466. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  5467. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  5468. result.m[10] = (axis.z * axis.z) * c1 + c;
  5469. result.m[11] = 0.0;
  5470. result.m[15] = 1.0;
  5471. result._markAsUpdated();
  5472. };
  5473. /**
  5474. * Returns a new Matrix as a rotation matrix from the Euler angles (y, x, z).
  5475. */
  5476. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  5477. var result = new Matrix();
  5478. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  5479. return result;
  5480. };
  5481. /**
  5482. * Sets the passed matrix "result" as a rotation matrix from the Euler angles (y, x, z).
  5483. */
  5484. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  5485. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  5486. this._tempQuaternion.toRotationMatrix(result);
  5487. };
  5488. /**
  5489. * Returns a new Matrix as a scaling matrix from the passed floats (x, y, z).
  5490. */
  5491. Matrix.Scaling = function (x, y, z) {
  5492. var result = Matrix.Zero();
  5493. Matrix.ScalingToRef(x, y, z, result);
  5494. return result;
  5495. };
  5496. /**
  5497. * Sets the passed matrix "result" as a scaling matrix from the passed floats (x, y, z).
  5498. */
  5499. Matrix.ScalingToRef = function (x, y, z, result) {
  5500. result.m[0] = x;
  5501. result.m[1] = 0.0;
  5502. result.m[2] = 0.0;
  5503. result.m[3] = 0.0;
  5504. result.m[4] = 0.0;
  5505. result.m[5] = y;
  5506. result.m[6] = 0.0;
  5507. result.m[7] = 0.0;
  5508. result.m[8] = 0.0;
  5509. result.m[9] = 0.0;
  5510. result.m[10] = z;
  5511. result.m[11] = 0.0;
  5512. result.m[12] = 0.0;
  5513. result.m[13] = 0.0;
  5514. result.m[14] = 0.0;
  5515. result.m[15] = 1.0;
  5516. result._markAsUpdated();
  5517. };
  5518. /**
  5519. * Returns a new Matrix as a translation matrix from the passed floats (x, y, z).
  5520. */
  5521. Matrix.Translation = function (x, y, z) {
  5522. var result = Matrix.Identity();
  5523. Matrix.TranslationToRef(x, y, z, result);
  5524. return result;
  5525. };
  5526. /**
  5527. * Sets the passed matrix "result" as a translation matrix from the passed floats (x, y, z).
  5528. */
  5529. Matrix.TranslationToRef = function (x, y, z, result) {
  5530. 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);
  5531. };
  5532. /**
  5533. * Returns a new Matrix whose values are the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  5534. * @param startValue defines the start value
  5535. * @param endValue defines the end value
  5536. * @param gradient defines the gradient factor
  5537. * @returns the new matrix
  5538. */
  5539. Matrix.Lerp = function (startValue, endValue, gradient) {
  5540. var result = Matrix.Zero();
  5541. Matrix.LerpToRef(startValue, endValue, gradient, result);
  5542. return result;
  5543. };
  5544. /**
  5545. * Set the passed matrix "result" as the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  5546. * @param startValue defines the start value
  5547. * @param endValue defines the end value
  5548. * @param gradient defines the gradient factor
  5549. * @param result defines the Matrix object where to store data
  5550. */
  5551. Matrix.LerpToRef = function (startValue, endValue, gradient, result) {
  5552. for (var index = 0; index < 16; index++) {
  5553. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  5554. }
  5555. result._markAsUpdated();
  5556. };
  5557. /**
  5558. * Returns a new Matrix whose values are computed by :
  5559. * - decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices,
  5560. * - interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end,
  5561. * - recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices.
  5562. */
  5563. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  5564. var startScale = new Vector3(0, 0, 0);
  5565. var startRotation = new Quaternion();
  5566. var startTranslation = new Vector3(0, 0, 0);
  5567. startValue.decompose(startScale, startRotation, startTranslation);
  5568. var endScale = new Vector3(0, 0, 0);
  5569. var endRotation = new Quaternion();
  5570. var endTranslation = new Vector3(0, 0, 0);
  5571. endValue.decompose(endScale, endRotation, endTranslation);
  5572. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  5573. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  5574. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  5575. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  5576. };
  5577. /**
  5578. * 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".
  5579. * This methods works for a Left-Handed system.
  5580. */
  5581. Matrix.LookAtLH = function (eye, target, up) {
  5582. var result = Matrix.Zero();
  5583. Matrix.LookAtLHToRef(eye, target, up, result);
  5584. return result;
  5585. };
  5586. /**
  5587. * 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".
  5588. * This methods works for a Left-Handed system.
  5589. */
  5590. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  5591. // Z axis
  5592. target.subtractToRef(eye, this._zAxis);
  5593. this._zAxis.normalize();
  5594. // X axis
  5595. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  5596. if (this._xAxis.lengthSquared() === 0) {
  5597. this._xAxis.x = 1.0;
  5598. }
  5599. else {
  5600. this._xAxis.normalize();
  5601. }
  5602. // Y axis
  5603. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  5604. this._yAxis.normalize();
  5605. // Eye angles
  5606. var ex = -Vector3.Dot(this._xAxis, eye);
  5607. var ey = -Vector3.Dot(this._yAxis, eye);
  5608. var ez = -Vector3.Dot(this._zAxis, eye);
  5609. 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);
  5610. };
  5611. /**
  5612. * 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".
  5613. * This methods works for a Right-Handed system.
  5614. */
  5615. Matrix.LookAtRH = function (eye, target, up) {
  5616. var result = Matrix.Zero();
  5617. Matrix.LookAtRHToRef(eye, target, up, result);
  5618. return result;
  5619. };
  5620. /**
  5621. * 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".
  5622. * This methods works for a Left-Handed system.
  5623. */
  5624. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  5625. // Z axis
  5626. eye.subtractToRef(target, this._zAxis);
  5627. this._zAxis.normalize();
  5628. // X axis
  5629. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  5630. if (this._xAxis.lengthSquared() === 0) {
  5631. this._xAxis.x = 1.0;
  5632. }
  5633. else {
  5634. this._xAxis.normalize();
  5635. }
  5636. // Y axis
  5637. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  5638. this._yAxis.normalize();
  5639. // Eye angles
  5640. var ex = -Vector3.Dot(this._xAxis, eye);
  5641. var ey = -Vector3.Dot(this._yAxis, eye);
  5642. var ez = -Vector3.Dot(this._zAxis, eye);
  5643. 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);
  5644. };
  5645. /**
  5646. * 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.
  5647. */
  5648. Matrix.OrthoLH = function (width, height, znear, zfar) {
  5649. var matrix = Matrix.Zero();
  5650. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  5651. return matrix;
  5652. };
  5653. /**
  5654. * 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.
  5655. */
  5656. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  5657. var n = znear;
  5658. var f = zfar;
  5659. var a = 2.0 / width;
  5660. var b = 2.0 / height;
  5661. var c = 2.0 / (f - n);
  5662. var d = -(f + n) / (f - n);
  5663. 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);
  5664. };
  5665. /**
  5666. * 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.
  5667. */
  5668. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  5669. var matrix = Matrix.Zero();
  5670. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  5671. return matrix;
  5672. };
  5673. /**
  5674. * 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.
  5675. */
  5676. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  5677. var n = znear;
  5678. var f = zfar;
  5679. var a = 2.0 / (right - left);
  5680. var b = 2.0 / (top - bottom);
  5681. var c = 2.0 / (f - n);
  5682. var d = -(f + n) / (f - n);
  5683. var i0 = (left + right) / (left - right);
  5684. var i1 = (top + bottom) / (bottom - top);
  5685. 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);
  5686. };
  5687. /**
  5688. * 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.
  5689. */
  5690. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  5691. var matrix = Matrix.Zero();
  5692. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  5693. return matrix;
  5694. };
  5695. /**
  5696. * 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.
  5697. */
  5698. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  5699. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  5700. result.m[10] *= -1.0;
  5701. };
  5702. /**
  5703. * 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.
  5704. */
  5705. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  5706. var matrix = Matrix.Zero();
  5707. var n = znear;
  5708. var f = zfar;
  5709. var a = 2.0 * n / width;
  5710. var b = 2.0 * n / height;
  5711. var c = (f + n) / (f - n);
  5712. var d = -2.0 * f * n / (f - n);
  5713. 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);
  5714. return matrix;
  5715. };
  5716. /**
  5717. * 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.
  5718. */
  5719. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  5720. var matrix = Matrix.Zero();
  5721. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  5722. return matrix;
  5723. };
  5724. /**
  5725. * 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.
  5726. */
  5727. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  5728. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  5729. var n = znear;
  5730. var f = zfar;
  5731. var t = 1.0 / (Math.tan(fov * 0.5));
  5732. var a = isVerticalFovFixed ? (t / aspect) : t;
  5733. var b = isVerticalFovFixed ? t : (t * aspect);
  5734. var c = (f + n) / (f - n);
  5735. var d = -2.0 * f * n / (f - n);
  5736. 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);
  5737. };
  5738. /**
  5739. * 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.
  5740. */
  5741. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  5742. var matrix = Matrix.Zero();
  5743. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  5744. return matrix;
  5745. };
  5746. /**
  5747. * 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.
  5748. */
  5749. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  5750. //alternatively this could be expressed as:
  5751. // m = PerspectiveFovLHToRef
  5752. // m[10] *= -1.0;
  5753. // m[11] *= -1.0;
  5754. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  5755. var n = znear;
  5756. var f = zfar;
  5757. var t = 1.0 / (Math.tan(fov * 0.5));
  5758. var a = isVerticalFovFixed ? (t / aspect) : t;
  5759. var b = isVerticalFovFixed ? t : (t * aspect);
  5760. var c = -(f + n) / (f - n);
  5761. var d = -2 * f * n / (f - n);
  5762. 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);
  5763. };
  5764. /**
  5765. * 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.
  5766. */
  5767. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  5768. if (rightHanded === void 0) { rightHanded = false; }
  5769. var rightHandedFactor = rightHanded ? -1 : 1;
  5770. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  5771. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  5772. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  5773. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  5774. var xScale = 2.0 / (leftTan + rightTan);
  5775. var yScale = 2.0 / (upTan + downTan);
  5776. result.m[0] = xScale;
  5777. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  5778. result.m[5] = yScale;
  5779. result.m[6] = result.m[7] = 0.0;
  5780. result.m[8] = ((leftTan - rightTan) * xScale * 0.5); // * rightHandedFactor;
  5781. result.m[9] = -((upTan - downTan) * yScale * 0.5); // * rightHandedFactor;
  5782. //result.m[10] = -(znear + zfar) / (zfar - znear) * rightHandedFactor;
  5783. result.m[10] = -zfar / (znear - zfar);
  5784. result.m[11] = 1.0 * rightHandedFactor;
  5785. result.m[12] = result.m[13] = result.m[15] = 0.0;
  5786. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  5787. // result.m[14] = (znear * zfar) / (znear - zfar);
  5788. result._markAsUpdated();
  5789. };
  5790. /**
  5791. * Returns the final transformation matrix : world * view * projection * viewport
  5792. */
  5793. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  5794. var cw = viewport.width;
  5795. var ch = viewport.height;
  5796. var cx = viewport.x;
  5797. var cy = viewport.y;
  5798. 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);
  5799. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  5800. };
  5801. /**
  5802. * Returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the passed Matrix.
  5803. */
  5804. Matrix.GetAsMatrix2x2 = function (matrix) {
  5805. return new Float32Array([
  5806. matrix.m[0], matrix.m[1],
  5807. matrix.m[4], matrix.m[5]
  5808. ]);
  5809. };
  5810. /**
  5811. * Returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the passed Matrix.
  5812. */
  5813. Matrix.GetAsMatrix3x3 = function (matrix) {
  5814. return new Float32Array([
  5815. matrix.m[0], matrix.m[1], matrix.m[2],
  5816. matrix.m[4], matrix.m[5], matrix.m[6],
  5817. matrix.m[8], matrix.m[9], matrix.m[10]
  5818. ]);
  5819. };
  5820. /**
  5821. * Compute the transpose of the passed Matrix.
  5822. * Returns a new Matrix.
  5823. */
  5824. Matrix.Transpose = function (matrix) {
  5825. var result = new Matrix();
  5826. Matrix.TransposeToRef(matrix, result);
  5827. return result;
  5828. };
  5829. /**
  5830. * Compute the transpose of the passed Matrix and store it in the result matrix.
  5831. */
  5832. Matrix.TransposeToRef = function (matrix, result) {
  5833. result.m[0] = matrix.m[0];
  5834. result.m[1] = matrix.m[4];
  5835. result.m[2] = matrix.m[8];
  5836. result.m[3] = matrix.m[12];
  5837. result.m[4] = matrix.m[1];
  5838. result.m[5] = matrix.m[5];
  5839. result.m[6] = matrix.m[9];
  5840. result.m[7] = matrix.m[13];
  5841. result.m[8] = matrix.m[2];
  5842. result.m[9] = matrix.m[6];
  5843. result.m[10] = matrix.m[10];
  5844. result.m[11] = matrix.m[14];
  5845. result.m[12] = matrix.m[3];
  5846. result.m[13] = matrix.m[7];
  5847. result.m[14] = matrix.m[11];
  5848. result.m[15] = matrix.m[15];
  5849. };
  5850. /**
  5851. * Returns a new Matrix as the reflection matrix across the passed plane.
  5852. */
  5853. Matrix.Reflection = function (plane) {
  5854. var matrix = new Matrix();
  5855. Matrix.ReflectionToRef(plane, matrix);
  5856. return matrix;
  5857. };
  5858. /**
  5859. * Sets the passed matrix "result" as the reflection matrix across the passed plane.
  5860. */
  5861. Matrix.ReflectionToRef = function (plane, result) {
  5862. plane.normalize();
  5863. var x = plane.normal.x;
  5864. var y = plane.normal.y;
  5865. var z = plane.normal.z;
  5866. var temp = -2 * x;
  5867. var temp2 = -2 * y;
  5868. var temp3 = -2 * z;
  5869. result.m[0] = (temp * x) + 1;
  5870. result.m[1] = temp2 * x;
  5871. result.m[2] = temp3 * x;
  5872. result.m[3] = 0.0;
  5873. result.m[4] = temp * y;
  5874. result.m[5] = (temp2 * y) + 1;
  5875. result.m[6] = temp3 * y;
  5876. result.m[7] = 0.0;
  5877. result.m[8] = temp * z;
  5878. result.m[9] = temp2 * z;
  5879. result.m[10] = (temp3 * z) + 1;
  5880. result.m[11] = 0.0;
  5881. result.m[12] = temp * plane.d;
  5882. result.m[13] = temp2 * plane.d;
  5883. result.m[14] = temp3 * plane.d;
  5884. result.m[15] = 1.0;
  5885. result._markAsUpdated();
  5886. };
  5887. /**
  5888. * Sets the passed matrix "mat" as a rotation matrix composed from the 3 passed left handed axis.
  5889. */
  5890. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  5891. result.m[0] = xaxis.x;
  5892. result.m[1] = xaxis.y;
  5893. result.m[2] = xaxis.z;
  5894. result.m[3] = 0.0;
  5895. result.m[4] = yaxis.x;
  5896. result.m[5] = yaxis.y;
  5897. result.m[6] = yaxis.z;
  5898. result.m[7] = 0.0;
  5899. result.m[8] = zaxis.x;
  5900. result.m[9] = zaxis.y;
  5901. result.m[10] = zaxis.z;
  5902. result.m[11] = 0.0;
  5903. result.m[12] = 0.0;
  5904. result.m[13] = 0.0;
  5905. result.m[14] = 0.0;
  5906. result.m[15] = 1.0;
  5907. result._markAsUpdated();
  5908. };
  5909. /**
  5910. * Sets the passed matrix "result" as a rotation matrix according to the passed quaternion.
  5911. */
  5912. Matrix.FromQuaternionToRef = function (quat, result) {
  5913. var xx = quat.x * quat.x;
  5914. var yy = quat.y * quat.y;
  5915. var zz = quat.z * quat.z;
  5916. var xy = quat.x * quat.y;
  5917. var zw = quat.z * quat.w;
  5918. var zx = quat.z * quat.x;
  5919. var yw = quat.y * quat.w;
  5920. var yz = quat.y * quat.z;
  5921. var xw = quat.x * quat.w;
  5922. result.m[0] = 1.0 - (2.0 * (yy + zz));
  5923. result.m[1] = 2.0 * (xy + zw);
  5924. result.m[2] = 2.0 * (zx - yw);
  5925. result.m[3] = 0.0;
  5926. result.m[4] = 2.0 * (xy - zw);
  5927. result.m[5] = 1.0 - (2.0 * (zz + xx));
  5928. result.m[6] = 2.0 * (yz + xw);
  5929. result.m[7] = 0.0;
  5930. result.m[8] = 2.0 * (zx + yw);
  5931. result.m[9] = 2.0 * (yz - xw);
  5932. result.m[10] = 1.0 - (2.0 * (yy + xx));
  5933. result.m[11] = 0.0;
  5934. result.m[12] = 0.0;
  5935. result.m[13] = 0.0;
  5936. result.m[14] = 0.0;
  5937. result.m[15] = 1.0;
  5938. result._markAsUpdated();
  5939. };
  5940. Matrix._tempQuaternion = new Quaternion();
  5941. Matrix._xAxis = Vector3.Zero();
  5942. Matrix._yAxis = Vector3.Zero();
  5943. Matrix._zAxis = Vector3.Zero();
  5944. Matrix._updateFlagSeed = 0;
  5945. Matrix._identityReadOnly = Matrix.Identity();
  5946. return Matrix;
  5947. }());
  5948. BABYLON.Matrix = Matrix;
  5949. var Plane = /** @class */ (function () {
  5950. /**
  5951. * Creates a Plane object according to the passed floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  5952. */
  5953. function Plane(a, b, c, d) {
  5954. this.normal = new Vector3(a, b, c);
  5955. this.d = d;
  5956. }
  5957. /**
  5958. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  5959. */
  5960. Plane.prototype.asArray = function () {
  5961. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  5962. };
  5963. // Methods
  5964. /**
  5965. * Returns a new plane copied from the current Plane.
  5966. */
  5967. Plane.prototype.clone = function () {
  5968. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  5969. };
  5970. /**
  5971. * Returns the string "Plane".
  5972. */
  5973. Plane.prototype.getClassName = function () {
  5974. return "Plane";
  5975. };
  5976. /**
  5977. * Returns the Plane hash code.
  5978. */
  5979. Plane.prototype.getHashCode = function () {
  5980. var hash = this.normal.getHashCode();
  5981. hash = (hash * 397) ^ (this.d || 0);
  5982. return hash;
  5983. };
  5984. /**
  5985. * Normalize the current Plane in place.
  5986. * Returns the updated Plane.
  5987. */
  5988. Plane.prototype.normalize = function () {
  5989. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  5990. var magnitude = 0.0;
  5991. if (norm !== 0) {
  5992. magnitude = 1.0 / norm;
  5993. }
  5994. this.normal.x *= magnitude;
  5995. this.normal.y *= magnitude;
  5996. this.normal.z *= magnitude;
  5997. this.d *= magnitude;
  5998. return this;
  5999. };
  6000. /**
  6001. * Returns a new Plane as the result of the transformation of the current Plane by the passed matrix.
  6002. */
  6003. Plane.prototype.transform = function (transformation) {
  6004. var transposedMatrix = Matrix.Transpose(transformation);
  6005. var x = this.normal.x;
  6006. var y = this.normal.y;
  6007. var z = this.normal.z;
  6008. var d = this.d;
  6009. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  6010. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  6011. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  6012. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  6013. return new Plane(normalX, normalY, normalZ, finalD);
  6014. };
  6015. /**
  6016. * Returns the dot product (float) of the point coordinates and the plane normal.
  6017. */
  6018. Plane.prototype.dotCoordinate = function (point) {
  6019. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  6020. };
  6021. /**
  6022. * Updates the current Plane from the plane defined by the three passed points.
  6023. * Returns the updated Plane.
  6024. */
  6025. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  6026. var x1 = point2.x - point1.x;
  6027. var y1 = point2.y - point1.y;
  6028. var z1 = point2.z - point1.z;
  6029. var x2 = point3.x - point1.x;
  6030. var y2 = point3.y - point1.y;
  6031. var z2 = point3.z - point1.z;
  6032. var yz = (y1 * z2) - (z1 * y2);
  6033. var xz = (z1 * x2) - (x1 * z2);
  6034. var xy = (x1 * y2) - (y1 * x2);
  6035. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  6036. var invPyth;
  6037. if (pyth !== 0) {
  6038. invPyth = 1.0 / pyth;
  6039. }
  6040. else {
  6041. invPyth = 0.0;
  6042. }
  6043. this.normal.x = yz * invPyth;
  6044. this.normal.y = xz * invPyth;
  6045. this.normal.z = xy * invPyth;
  6046. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  6047. return this;
  6048. };
  6049. /**
  6050. * Boolean : True is the vector "direction" is the same side than the plane normal.
  6051. */
  6052. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  6053. var dot = Vector3.Dot(this.normal, direction);
  6054. return (dot <= epsilon);
  6055. };
  6056. /**
  6057. * Returns the signed distance (float) from the passed point to the Plane.
  6058. */
  6059. Plane.prototype.signedDistanceTo = function (point) {
  6060. return Vector3.Dot(point, this.normal) + this.d;
  6061. };
  6062. // Statics
  6063. /**
  6064. * Returns a new Plane from the passed array.
  6065. */
  6066. Plane.FromArray = function (array) {
  6067. return new Plane(array[0], array[1], array[2], array[3]);
  6068. };
  6069. /**
  6070. * Returns a new Plane defined by the three passed points.
  6071. */
  6072. Plane.FromPoints = function (point1, point2, point3) {
  6073. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6074. result.copyFromPoints(point1, point2, point3);
  6075. return result;
  6076. };
  6077. /**
  6078. * Returns a new Plane the normal vector to this plane at the passed origin point.
  6079. * Note : the vector "normal" is updated because normalized.
  6080. */
  6081. Plane.FromPositionAndNormal = function (origin, normal) {
  6082. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6083. normal.normalize();
  6084. result.normal = normal;
  6085. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6086. return result;
  6087. };
  6088. /**
  6089. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the passed other point.
  6090. */
  6091. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  6092. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6093. return Vector3.Dot(point, normal) + d;
  6094. };
  6095. return Plane;
  6096. }());
  6097. BABYLON.Plane = Plane;
  6098. var Viewport = /** @class */ (function () {
  6099. /**
  6100. * Creates a Viewport object located at (x, y) and sized (width, height).
  6101. */
  6102. function Viewport(x, y, width, height) {
  6103. this.x = x;
  6104. this.y = y;
  6105. this.width = width;
  6106. this.height = height;
  6107. }
  6108. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  6109. if (renderWidthOrEngine.getRenderWidth) {
  6110. var engine = renderWidthOrEngine;
  6111. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  6112. }
  6113. var renderWidth = renderWidthOrEngine;
  6114. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  6115. };
  6116. /**
  6117. * Returns a new Viewport copied from the current one.
  6118. */
  6119. Viewport.prototype.clone = function () {
  6120. return new Viewport(this.x, this.y, this.width, this.height);
  6121. };
  6122. return Viewport;
  6123. }());
  6124. BABYLON.Viewport = Viewport;
  6125. var Frustum = /** @class */ (function () {
  6126. function Frustum() {
  6127. }
  6128. /**
  6129. * Returns a new array of 6 Frustum planes computed by the passed transformation matrix.
  6130. */
  6131. Frustum.GetPlanes = function (transform) {
  6132. var frustumPlanes = [];
  6133. for (var index = 0; index < 6; index++) {
  6134. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  6135. }
  6136. Frustum.GetPlanesToRef(transform, frustumPlanes);
  6137. return frustumPlanes;
  6138. };
  6139. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  6140. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  6141. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  6142. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  6143. frustumPlane.d = transform.m[15] + transform.m[14];
  6144. frustumPlane.normalize();
  6145. };
  6146. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  6147. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  6148. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  6149. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  6150. frustumPlane.d = transform.m[15] - transform.m[14];
  6151. frustumPlane.normalize();
  6152. };
  6153. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  6154. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  6155. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  6156. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  6157. frustumPlane.d = transform.m[15] + transform.m[12];
  6158. frustumPlane.normalize();
  6159. };
  6160. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  6161. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  6162. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  6163. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  6164. frustumPlane.d = transform.m[15] - transform.m[12];
  6165. frustumPlane.normalize();
  6166. };
  6167. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  6168. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  6169. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  6170. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  6171. frustumPlane.d = transform.m[15] - transform.m[13];
  6172. frustumPlane.normalize();
  6173. };
  6174. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  6175. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  6176. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  6177. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  6178. frustumPlane.d = transform.m[15] + transform.m[13];
  6179. frustumPlane.normalize();
  6180. };
  6181. /**
  6182. * Sets the passed array "frustumPlanes" with the 6 Frustum planes computed by the passed transformation matrix.
  6183. */
  6184. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  6185. // Near
  6186. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  6187. // Far
  6188. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  6189. // Left
  6190. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  6191. // Right
  6192. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  6193. // Top
  6194. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  6195. // Bottom
  6196. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  6197. };
  6198. return Frustum;
  6199. }());
  6200. BABYLON.Frustum = Frustum;
  6201. var Space;
  6202. (function (Space) {
  6203. Space[Space["LOCAL"] = 0] = "LOCAL";
  6204. Space[Space["WORLD"] = 1] = "WORLD";
  6205. Space[Space["BONE"] = 2] = "BONE";
  6206. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  6207. var Axis = /** @class */ (function () {
  6208. function Axis() {
  6209. }
  6210. Axis.X = new Vector3(1.0, 0.0, 0.0);
  6211. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  6212. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  6213. return Axis;
  6214. }());
  6215. BABYLON.Axis = Axis;
  6216. ;
  6217. var BezierCurve = /** @class */ (function () {
  6218. function BezierCurve() {
  6219. }
  6220. /**
  6221. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the passed x1, y1, x2, y2 floats.
  6222. */
  6223. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  6224. // Extract X (which is equal to time here)
  6225. var f0 = 1 - 3 * x2 + 3 * x1;
  6226. var f1 = 3 * x2 - 6 * x1;
  6227. var f2 = 3 * x1;
  6228. var refinedT = t;
  6229. for (var i = 0; i < 5; i++) {
  6230. var refinedT2 = refinedT * refinedT;
  6231. var refinedT3 = refinedT2 * refinedT;
  6232. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  6233. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  6234. refinedT -= (x - t) * slope;
  6235. refinedT = Math.min(1, Math.max(0, refinedT));
  6236. }
  6237. // Resolve cubic bezier for the given x
  6238. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  6239. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  6240. Math.pow(refinedT, 3);
  6241. };
  6242. return BezierCurve;
  6243. }());
  6244. BABYLON.BezierCurve = BezierCurve;
  6245. var Orientation;
  6246. (function (Orientation) {
  6247. Orientation[Orientation["CW"] = 0] = "CW";
  6248. Orientation[Orientation["CCW"] = 1] = "CCW";
  6249. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  6250. var Angle = /** @class */ (function () {
  6251. /**
  6252. * Creates an Angle object of "radians" radians (float).
  6253. */
  6254. function Angle(radians) {
  6255. var _this = this;
  6256. /**
  6257. * Returns the Angle value in degrees (float).
  6258. */
  6259. this.degrees = function () { return _this._radians * 180.0 / Math.PI; };
  6260. /**
  6261. * Returns the Angle value in radians (float).
  6262. */
  6263. this.radians = function () { return _this._radians; };
  6264. this._radians = radians;
  6265. if (this._radians < 0.0)
  6266. this._radians += (2.0 * Math.PI);
  6267. }
  6268. /**
  6269. * Returns a new Angle object valued with the angle value in radians between the two passed vectors.
  6270. */
  6271. Angle.BetweenTwoPoints = function (a, b) {
  6272. var delta = b.subtract(a);
  6273. var theta = Math.atan2(delta.y, delta.x);
  6274. return new Angle(theta);
  6275. };
  6276. /**
  6277. * Returns a new Angle object from the passed float in radians.
  6278. */
  6279. Angle.FromRadians = function (radians) {
  6280. return new Angle(radians);
  6281. };
  6282. /**
  6283. * Returns a new Angle object from the passed float in degrees.
  6284. */
  6285. Angle.FromDegrees = function (degrees) {
  6286. return new Angle(degrees * Math.PI / 180.0);
  6287. };
  6288. return Angle;
  6289. }());
  6290. BABYLON.Angle = Angle;
  6291. var Arc2 = /** @class */ (function () {
  6292. /**
  6293. * Creates an Arc object from the three passed points : start, middle and end.
  6294. */
  6295. function Arc2(startPoint, midPoint, endPoint) {
  6296. this.startPoint = startPoint;
  6297. this.midPoint = midPoint;
  6298. this.endPoint = endPoint;
  6299. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  6300. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  6301. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  6302. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  6303. 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);
  6304. this.radius = this.centerPoint.subtract(this.startPoint).length();
  6305. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  6306. var a1 = this.startAngle.degrees();
  6307. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  6308. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  6309. // angles correction
  6310. if (a2 - a1 > +180.0)
  6311. a2 -= 360.0;
  6312. if (a2 - a1 < -180.0)
  6313. a2 += 360.0;
  6314. if (a3 - a2 > +180.0)
  6315. a3 -= 360.0;
  6316. if (a3 - a2 < -180.0)
  6317. a3 += 360.0;
  6318. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  6319. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  6320. }
  6321. return Arc2;
  6322. }());
  6323. BABYLON.Arc2 = Arc2;
  6324. var Path2 = /** @class */ (function () {
  6325. /**
  6326. * Creates a Path2 object from the starting 2D coordinates x and y.
  6327. */
  6328. function Path2(x, y) {
  6329. this._points = new Array();
  6330. this._length = 0.0;
  6331. this.closed = false;
  6332. this._points.push(new Vector2(x, y));
  6333. }
  6334. /**
  6335. * Adds a new segment until the passed coordinates (x, y) to the current Path2.
  6336. * Returns the updated Path2.
  6337. */
  6338. Path2.prototype.addLineTo = function (x, y) {
  6339. if (this.closed) {
  6340. return this;
  6341. }
  6342. var newPoint = new Vector2(x, y);
  6343. var previousPoint = this._points[this._points.length - 1];
  6344. this._points.push(newPoint);
  6345. this._length += newPoint.subtract(previousPoint).length();
  6346. return this;
  6347. };
  6348. /**
  6349. * 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.
  6350. * Returns the updated Path2.
  6351. */
  6352. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  6353. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  6354. if (this.closed) {
  6355. return this;
  6356. }
  6357. var startPoint = this._points[this._points.length - 1];
  6358. var midPoint = new Vector2(midX, midY);
  6359. var endPoint = new Vector2(endX, endY);
  6360. var arc = new Arc2(startPoint, midPoint, endPoint);
  6361. var increment = arc.angle.radians() / numberOfSegments;
  6362. if (arc.orientation === Orientation.CW)
  6363. increment *= -1;
  6364. var currentAngle = arc.startAngle.radians() + increment;
  6365. for (var i = 0; i < numberOfSegments; i++) {
  6366. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  6367. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  6368. this.addLineTo(x, y);
  6369. currentAngle += increment;
  6370. }
  6371. return this;
  6372. };
  6373. /**
  6374. * Closes the Path2.
  6375. * Returns the Path2.
  6376. */
  6377. Path2.prototype.close = function () {
  6378. this.closed = true;
  6379. return this;
  6380. };
  6381. /**
  6382. * Returns the Path2 total length (float).
  6383. */
  6384. Path2.prototype.length = function () {
  6385. var result = this._length;
  6386. if (!this.closed) {
  6387. var lastPoint = this._points[this._points.length - 1];
  6388. var firstPoint = this._points[0];
  6389. result += (firstPoint.subtract(lastPoint).length());
  6390. }
  6391. return result;
  6392. };
  6393. /**
  6394. * Returns the Path2 internal array of points.
  6395. */
  6396. Path2.prototype.getPoints = function () {
  6397. return this._points;
  6398. };
  6399. /**
  6400. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  6401. */
  6402. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  6403. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  6404. return Vector2.Zero();
  6405. }
  6406. var lengthPosition = normalizedLengthPosition * this.length();
  6407. var previousOffset = 0;
  6408. for (var i = 0; i < this._points.length; i++) {
  6409. var j = (i + 1) % this._points.length;
  6410. var a = this._points[i];
  6411. var b = this._points[j];
  6412. var bToA = b.subtract(a);
  6413. var nextOffset = (bToA.length() + previousOffset);
  6414. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  6415. var dir = bToA.normalize();
  6416. var localOffset = lengthPosition - previousOffset;
  6417. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  6418. }
  6419. previousOffset = nextOffset;
  6420. }
  6421. return Vector2.Zero();
  6422. };
  6423. /**
  6424. * Returns a new Path2 starting at the coordinates (x, y).
  6425. */
  6426. Path2.StartingAt = function (x, y) {
  6427. return new Path2(x, y);
  6428. };
  6429. return Path2;
  6430. }());
  6431. BABYLON.Path2 = Path2;
  6432. var Path3D = /** @class */ (function () {
  6433. /**
  6434. * new Path3D(path, normal, raw)
  6435. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  6436. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  6437. * path : an array of Vector3, the curve axis of the Path3D
  6438. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  6439. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  6440. */
  6441. function Path3D(path, firstNormal, raw) {
  6442. if (firstNormal === void 0) { firstNormal = null; }
  6443. this.path = path;
  6444. this._curve = new Array();
  6445. this._distances = new Array();
  6446. this._tangents = new Array();
  6447. this._normals = new Array();
  6448. this._binormals = new Array();
  6449. for (var p = 0; p < path.length; p++) {
  6450. this._curve[p] = path[p].clone(); // hard copy
  6451. }
  6452. this._raw = raw || false;
  6453. this._compute(firstNormal);
  6454. }
  6455. /**
  6456. * Returns the Path3D array of successive Vector3 designing its curve.
  6457. */
  6458. Path3D.prototype.getCurve = function () {
  6459. return this._curve;
  6460. };
  6461. /**
  6462. * Returns an array populated with tangent vectors on each Path3D curve point.
  6463. */
  6464. Path3D.prototype.getTangents = function () {
  6465. return this._tangents;
  6466. };
  6467. /**
  6468. * Returns an array populated with normal vectors on each Path3D curve point.
  6469. */
  6470. Path3D.prototype.getNormals = function () {
  6471. return this._normals;
  6472. };
  6473. /**
  6474. * Returns an array populated with binormal vectors on each Path3D curve point.
  6475. */
  6476. Path3D.prototype.getBinormals = function () {
  6477. return this._binormals;
  6478. };
  6479. /**
  6480. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  6481. */
  6482. Path3D.prototype.getDistances = function () {
  6483. return this._distances;
  6484. };
  6485. /**
  6486. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  6487. * Returns the same object updated.
  6488. */
  6489. Path3D.prototype.update = function (path, firstNormal) {
  6490. if (firstNormal === void 0) { firstNormal = null; }
  6491. for (var p = 0; p < path.length; p++) {
  6492. this._curve[p].x = path[p].x;
  6493. this._curve[p].y = path[p].y;
  6494. this._curve[p].z = path[p].z;
  6495. }
  6496. this._compute(firstNormal);
  6497. return this;
  6498. };
  6499. // private function compute() : computes tangents, normals and binormals
  6500. Path3D.prototype._compute = function (firstNormal) {
  6501. var l = this._curve.length;
  6502. // first and last tangents
  6503. this._tangents[0] = this._getFirstNonNullVector(0);
  6504. if (!this._raw) {
  6505. this._tangents[0].normalize();
  6506. }
  6507. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  6508. if (!this._raw) {
  6509. this._tangents[l - 1].normalize();
  6510. }
  6511. // normals and binormals at first point : arbitrary vector with _normalVector()
  6512. var tg0 = this._tangents[0];
  6513. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  6514. this._normals[0] = pp0;
  6515. if (!this._raw) {
  6516. this._normals[0].normalize();
  6517. }
  6518. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  6519. if (!this._raw) {
  6520. this._binormals[0].normalize();
  6521. }
  6522. this._distances[0] = 0.0;
  6523. // normals and binormals : next points
  6524. var prev; // previous vector (segment)
  6525. var cur; // current vector (segment)
  6526. var curTang; // current tangent
  6527. // previous normal
  6528. var prevBinor; // previous binormal
  6529. for (var i = 1; i < l; i++) {
  6530. // tangents
  6531. prev = this._getLastNonNullVector(i);
  6532. if (i < l - 1) {
  6533. cur = this._getFirstNonNullVector(i);
  6534. this._tangents[i] = prev.add(cur);
  6535. this._tangents[i].normalize();
  6536. }
  6537. this._distances[i] = this._distances[i - 1] + prev.length();
  6538. // normals and binormals
  6539. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  6540. curTang = this._tangents[i];
  6541. prevBinor = this._binormals[i - 1];
  6542. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  6543. if (!this._raw) {
  6544. this._normals[i].normalize();
  6545. }
  6546. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  6547. if (!this._raw) {
  6548. this._binormals[i].normalize();
  6549. }
  6550. }
  6551. };
  6552. // private function getFirstNonNullVector(index)
  6553. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  6554. Path3D.prototype._getFirstNonNullVector = function (index) {
  6555. var i = 1;
  6556. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  6557. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  6558. i++;
  6559. nNVector = this._curve[index + i].subtract(this._curve[index]);
  6560. }
  6561. return nNVector;
  6562. };
  6563. // private function getLastNonNullVector(index)
  6564. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  6565. Path3D.prototype._getLastNonNullVector = function (index) {
  6566. var i = 1;
  6567. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  6568. while (nLVector.length() === 0 && index > i + 1) {
  6569. i++;
  6570. nLVector = this._curve[index].subtract(this._curve[index - i]);
  6571. }
  6572. return nLVector;
  6573. };
  6574. // private function normalVector(v0, vt, va) :
  6575. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  6576. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  6577. Path3D.prototype._normalVector = function (v0, vt, va) {
  6578. var normal0;
  6579. var tgl = vt.length();
  6580. if (tgl === 0.0) {
  6581. tgl = 1.0;
  6582. }
  6583. if (va === undefined || va === null) {
  6584. var point;
  6585. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) {
  6586. point = new Vector3(0.0, -1.0, 0.0);
  6587. }
  6588. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  6589. point = new Vector3(1.0, 0.0, 0.0);
  6590. }
  6591. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  6592. point = new Vector3(0.0, 0.0, 1.0);
  6593. }
  6594. else {
  6595. point = Vector3.Zero();
  6596. }
  6597. normal0 = Vector3.Cross(vt, point);
  6598. }
  6599. else {
  6600. normal0 = Vector3.Cross(vt, va);
  6601. Vector3.CrossToRef(normal0, vt, normal0);
  6602. }
  6603. normal0.normalize();
  6604. return normal0;
  6605. };
  6606. return Path3D;
  6607. }());
  6608. BABYLON.Path3D = Path3D;
  6609. var Curve3 = /** @class */ (function () {
  6610. /**
  6611. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  6612. * A Curve3 is designed from a series of successive Vector3.
  6613. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  6614. */
  6615. function Curve3(points) {
  6616. this._length = 0.0;
  6617. this._points = points;
  6618. this._length = this._computeLength(points);
  6619. }
  6620. /**
  6621. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  6622. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  6623. * @param v1 (Vector3) the control point
  6624. * @param v2 (Vector3) the end point of the Quadratic Bezier
  6625. * @param nbPoints (integer) the wanted number of points in the curve
  6626. */
  6627. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  6628. nbPoints = nbPoints > 2 ? nbPoints : 3;
  6629. var bez = new Array();
  6630. var equation = function (t, val0, val1, val2) {
  6631. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  6632. return res;
  6633. };
  6634. for (var i = 0; i <= nbPoints; i++) {
  6635. 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)));
  6636. }
  6637. return new Curve3(bez);
  6638. };
  6639. /**
  6640. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  6641. * @param v0 (Vector3) the origin point of the Cubic Bezier
  6642. * @param v1 (Vector3) the first control point
  6643. * @param v2 (Vector3) the second control point
  6644. * @param v3 (Vector3) the end point of the Cubic Bezier
  6645. * @param nbPoints (integer) the wanted number of points in the curve
  6646. */
  6647. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  6648. nbPoints = nbPoints > 3 ? nbPoints : 4;
  6649. var bez = new Array();
  6650. var equation = function (t, val0, val1, val2, val3) {
  6651. 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;
  6652. return res;
  6653. };
  6654. for (var i = 0; i <= nbPoints; i++) {
  6655. 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)));
  6656. }
  6657. return new Curve3(bez);
  6658. };
  6659. /**
  6660. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  6661. * @param p1 (Vector3) the origin point of the Hermite Spline
  6662. * @param t1 (Vector3) the tangent vector at the origin point
  6663. * @param p2 (Vector3) the end point of the Hermite Spline
  6664. * @param t2 (Vector3) the tangent vector at the end point
  6665. * @param nbPoints (integer) the wanted number of points in the curve
  6666. */
  6667. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  6668. var hermite = new Array();
  6669. var step = 1.0 / nbPoints;
  6670. for (var i = 0; i <= nbPoints; i++) {
  6671. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  6672. }
  6673. return new Curve3(hermite);
  6674. };
  6675. /**
  6676. * Returns a Curve3 object along a CatmullRom Spline curve :
  6677. * @param points (array of Vector3) the points the spline must pass through. At least, four points required.
  6678. * @param nbPoints (integer) the wanted number of points between each curve control points.
  6679. */
  6680. Curve3.CreateCatmullRomSpline = function (points, nbPoints) {
  6681. var totalPoints = new Array();
  6682. totalPoints.push(points[0].clone());
  6683. Array.prototype.push.apply(totalPoints, points);
  6684. totalPoints.push(points[points.length - 1].clone());
  6685. var catmullRom = new Array();
  6686. var step = 1.0 / nbPoints;
  6687. var amount = 0.0;
  6688. for (var i = 0; i < totalPoints.length - 3; i++) {
  6689. amount = 0;
  6690. for (var c = 0; c < nbPoints; c++) {
  6691. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  6692. amount += step;
  6693. }
  6694. }
  6695. i--;
  6696. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  6697. return new Curve3(catmullRom);
  6698. };
  6699. /**
  6700. * Returns the Curve3 stored array of successive Vector3
  6701. */
  6702. Curve3.prototype.getPoints = function () {
  6703. return this._points;
  6704. };
  6705. /**
  6706. * Returns the computed length (float) of the curve.
  6707. */
  6708. Curve3.prototype.length = function () {
  6709. return this._length;
  6710. };
  6711. /**
  6712. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  6713. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  6714. * curveA and curveB keep unchanged.
  6715. */
  6716. Curve3.prototype.continue = function (curve) {
  6717. var lastPoint = this._points[this._points.length - 1];
  6718. var continuedPoints = this._points.slice();
  6719. var curvePoints = curve.getPoints();
  6720. for (var i = 1; i < curvePoints.length; i++) {
  6721. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  6722. }
  6723. var continuedCurve = new Curve3(continuedPoints);
  6724. return continuedCurve;
  6725. };
  6726. Curve3.prototype._computeLength = function (path) {
  6727. var l = 0;
  6728. for (var i = 1; i < path.length; i++) {
  6729. l += (path[i].subtract(path[i - 1])).length();
  6730. }
  6731. return l;
  6732. };
  6733. return Curve3;
  6734. }());
  6735. BABYLON.Curve3 = Curve3;
  6736. // Vertex formats
  6737. var PositionNormalVertex = /** @class */ (function () {
  6738. function PositionNormalVertex(position, normal) {
  6739. if (position === void 0) { position = Vector3.Zero(); }
  6740. if (normal === void 0) { normal = Vector3.Up(); }
  6741. this.position = position;
  6742. this.normal = normal;
  6743. }
  6744. PositionNormalVertex.prototype.clone = function () {
  6745. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  6746. };
  6747. return PositionNormalVertex;
  6748. }());
  6749. BABYLON.PositionNormalVertex = PositionNormalVertex;
  6750. var PositionNormalTextureVertex = /** @class */ (function () {
  6751. function PositionNormalTextureVertex(position, normal, uv) {
  6752. if (position === void 0) { position = Vector3.Zero(); }
  6753. if (normal === void 0) { normal = Vector3.Up(); }
  6754. if (uv === void 0) { uv = Vector2.Zero(); }
  6755. this.position = position;
  6756. this.normal = normal;
  6757. this.uv = uv;
  6758. }
  6759. PositionNormalTextureVertex.prototype.clone = function () {
  6760. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  6761. };
  6762. return PositionNormalTextureVertex;
  6763. }());
  6764. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  6765. // Temporary pre-allocated objects for engine internal use
  6766. // usage in any internal function :
  6767. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  6768. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  6769. var Tmp = /** @class */ (function () {
  6770. function Tmp() {
  6771. }
  6772. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  6773. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  6774. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  6775. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  6776. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  6777. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  6778. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  6779. Matrix.Zero(), Matrix.Zero(),
  6780. Matrix.Zero(), Matrix.Zero(),
  6781. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  6782. return Tmp;
  6783. }());
  6784. BABYLON.Tmp = Tmp;
  6785. // Same as Tmp but not exported to keep it onyl for math functions to avoid conflicts
  6786. var MathTmp = /** @class */ (function () {
  6787. function MathTmp() {
  6788. }
  6789. MathTmp.Vector3 = [Vector3.Zero()];
  6790. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  6791. MathTmp.Quaternion = [Quaternion.Zero()];
  6792. return MathTmp;
  6793. }());
  6794. })(BABYLON || (BABYLON = {}));
  6795. //# sourceMappingURL=babylon.math.js.map
  6796. var BABYLON;
  6797. (function (BABYLON) {
  6798. var Scalar = /** @class */ (function () {
  6799. function Scalar() {
  6800. }
  6801. /**
  6802. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  6803. */
  6804. Scalar.WithinEpsilon = function (a, b, epsilon) {
  6805. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  6806. var num = a - b;
  6807. return -epsilon <= num && num <= epsilon;
  6808. };
  6809. /**
  6810. * Returns a string : the upper case translation of the number i to hexadecimal.
  6811. */
  6812. Scalar.ToHex = function (i) {
  6813. var str = i.toString(16);
  6814. if (i <= 15) {
  6815. return ("0" + str).toUpperCase();
  6816. }
  6817. return str.toUpperCase();
  6818. };
  6819. /**
  6820. * Returns -1 if value is negative and +1 is value is positive.
  6821. * Returns the value itself if it's equal to zero.
  6822. */
  6823. Scalar.Sign = function (value) {
  6824. value = +value; // convert to a number
  6825. if (value === 0 || isNaN(value))
  6826. return value;
  6827. return value > 0 ? 1 : -1;
  6828. };
  6829. /**
  6830. * Returns the value itself if it's between min and max.
  6831. * Returns min if the value is lower than min.
  6832. * Returns max if the value is greater than max.
  6833. */
  6834. Scalar.Clamp = function (value, min, max) {
  6835. if (min === void 0) { min = 0; }
  6836. if (max === void 0) { max = 1; }
  6837. return Math.min(max, Math.max(min, value));
  6838. };
  6839. /**
  6840. * Returns the log2 of value.
  6841. */
  6842. Scalar.Log2 = function (value) {
  6843. return Math.log(value) * Math.LOG2E;
  6844. };
  6845. /**
  6846. * Loops the value, so that it is never larger than length and never smaller than 0.
  6847. *
  6848. * This is similar to the modulo operator but it works with floating point numbers.
  6849. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  6850. * With t = 5 and length = 2.5, the result would be 0.0.
  6851. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  6852. */
  6853. Scalar.Repeat = function (value, length) {
  6854. return value - Math.floor(value / length) * length;
  6855. };
  6856. /**
  6857. * Normalize the value between 0.0 and 1.0 using min and max values
  6858. */
  6859. Scalar.Normalize = function (value, min, max) {
  6860. return (value - min) / (max - min);
  6861. };
  6862. /**
  6863. * Denormalize the value from 0.0 and 1.0 using min and max values
  6864. */
  6865. Scalar.Denormalize = function (normalized, min, max) {
  6866. return (normalized * (max - min) + min);
  6867. };
  6868. /**
  6869. * Calculates the shortest difference between two given angles given in degrees.
  6870. */
  6871. Scalar.DeltaAngle = function (current, target) {
  6872. var num = Scalar.Repeat(target - current, 360.0);
  6873. if (num > 180.0) {
  6874. num -= 360.0;
  6875. }
  6876. return num;
  6877. };
  6878. /**
  6879. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  6880. *
  6881. * The returned value will move back and forth between 0 and length
  6882. */
  6883. Scalar.PingPong = function (tx, length) {
  6884. var t = Scalar.Repeat(tx, length * 2.0);
  6885. return length - Math.abs(t - length);
  6886. };
  6887. /**
  6888. * Interpolates between min and max with smoothing at the limits.
  6889. *
  6890. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  6891. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  6892. */
  6893. Scalar.SmoothStep = function (from, to, tx) {
  6894. var t = Scalar.Clamp(tx);
  6895. t = -2.0 * t * t * t + 3.0 * t * t;
  6896. return to * t + from * (1.0 - t);
  6897. };
  6898. /**
  6899. * Moves a value current towards target.
  6900. *
  6901. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  6902. * Negative values of maxDelta pushes the value away from target.
  6903. */
  6904. Scalar.MoveTowards = function (current, target, maxDelta) {
  6905. var result = 0;
  6906. if (Math.abs(target - current) <= maxDelta) {
  6907. result = target;
  6908. }
  6909. else {
  6910. result = current + Scalar.Sign(target - current) * maxDelta;
  6911. }
  6912. return result;
  6913. };
  6914. /**
  6915. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  6916. *
  6917. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  6918. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  6919. */
  6920. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  6921. var num = Scalar.DeltaAngle(current, target);
  6922. var result = 0;
  6923. if (-maxDelta < num && num < maxDelta) {
  6924. result = target;
  6925. }
  6926. else {
  6927. target = current + num;
  6928. result = Scalar.MoveTowards(current, target, maxDelta);
  6929. }
  6930. return result;
  6931. };
  6932. /**
  6933. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  6934. */
  6935. Scalar.Lerp = function (start, end, amount) {
  6936. return start + ((end - start) * amount);
  6937. };
  6938. /**
  6939. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  6940. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  6941. */
  6942. Scalar.LerpAngle = function (start, end, amount) {
  6943. var num = Scalar.Repeat(end - start, 360.0);
  6944. if (num > 180.0) {
  6945. num -= 360.0;
  6946. }
  6947. return start + num * Scalar.Clamp(amount);
  6948. };
  6949. /**
  6950. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  6951. */
  6952. Scalar.InverseLerp = function (a, b, value) {
  6953. var result = 0;
  6954. if (a != b) {
  6955. result = Scalar.Clamp((value - a) / (b - a));
  6956. }
  6957. else {
  6958. result = 0.0;
  6959. }
  6960. return result;
  6961. };
  6962. /**
  6963. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  6964. */
  6965. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  6966. var squared = amount * amount;
  6967. var cubed = amount * squared;
  6968. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  6969. var part2 = (-2.0 * cubed) + (3.0 * squared);
  6970. var part3 = (cubed - (2.0 * squared)) + amount;
  6971. var part4 = cubed - squared;
  6972. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  6973. };
  6974. /**
  6975. * Returns a random float number between and min and max values
  6976. */
  6977. Scalar.RandomRange = function (min, max) {
  6978. if (min === max)
  6979. return min;
  6980. return ((Math.random() * (max - min)) + min);
  6981. };
  6982. /**
  6983. * This function returns percentage of a number in a given range.
  6984. *
  6985. * RangeToPercent(40,20,60) will return 0.5 (50%)
  6986. * RangeToPercent(34,0,100) will return 0.34 (34%)
  6987. */
  6988. Scalar.RangeToPercent = function (number, min, max) {
  6989. return ((number - min) / (max - min));
  6990. };
  6991. /**
  6992. * This function returns number that corresponds to the percentage in a given range.
  6993. *
  6994. * PercentToRange(0.34,0,100) will return 34.
  6995. */
  6996. Scalar.PercentToRange = function (percent, min, max) {
  6997. return ((max - min) * percent + min);
  6998. };
  6999. /**
  7000. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  7001. * @param angle The angle to normalize in radian.
  7002. * @return The converted angle.
  7003. */
  7004. Scalar.NormalizeRadians = function (angle) {
  7005. // More precise but slower version kept for reference.
  7006. // angle = angle % Tools.TwoPi;
  7007. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  7008. //if (angle > Math.PI) {
  7009. // angle -= Tools.TwoPi;
  7010. //}
  7011. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  7012. return angle;
  7013. };
  7014. /**
  7015. * Two pi constants convenient for computation.
  7016. */
  7017. Scalar.TwoPi = Math.PI * 2;
  7018. return Scalar;
  7019. }());
  7020. BABYLON.Scalar = Scalar;
  7021. })(BABYLON || (BABYLON = {}));
  7022. //# sourceMappingURL=babylon.math.scalar.js.map
  7023. //# sourceMappingURL=babylon.mixins.js.map
  7024. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  7025. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  7026. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  7027. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  7028. //# sourceMappingURL=babylon.webgl2.js.map
  7029. var BABYLON;
  7030. (function (BABYLON) {
  7031. var __decoratorInitialStore = {};
  7032. var __mergedStore = {};
  7033. var _copySource = function (creationFunction, source, instanciate) {
  7034. var destination = creationFunction();
  7035. // Tags
  7036. if (BABYLON.Tags) {
  7037. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7038. }
  7039. var classStore = getMergedStore(destination);
  7040. // Properties
  7041. for (var property in classStore) {
  7042. var propertyDescriptor = classStore[property];
  7043. var sourceProperty = source[property];
  7044. var propertyType = propertyDescriptor.type;
  7045. if (sourceProperty !== undefined && sourceProperty !== null) {
  7046. switch (propertyType) {
  7047. case 0: // Value
  7048. case 6:// Mesh reference
  7049. destination[property] = sourceProperty;
  7050. break;
  7051. case 1:// Texture
  7052. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  7053. break;
  7054. case 2: // Color3
  7055. case 3: // FresnelParameters
  7056. case 4: // Vector2
  7057. case 5: // Vector3
  7058. case 7: // Color Curves
  7059. case 10:// Quaternion
  7060. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  7061. break;
  7062. }
  7063. }
  7064. }
  7065. return destination;
  7066. };
  7067. function getDirectStore(target) {
  7068. var classKey = target.getClassName();
  7069. if (!__decoratorInitialStore[classKey]) {
  7070. __decoratorInitialStore[classKey] = {};
  7071. }
  7072. return __decoratorInitialStore[classKey];
  7073. }
  7074. /**
  7075. * Return the list of properties flagged as serializable
  7076. * @param target: host object
  7077. */
  7078. function getMergedStore(target) {
  7079. var classKey = target.getClassName();
  7080. if (__mergedStore[classKey]) {
  7081. return __mergedStore[classKey];
  7082. }
  7083. __mergedStore[classKey] = {};
  7084. var store = __mergedStore[classKey];
  7085. var currentTarget = target;
  7086. var currentKey = classKey;
  7087. while (currentKey) {
  7088. var initialStore = __decoratorInitialStore[currentKey];
  7089. for (var property in initialStore) {
  7090. store[property] = initialStore[property];
  7091. }
  7092. var parent_1 = void 0;
  7093. var done = false;
  7094. do {
  7095. parent_1 = Object.getPrototypeOf(currentTarget);
  7096. if (!parent_1.getClassName) {
  7097. done = true;
  7098. break;
  7099. }
  7100. if (parent_1.getClassName() !== currentKey) {
  7101. break;
  7102. }
  7103. currentTarget = parent_1;
  7104. } while (parent_1);
  7105. if (done) {
  7106. break;
  7107. }
  7108. currentKey = parent_1.getClassName();
  7109. currentTarget = parent_1;
  7110. }
  7111. return store;
  7112. }
  7113. function generateSerializableMember(type, sourceName) {
  7114. return function (target, propertyKey) {
  7115. var classStore = getDirectStore(target);
  7116. if (!classStore[propertyKey]) {
  7117. classStore[propertyKey] = { type: type, sourceName: sourceName };
  7118. }
  7119. };
  7120. }
  7121. function generateExpandMember(setCallback, targetKey) {
  7122. if (targetKey === void 0) { targetKey = null; }
  7123. return function (target, propertyKey) {
  7124. var key = targetKey || ("_" + propertyKey);
  7125. Object.defineProperty(target, propertyKey, {
  7126. get: function () {
  7127. return this[key];
  7128. },
  7129. set: function (value) {
  7130. if (this[key] === value) {
  7131. return;
  7132. }
  7133. this[key] = value;
  7134. target[setCallback].apply(this);
  7135. },
  7136. enumerable: true,
  7137. configurable: true
  7138. });
  7139. };
  7140. }
  7141. function expandToProperty(callback, targetKey) {
  7142. if (targetKey === void 0) { targetKey = null; }
  7143. return generateExpandMember(callback, targetKey);
  7144. }
  7145. BABYLON.expandToProperty = expandToProperty;
  7146. function serialize(sourceName) {
  7147. return generateSerializableMember(0, sourceName); // value member
  7148. }
  7149. BABYLON.serialize = serialize;
  7150. function serializeAsTexture(sourceName) {
  7151. return generateSerializableMember(1, sourceName); // texture member
  7152. }
  7153. BABYLON.serializeAsTexture = serializeAsTexture;
  7154. function serializeAsColor3(sourceName) {
  7155. return generateSerializableMember(2, sourceName); // color3 member
  7156. }
  7157. BABYLON.serializeAsColor3 = serializeAsColor3;
  7158. function serializeAsFresnelParameters(sourceName) {
  7159. return generateSerializableMember(3, sourceName); // fresnel parameters member
  7160. }
  7161. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  7162. function serializeAsVector2(sourceName) {
  7163. return generateSerializableMember(4, sourceName); // vector2 member
  7164. }
  7165. BABYLON.serializeAsVector2 = serializeAsVector2;
  7166. function serializeAsVector3(sourceName) {
  7167. return generateSerializableMember(5, sourceName); // vector3 member
  7168. }
  7169. BABYLON.serializeAsVector3 = serializeAsVector3;
  7170. function serializeAsMeshReference(sourceName) {
  7171. return generateSerializableMember(6, sourceName); // mesh reference member
  7172. }
  7173. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  7174. function serializeAsColorCurves(sourceName) {
  7175. return generateSerializableMember(7, sourceName); // color curves
  7176. }
  7177. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  7178. function serializeAsColor4(sourceName) {
  7179. return generateSerializableMember(8, sourceName); // color 4
  7180. }
  7181. BABYLON.serializeAsColor4 = serializeAsColor4;
  7182. function serializeAsImageProcessingConfiguration(sourceName) {
  7183. return generateSerializableMember(9, sourceName); // image processing
  7184. }
  7185. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  7186. function serializeAsQuaternion(sourceName) {
  7187. return generateSerializableMember(10, sourceName); // quaternion member
  7188. }
  7189. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  7190. var SerializationHelper = /** @class */ (function () {
  7191. function SerializationHelper() {
  7192. }
  7193. SerializationHelper.Serialize = function (entity, serializationObject) {
  7194. if (!serializationObject) {
  7195. serializationObject = {};
  7196. }
  7197. // Tags
  7198. if (BABYLON.Tags) {
  7199. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  7200. }
  7201. var serializedProperties = getMergedStore(entity);
  7202. // Properties
  7203. for (var property in serializedProperties) {
  7204. var propertyDescriptor = serializedProperties[property];
  7205. var targetPropertyName = propertyDescriptor.sourceName || property;
  7206. var propertyType = propertyDescriptor.type;
  7207. var sourceProperty = entity[property];
  7208. if (sourceProperty !== undefined && sourceProperty !== null) {
  7209. switch (propertyType) {
  7210. case 0:// Value
  7211. serializationObject[targetPropertyName] = sourceProperty;
  7212. break;
  7213. case 1:// Texture
  7214. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7215. break;
  7216. case 2:// Color3
  7217. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7218. break;
  7219. case 3:// FresnelParameters
  7220. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7221. break;
  7222. case 4:// Vector2
  7223. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7224. break;
  7225. case 5:// Vector3
  7226. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7227. break;
  7228. case 6:// Mesh reference
  7229. serializationObject[targetPropertyName] = sourceProperty.id;
  7230. break;
  7231. case 7:// Color Curves
  7232. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7233. break;
  7234. case 8:// Color 4
  7235. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7236. break;
  7237. case 9:// Image Processing
  7238. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7239. break;
  7240. }
  7241. }
  7242. }
  7243. return serializationObject;
  7244. };
  7245. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  7246. if (rootUrl === void 0) { rootUrl = null; }
  7247. var destination = creationFunction();
  7248. if (!rootUrl) {
  7249. rootUrl = "";
  7250. }
  7251. // Tags
  7252. if (BABYLON.Tags) {
  7253. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7254. }
  7255. var classStore = getMergedStore(destination);
  7256. // Properties
  7257. for (var property in classStore) {
  7258. var propertyDescriptor = classStore[property];
  7259. var sourceProperty = source[propertyDescriptor.sourceName || property];
  7260. var propertyType = propertyDescriptor.type;
  7261. if (sourceProperty !== undefined && sourceProperty !== null) {
  7262. var dest = destination;
  7263. switch (propertyType) {
  7264. case 0:// Value
  7265. dest[property] = sourceProperty;
  7266. break;
  7267. case 1:// Texture
  7268. if (scene) {
  7269. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  7270. }
  7271. break;
  7272. case 2:// Color3
  7273. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  7274. break;
  7275. case 3:// FresnelParameters
  7276. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  7277. break;
  7278. case 4:// Vector2
  7279. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  7280. break;
  7281. case 5:// Vector3
  7282. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  7283. break;
  7284. case 6:// Mesh reference
  7285. if (scene) {
  7286. dest[property] = scene.getLastMeshByID(sourceProperty);
  7287. }
  7288. break;
  7289. case 7:// Color Curves
  7290. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  7291. break;
  7292. case 8:// Color 4
  7293. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  7294. break;
  7295. case 9:// Image Processing
  7296. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  7297. break;
  7298. }
  7299. }
  7300. }
  7301. return destination;
  7302. };
  7303. SerializationHelper.Clone = function (creationFunction, source) {
  7304. return _copySource(creationFunction, source, false);
  7305. };
  7306. SerializationHelper.Instanciate = function (creationFunction, source) {
  7307. return _copySource(creationFunction, source, true);
  7308. };
  7309. return SerializationHelper;
  7310. }());
  7311. BABYLON.SerializationHelper = SerializationHelper;
  7312. })(BABYLON || (BABYLON = {}));
  7313. //# sourceMappingURL=babylon.decorators.js.map
  7314. var BABYLON;
  7315. (function (BABYLON) {
  7316. /**
  7317. * Wrapper class for promise with external resolve and reject.
  7318. */
  7319. var Deferred = /** @class */ (function () {
  7320. /**
  7321. * Constructor for this deferred object.
  7322. */
  7323. function Deferred() {
  7324. var _this = this;
  7325. this.promise = new Promise(function (resolve, reject) {
  7326. _this._resolve = resolve;
  7327. _this._reject = reject;
  7328. });
  7329. }
  7330. Object.defineProperty(Deferred.prototype, "resolve", {
  7331. /**
  7332. * The resolve method of the promise associated with this deferred object.
  7333. */
  7334. get: function () {
  7335. return this._resolve;
  7336. },
  7337. enumerable: true,
  7338. configurable: true
  7339. });
  7340. Object.defineProperty(Deferred.prototype, "reject", {
  7341. /**
  7342. * The reject method of the promise associated with this deferred object.
  7343. */
  7344. get: function () {
  7345. return this._reject;
  7346. },
  7347. enumerable: true,
  7348. configurable: true
  7349. });
  7350. return Deferred;
  7351. }());
  7352. BABYLON.Deferred = Deferred;
  7353. })(BABYLON || (BABYLON = {}));
  7354. //# sourceMappingURL=babylon.deferred.js.map
  7355. var BABYLON;
  7356. (function (BABYLON) {
  7357. /**
  7358. * A class serves as a medium between the observable and its observers
  7359. */
  7360. var EventState = /** @class */ (function () {
  7361. /**
  7362. * Create a new EventState
  7363. * @param mask defines the mask associated with this state
  7364. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  7365. * @param target defines the original target of the state
  7366. * @param currentTarget defines the current target of the state
  7367. */
  7368. function EventState(mask, skipNextObservers, target, currentTarget) {
  7369. if (skipNextObservers === void 0) { skipNextObservers = false; }
  7370. this.initalize(mask, skipNextObservers, target, currentTarget);
  7371. }
  7372. /**
  7373. * Initialize the current event state
  7374. * @param mask defines the mask associated with this state
  7375. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  7376. * @param target defines the original target of the state
  7377. * @param currentTarget defines the current target of the state
  7378. * @returns the current event state
  7379. */
  7380. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  7381. if (skipNextObservers === void 0) { skipNextObservers = false; }
  7382. this.mask = mask;
  7383. this.skipNextObservers = skipNextObservers;
  7384. this.target = target;
  7385. this.currentTarget = currentTarget;
  7386. return this;
  7387. };
  7388. return EventState;
  7389. }());
  7390. BABYLON.EventState = EventState;
  7391. /**
  7392. * Represent an Observer registered to a given Observable object.
  7393. */
  7394. var Observer = /** @class */ (function () {
  7395. /**
  7396. * Creates a new observer
  7397. * @param callback defines the callback to call when the observer is notified
  7398. * @param mask defines the mask of the observer (used to filter notifications)
  7399. * @param scope defines the current scope used to restore the JS context
  7400. */
  7401. function Observer(
  7402. /**
  7403. * Defines the callback to call when the observer is notified
  7404. */
  7405. callback,
  7406. /**
  7407. * Defines the mask of the observer (used to filter notifications)
  7408. */
  7409. mask,
  7410. /**
  7411. * Defines the current scope used to restore the JS context
  7412. */
  7413. scope) {
  7414. if (scope === void 0) { scope = null; }
  7415. this.callback = callback;
  7416. this.mask = mask;
  7417. this.scope = scope;
  7418. /** @ignore */
  7419. this._willBeUnregistered = false;
  7420. /**
  7421. * Gets or sets a property defining that the observer as to be unregistered after the next notification
  7422. */
  7423. this.unregisterOnNextCall = false;
  7424. }
  7425. return Observer;
  7426. }());
  7427. BABYLON.Observer = Observer;
  7428. /**
  7429. * Represent a list of observers registered to multiple Observables object.
  7430. */
  7431. var MultiObserver = /** @class */ (function () {
  7432. function MultiObserver() {
  7433. }
  7434. /**
  7435. * Release associated resources
  7436. */
  7437. MultiObserver.prototype.dispose = function () {
  7438. if (this._observers && this._observables) {
  7439. for (var index = 0; index < this._observers.length; index++) {
  7440. this._observables[index].remove(this._observers[index]);
  7441. }
  7442. }
  7443. this._observers = null;
  7444. this._observables = null;
  7445. };
  7446. /**
  7447. * Raise a callback when one of the observable will notify
  7448. * @param observables defines a list of observables to watch
  7449. * @param callback defines the callback to call on notification
  7450. * @param mask defines the mask used to filter notifications
  7451. * @param scope defines the current scope used to restore the JS context
  7452. * @returns the new MultiObserver
  7453. */
  7454. MultiObserver.Watch = function (observables, callback, mask, scope) {
  7455. if (mask === void 0) { mask = -1; }
  7456. if (scope === void 0) { scope = null; }
  7457. var result = new MultiObserver();
  7458. result._observers = new Array();
  7459. result._observables = observables;
  7460. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  7461. var observable = observables_1[_i];
  7462. var observer = observable.add(callback, mask, false, scope);
  7463. if (observer) {
  7464. result._observers.push(observer);
  7465. }
  7466. }
  7467. return result;
  7468. };
  7469. return MultiObserver;
  7470. }());
  7471. BABYLON.MultiObserver = MultiObserver;
  7472. /**
  7473. * The Observable class is a simple implementation of the Observable pattern.
  7474. * 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.
  7475. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  7476. * 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).
  7477. * 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.
  7478. */
  7479. var Observable = /** @class */ (function () {
  7480. /**
  7481. * Creates a new observable
  7482. * @param onObserverAdded defines a callback to call when a new observer is added
  7483. */
  7484. function Observable(onObserverAdded) {
  7485. this._observers = new Array();
  7486. this._eventState = new EventState(0);
  7487. if (onObserverAdded) {
  7488. this._onObserverAdded = onObserverAdded;
  7489. }
  7490. }
  7491. /**
  7492. * Create a new Observer with the specified callback
  7493. * @param callback the callback that will be executed for that Observer
  7494. * @param mask the mask used to filter observers
  7495. * @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.
  7496. * @param scope optional scope for the callback to be called from
  7497. * @param unregisterOnFirstCall defines if the observer as to be unregistered after the next notification
  7498. * @returns the new observer created for the callback
  7499. */
  7500. Observable.prototype.add = function (callback, mask, insertFirst, scope, unregisterOnFirstCall) {
  7501. if (mask === void 0) { mask = -1; }
  7502. if (insertFirst === void 0) { insertFirst = false; }
  7503. if (scope === void 0) { scope = null; }
  7504. if (unregisterOnFirstCall === void 0) { unregisterOnFirstCall = false; }
  7505. if (!callback) {
  7506. return null;
  7507. }
  7508. var observer = new Observer(callback, mask, scope);
  7509. observer.unregisterOnNextCall = unregisterOnFirstCall;
  7510. if (insertFirst) {
  7511. this._observers.unshift(observer);
  7512. }
  7513. else {
  7514. this._observers.push(observer);
  7515. }
  7516. if (this._onObserverAdded) {
  7517. this._onObserverAdded(observer);
  7518. }
  7519. return observer;
  7520. };
  7521. /**
  7522. * Remove an Observer from the Observable object
  7523. * @param observer the instance of the Observer to remove
  7524. * @returns false if it doesn't belong to this Observable
  7525. */
  7526. Observable.prototype.remove = function (observer) {
  7527. if (!observer) {
  7528. return false;
  7529. }
  7530. var index = this._observers.indexOf(observer);
  7531. if (index !== -1) {
  7532. this._observers.splice(index, 1);
  7533. return true;
  7534. }
  7535. return false;
  7536. };
  7537. /**
  7538. * Remove a callback from the Observable object
  7539. * @param callback the callback to remove
  7540. * @param scope optional scope. If used only the callbacks with this scope will be removed
  7541. * @returns false if it doesn't belong to this Observable
  7542. */
  7543. Observable.prototype.removeCallback = function (callback, scope) {
  7544. for (var index = 0; index < this._observers.length; index++) {
  7545. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  7546. this._observers.splice(index, 1);
  7547. return true;
  7548. }
  7549. }
  7550. return false;
  7551. };
  7552. Observable.prototype._deferUnregister = function (observer) {
  7553. var _this = this;
  7554. observer.unregisterOnNextCall = false;
  7555. observer._willBeUnregistered = true;
  7556. BABYLON.Tools.SetImmediate(function () {
  7557. _this.remove(observer);
  7558. });
  7559. };
  7560. /**
  7561. * Notify all Observers by calling their respective callback with the given data
  7562. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  7563. * @param eventData defines the data to send to all observers
  7564. * @param mask defines the mask of the current notification (observers with incompatible mask (ie mask & observer.mask === 0) will not be notified)
  7565. * @param target defines the original target of the state
  7566. * @param currentTarget defines the current target of the state
  7567. * @returns false if the complete observer chain was not processed (because one observer set the skipNextObservers to true)
  7568. */
  7569. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  7570. if (mask === void 0) { mask = -1; }
  7571. if (!this._observers.length) {
  7572. return true;
  7573. }
  7574. var state = this._eventState;
  7575. state.mask = mask;
  7576. state.target = target;
  7577. state.currentTarget = currentTarget;
  7578. state.skipNextObservers = false;
  7579. state.lastReturnValue = eventData;
  7580. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  7581. var obs = _a[_i];
  7582. if (obs._willBeUnregistered) {
  7583. continue;
  7584. }
  7585. if (obs.mask & mask) {
  7586. if (obs.scope) {
  7587. state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]);
  7588. }
  7589. else {
  7590. state.lastReturnValue = obs.callback(eventData, state);
  7591. }
  7592. if (obs.unregisterOnNextCall) {
  7593. this._deferUnregister(obs);
  7594. }
  7595. }
  7596. if (state.skipNextObservers) {
  7597. return false;
  7598. }
  7599. }
  7600. return true;
  7601. };
  7602. /**
  7603. * Calling this will execute each callback, expecting it to be a promise or return a value.
  7604. * If at any point in the chain one function fails, the promise will fail and the execution will not continue.
  7605. * This is useful when a chain of events (sometimes async events) is needed to initialize a certain object
  7606. * and it is crucial that all callbacks will be executed.
  7607. * The order of the callbacks is kept, callbacks are not executed parallel.
  7608. *
  7609. * @param eventData The data to be sent to each callback
  7610. * @param mask is used to filter observers defaults to -1
  7611. * @param target defines the callback target (see EventState)
  7612. * @param currentTarget defines he current object in the bubbling phase
  7613. * @returns {Promise<T>} will return a Promise than resolves when all callbacks executed successfully.
  7614. */
  7615. Observable.prototype.notifyObserversWithPromise = function (eventData, mask, target, currentTarget) {
  7616. var _this = this;
  7617. if (mask === void 0) { mask = -1; }
  7618. // create an empty promise
  7619. var p = Promise.resolve(eventData);
  7620. // no observers? return this promise.
  7621. if (!this._observers.length) {
  7622. return p;
  7623. }
  7624. var state = this._eventState;
  7625. state.mask = mask;
  7626. state.target = target;
  7627. state.currentTarget = currentTarget;
  7628. state.skipNextObservers = false;
  7629. // execute one callback after another (not using Promise.all, the order is important)
  7630. this._observers.forEach(function (obs) {
  7631. if (state.skipNextObservers) {
  7632. return;
  7633. }
  7634. if (obs._willBeUnregistered) {
  7635. return;
  7636. }
  7637. if (obs.mask & mask) {
  7638. if (obs.scope) {
  7639. p = p.then(function (lastReturnedValue) {
  7640. state.lastReturnValue = lastReturnedValue;
  7641. return obs.callback.apply(obs.scope, [eventData, state]);
  7642. });
  7643. }
  7644. else {
  7645. p = p.then(function (lastReturnedValue) {
  7646. state.lastReturnValue = lastReturnedValue;
  7647. return obs.callback(eventData, state);
  7648. });
  7649. }
  7650. if (obs.unregisterOnNextCall) {
  7651. _this._deferUnregister(obs);
  7652. }
  7653. }
  7654. });
  7655. // return the eventData
  7656. return p.then(function () { return eventData; });
  7657. };
  7658. /**
  7659. * Notify a specific observer
  7660. * @param observer defines the observer to notify
  7661. * @param eventData defines the data to be sent to each callback
  7662. * @param mask is used to filter observers defaults to -1
  7663. */
  7664. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  7665. if (mask === void 0) { mask = -1; }
  7666. var state = this._eventState;
  7667. state.mask = mask;
  7668. state.skipNextObservers = false;
  7669. observer.callback(eventData, state);
  7670. };
  7671. /**
  7672. * Gets a boolean indicating if the observable has at least one observer
  7673. * @returns true is the Observable has at least one Observer registered
  7674. */
  7675. Observable.prototype.hasObservers = function () {
  7676. return this._observers.length > 0;
  7677. };
  7678. /**
  7679. * Clear the list of observers
  7680. */
  7681. Observable.prototype.clear = function () {
  7682. this._observers = new Array();
  7683. this._onObserverAdded = null;
  7684. };
  7685. /**
  7686. * Clone the current observable
  7687. * @returns a new observable
  7688. */
  7689. Observable.prototype.clone = function () {
  7690. var result = new Observable();
  7691. result._observers = this._observers.slice(0);
  7692. return result;
  7693. };
  7694. /**
  7695. * Does this observable handles observer registered with a given mask
  7696. * @param mask defines the mask to be tested
  7697. * @return whether or not one observer registered with the given mask is handeled
  7698. **/
  7699. Observable.prototype.hasSpecificMask = function (mask) {
  7700. if (mask === void 0) { mask = -1; }
  7701. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  7702. var obs = _a[_i];
  7703. if (obs.mask & mask || obs.mask === mask) {
  7704. return true;
  7705. }
  7706. }
  7707. return false;
  7708. };
  7709. return Observable;
  7710. }());
  7711. BABYLON.Observable = Observable;
  7712. })(BABYLON || (BABYLON = {}));
  7713. //# sourceMappingURL=babylon.observable.js.map
  7714. var BABYLON;
  7715. (function (BABYLON) {
  7716. var SmartArray = /** @class */ (function () {
  7717. function SmartArray(capacity) {
  7718. this.length = 0;
  7719. this.data = new Array(capacity);
  7720. this._id = SmartArray._GlobalId++;
  7721. }
  7722. SmartArray.prototype.push = function (value) {
  7723. this.data[this.length++] = value;
  7724. if (this.length > this.data.length) {
  7725. this.data.length *= 2;
  7726. }
  7727. };
  7728. SmartArray.prototype.forEach = function (func) {
  7729. for (var index = 0; index < this.length; index++) {
  7730. func(this.data[index]);
  7731. }
  7732. };
  7733. SmartArray.prototype.sort = function (compareFn) {
  7734. this.data.sort(compareFn);
  7735. };
  7736. SmartArray.prototype.reset = function () {
  7737. this.length = 0;
  7738. };
  7739. SmartArray.prototype.dispose = function () {
  7740. this.reset();
  7741. if (this.data) {
  7742. this.data.length = 0;
  7743. this.data = [];
  7744. }
  7745. };
  7746. SmartArray.prototype.concat = function (array) {
  7747. if (array.length === 0) {
  7748. return;
  7749. }
  7750. if (this.length + array.length > this.data.length) {
  7751. this.data.length = (this.length + array.length) * 2;
  7752. }
  7753. for (var index = 0; index < array.length; index++) {
  7754. this.data[this.length++] = (array.data || array)[index];
  7755. }
  7756. };
  7757. SmartArray.prototype.indexOf = function (value) {
  7758. var position = this.data.indexOf(value);
  7759. if (position >= this.length) {
  7760. return -1;
  7761. }
  7762. return position;
  7763. };
  7764. SmartArray.prototype.contains = function (value) {
  7765. return this.data.indexOf(value) !== -1;
  7766. };
  7767. // Statics
  7768. SmartArray._GlobalId = 0;
  7769. return SmartArray;
  7770. }());
  7771. BABYLON.SmartArray = SmartArray;
  7772. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  7773. __extends(SmartArrayNoDuplicate, _super);
  7774. function SmartArrayNoDuplicate() {
  7775. var _this = _super !== null && _super.apply(this, arguments) || this;
  7776. _this._duplicateId = 0;
  7777. return _this;
  7778. }
  7779. SmartArrayNoDuplicate.prototype.push = function (value) {
  7780. _super.prototype.push.call(this, value);
  7781. if (!value.__smartArrayFlags) {
  7782. value.__smartArrayFlags = {};
  7783. }
  7784. value.__smartArrayFlags[this._id] = this._duplicateId;
  7785. };
  7786. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  7787. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  7788. return false;
  7789. }
  7790. this.push(value);
  7791. return true;
  7792. };
  7793. SmartArrayNoDuplicate.prototype.reset = function () {
  7794. _super.prototype.reset.call(this);
  7795. this._duplicateId++;
  7796. };
  7797. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  7798. if (array.length === 0) {
  7799. return;
  7800. }
  7801. if (this.length + array.length > this.data.length) {
  7802. this.data.length = (this.length + array.length) * 2;
  7803. }
  7804. for (var index = 0; index < array.length; index++) {
  7805. var item = (array.data || array)[index];
  7806. this.pushNoDuplicate(item);
  7807. }
  7808. };
  7809. return SmartArrayNoDuplicate;
  7810. }(SmartArray));
  7811. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  7812. })(BABYLON || (BABYLON = {}));
  7813. //# sourceMappingURL=babylon.smartArray.js.map
  7814. var BABYLON;
  7815. (function (BABYLON) {
  7816. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  7817. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  7818. var LoadFileError = /** @class */ (function (_super) {
  7819. __extends(LoadFileError, _super);
  7820. function LoadFileError(message, request) {
  7821. var _this = _super.call(this, message) || this;
  7822. _this.request = request;
  7823. _this.name = "LoadFileError";
  7824. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  7825. return _this;
  7826. }
  7827. // Polyfill for Object.setPrototypeOf if necessary.
  7828. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  7829. return LoadFileError;
  7830. }(Error));
  7831. BABYLON.LoadFileError = LoadFileError;
  7832. var RetryStrategy = /** @class */ (function () {
  7833. function RetryStrategy() {
  7834. }
  7835. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  7836. if (maxRetries === void 0) { maxRetries = 3; }
  7837. if (baseInterval === void 0) { baseInterval = 500; }
  7838. return function (url, request, retryIndex) {
  7839. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  7840. return -1;
  7841. }
  7842. return Math.pow(2, retryIndex) * baseInterval;
  7843. };
  7844. };
  7845. return RetryStrategy;
  7846. }());
  7847. BABYLON.RetryStrategy = RetryStrategy;
  7848. // Screenshots
  7849. var screenshotCanvas;
  7850. var cloneValue = function (source, destinationObject) {
  7851. if (!source)
  7852. return null;
  7853. if (source instanceof BABYLON.Mesh) {
  7854. return null;
  7855. }
  7856. if (source instanceof BABYLON.SubMesh) {
  7857. return source.clone(destinationObject);
  7858. }
  7859. else if (source.clone) {
  7860. return source.clone();
  7861. }
  7862. return null;
  7863. };
  7864. var Tools = /** @class */ (function () {
  7865. function Tools() {
  7866. }
  7867. /**
  7868. * Interpolates between a and b via alpha
  7869. * @param a The lower value (returned when alpha = 0)
  7870. * @param b The upper value (returned when alpha = 1)
  7871. * @param alpha The interpolation-factor
  7872. * @return The mixed value
  7873. */
  7874. Tools.Mix = function (a, b, alpha) {
  7875. return a * (1 - alpha) + b * alpha;
  7876. };
  7877. Tools.Instantiate = function (className) {
  7878. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  7879. return Tools.RegisteredExternalClasses[className];
  7880. }
  7881. var arr = className.split(".");
  7882. var fn = (window || this);
  7883. for (var i = 0, len = arr.length; i < len; i++) {
  7884. fn = fn[arr[i]];
  7885. }
  7886. if (typeof fn !== "function") {
  7887. return null;
  7888. }
  7889. return fn;
  7890. };
  7891. /**
  7892. * Provides a slice function that will work even on IE
  7893. * @param data defines the array to slice
  7894. * @returns the new sliced array
  7895. */
  7896. Tools.Slice = function (data) {
  7897. if (data.slice) {
  7898. return data.slice();
  7899. }
  7900. return Array.prototype.slice.call(data);
  7901. };
  7902. Tools.SetImmediate = function (action) {
  7903. if (window.setImmediate) {
  7904. window.setImmediate(action);
  7905. }
  7906. else {
  7907. setTimeout(action, 1);
  7908. }
  7909. };
  7910. Tools.IsExponentOfTwo = function (value) {
  7911. var count = 1;
  7912. do {
  7913. count *= 2;
  7914. } while (count < value);
  7915. return count === value;
  7916. };
  7917. /**
  7918. * Find the next highest power of two.
  7919. * @param x Number to start search from.
  7920. * @return Next highest power of two.
  7921. */
  7922. Tools.CeilingPOT = function (x) {
  7923. x--;
  7924. x |= x >> 1;
  7925. x |= x >> 2;
  7926. x |= x >> 4;
  7927. x |= x >> 8;
  7928. x |= x >> 16;
  7929. x++;
  7930. return x;
  7931. };
  7932. /**
  7933. * Find the next lowest power of two.
  7934. * @param x Number to start search from.
  7935. * @return Next lowest power of two.
  7936. */
  7937. Tools.FloorPOT = function (x) {
  7938. x = x | (x >> 1);
  7939. x = x | (x >> 2);
  7940. x = x | (x >> 4);
  7941. x = x | (x >> 8);
  7942. x = x | (x >> 16);
  7943. return x - (x >> 1);
  7944. };
  7945. /**
  7946. * Find the nearest power of two.
  7947. * @param x Number to start search from.
  7948. * @return Next nearest power of two.
  7949. */
  7950. Tools.NearestPOT = function (x) {
  7951. var c = Tools.CeilingPOT(x);
  7952. var f = Tools.FloorPOT(x);
  7953. return (c - x) > (x - f) ? f : c;
  7954. };
  7955. Tools.GetExponentOfTwo = function (value, max, mode) {
  7956. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  7957. var pot;
  7958. switch (mode) {
  7959. case BABYLON.Engine.SCALEMODE_FLOOR:
  7960. pot = Tools.FloorPOT(value);
  7961. break;
  7962. case BABYLON.Engine.SCALEMODE_NEAREST:
  7963. pot = Tools.NearestPOT(value);
  7964. break;
  7965. case BABYLON.Engine.SCALEMODE_CEILING:
  7966. default:
  7967. pot = Tools.CeilingPOT(value);
  7968. break;
  7969. }
  7970. return Math.min(pot, max);
  7971. };
  7972. Tools.GetFilename = function (path) {
  7973. var index = path.lastIndexOf("/");
  7974. if (index < 0)
  7975. return path;
  7976. return path.substring(index + 1);
  7977. };
  7978. /**
  7979. * Extracts the "folder" part of a path (everything before the filename).
  7980. * @param uri The URI to extract the info from
  7981. * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present
  7982. * @returns The "folder" part of the path
  7983. */
  7984. Tools.GetFolderPath = function (uri, returnUnchangedIfNoSlash) {
  7985. if (returnUnchangedIfNoSlash === void 0) { returnUnchangedIfNoSlash = false; }
  7986. var index = uri.lastIndexOf("/");
  7987. if (index < 0) {
  7988. if (returnUnchangedIfNoSlash) {
  7989. return uri;
  7990. }
  7991. return "";
  7992. }
  7993. return uri.substring(0, index + 1);
  7994. };
  7995. Tools.GetDOMTextContent = function (element) {
  7996. var result = "";
  7997. var child = element.firstChild;
  7998. while (child) {
  7999. if (child.nodeType === 3) {
  8000. result += child.textContent;
  8001. }
  8002. child = child.nextSibling;
  8003. }
  8004. return result;
  8005. };
  8006. Tools.ToDegrees = function (angle) {
  8007. return angle * 180 / Math.PI;
  8008. };
  8009. Tools.ToRadians = function (angle) {
  8010. return angle * Math.PI / 180;
  8011. };
  8012. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  8013. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  8014. var output = "";
  8015. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  8016. var i = 0;
  8017. var bytes = new Uint8Array(buffer);
  8018. while (i < bytes.length) {
  8019. chr1 = bytes[i++];
  8020. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  8021. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  8022. enc1 = chr1 >> 2;
  8023. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  8024. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  8025. enc4 = chr3 & 63;
  8026. if (isNaN(chr2)) {
  8027. enc3 = enc4 = 64;
  8028. }
  8029. else if (isNaN(chr3)) {
  8030. enc4 = 64;
  8031. }
  8032. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  8033. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  8034. }
  8035. return "data:image/png;base64," + output;
  8036. };
  8037. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  8038. if (bias === void 0) { bias = null; }
  8039. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8040. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8041. for (var index = indexStart; index < indexStart + indexCount; index++) {
  8042. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  8043. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8044. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8045. }
  8046. if (bias) {
  8047. minimum.x -= minimum.x * bias.x + bias.y;
  8048. minimum.y -= minimum.y * bias.x + bias.y;
  8049. minimum.z -= minimum.z * bias.x + bias.y;
  8050. maximum.x += maximum.x * bias.x + bias.y;
  8051. maximum.y += maximum.y * bias.x + bias.y;
  8052. maximum.z += maximum.z * bias.x + bias.y;
  8053. }
  8054. return {
  8055. minimum: minimum,
  8056. maximum: maximum
  8057. };
  8058. };
  8059. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  8060. if (bias === void 0) { bias = null; }
  8061. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8062. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8063. if (!stride) {
  8064. stride = 3;
  8065. }
  8066. for (var index = start; index < start + count; index++) {
  8067. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  8068. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8069. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8070. }
  8071. if (bias) {
  8072. minimum.x -= minimum.x * bias.x + bias.y;
  8073. minimum.y -= minimum.y * bias.x + bias.y;
  8074. minimum.z -= minimum.z * bias.x + bias.y;
  8075. maximum.x += maximum.x * bias.x + bias.y;
  8076. maximum.y += maximum.y * bias.x + bias.y;
  8077. maximum.z += maximum.z * bias.x + bias.y;
  8078. }
  8079. return {
  8080. minimum: minimum,
  8081. maximum: maximum
  8082. };
  8083. };
  8084. Tools.Vector2ArrayFeeder = function (array) {
  8085. return function (index) {
  8086. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  8087. var length = isFloatArray ? array.length / 2 : array.length;
  8088. if (index >= length) {
  8089. return null;
  8090. }
  8091. if (isFloatArray) {
  8092. var fa = array;
  8093. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  8094. }
  8095. var a = array;
  8096. return a[index];
  8097. };
  8098. };
  8099. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  8100. if (bias === void 0) { bias = null; }
  8101. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  8102. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  8103. var i = 0;
  8104. var cur = feeder(i++);
  8105. while (cur) {
  8106. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  8107. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  8108. cur = feeder(i++);
  8109. }
  8110. if (bias) {
  8111. minimum.x -= minimum.x * bias.x + bias.y;
  8112. minimum.y -= minimum.y * bias.x + bias.y;
  8113. maximum.x += maximum.x * bias.x + bias.y;
  8114. maximum.y += maximum.y * bias.x + bias.y;
  8115. }
  8116. return {
  8117. minimum: minimum,
  8118. maximum: maximum
  8119. };
  8120. };
  8121. Tools.MakeArray = function (obj, allowsNullUndefined) {
  8122. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  8123. return null;
  8124. return Array.isArray(obj) ? obj : [obj];
  8125. };
  8126. // Misc.
  8127. Tools.GetPointerPrefix = function () {
  8128. var eventPrefix = "pointer";
  8129. // Check if pointer events are supported
  8130. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  8131. eventPrefix = "mouse";
  8132. }
  8133. return eventPrefix;
  8134. };
  8135. /**
  8136. * @param func - the function to be called
  8137. * @param requester - the object that will request the next frame. Falls back to window.
  8138. */
  8139. Tools.QueueNewFrame = function (func, requester) {
  8140. if (!Tools.IsWindowObjectExist()) {
  8141. return setTimeout(func, 16);
  8142. }
  8143. if (!requester) {
  8144. requester = window;
  8145. }
  8146. if (requester.requestAnimationFrame) {
  8147. return requester.requestAnimationFrame(func);
  8148. }
  8149. else if (requester.msRequestAnimationFrame) {
  8150. return requester.msRequestAnimationFrame(func);
  8151. }
  8152. else if (requester.webkitRequestAnimationFrame) {
  8153. return requester.webkitRequestAnimationFrame(func);
  8154. }
  8155. else if (requester.mozRequestAnimationFrame) {
  8156. return requester.mozRequestAnimationFrame(func);
  8157. }
  8158. else if (requester.oRequestAnimationFrame) {
  8159. return requester.oRequestAnimationFrame(func);
  8160. }
  8161. else {
  8162. return window.setTimeout(func, 16);
  8163. }
  8164. };
  8165. Tools.RequestFullscreen = function (element) {
  8166. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  8167. if (!requestFunction)
  8168. return;
  8169. requestFunction.call(element);
  8170. };
  8171. Tools.ExitFullscreen = function () {
  8172. if (document.exitFullscreen) {
  8173. document.exitFullscreen();
  8174. }
  8175. else if (document.mozCancelFullScreen) {
  8176. document.mozCancelFullScreen();
  8177. }
  8178. else if (document.webkitCancelFullScreen) {
  8179. document.webkitCancelFullScreen();
  8180. }
  8181. else if (document.msCancelFullScreen) {
  8182. document.msCancelFullScreen();
  8183. }
  8184. };
  8185. Tools.SetCorsBehavior = function (url, element) {
  8186. if (url && url.indexOf("data:") === 0) {
  8187. return;
  8188. }
  8189. if (Tools.CorsBehavior) {
  8190. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  8191. element.crossOrigin = Tools.CorsBehavior;
  8192. }
  8193. else {
  8194. var result = Tools.CorsBehavior(url);
  8195. if (result) {
  8196. element.crossOrigin = result;
  8197. }
  8198. }
  8199. }
  8200. };
  8201. // External files
  8202. Tools.CleanUrl = function (url) {
  8203. url = url.replace(/#/mg, "%23");
  8204. return url;
  8205. };
  8206. Tools.LoadImage = function (url, onLoad, onError, database) {
  8207. if (url instanceof ArrayBuffer) {
  8208. url = Tools.EncodeArrayBufferTobase64(url);
  8209. }
  8210. url = Tools.CleanUrl(url);
  8211. url = Tools.PreprocessUrl(url);
  8212. var img = new Image();
  8213. Tools.SetCorsBehavior(url, img);
  8214. var loadHandler = function () {
  8215. img.removeEventListener("load", loadHandler);
  8216. img.removeEventListener("error", errorHandler);
  8217. onLoad(img);
  8218. };
  8219. var errorHandler = function (err) {
  8220. img.removeEventListener("load", loadHandler);
  8221. img.removeEventListener("error", errorHandler);
  8222. Tools.Error("Error while trying to load image: " + url);
  8223. if (onError) {
  8224. onError("Error while trying to load image: " + url, err);
  8225. }
  8226. };
  8227. img.addEventListener("load", loadHandler);
  8228. img.addEventListener("error", errorHandler);
  8229. var noIndexedDB = function () {
  8230. img.src = url;
  8231. };
  8232. var loadFromIndexedDB = function () {
  8233. if (database) {
  8234. database.loadImageFromDB(url, img);
  8235. }
  8236. };
  8237. //ANY database to do!
  8238. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  8239. database.openAsync(loadFromIndexedDB, noIndexedDB);
  8240. }
  8241. else {
  8242. if (url.indexOf("file:") !== -1) {
  8243. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  8244. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  8245. try {
  8246. var blobURL;
  8247. try {
  8248. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  8249. }
  8250. catch (ex) {
  8251. // Chrome doesn't support oneTimeOnly parameter
  8252. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  8253. }
  8254. img.src = blobURL;
  8255. }
  8256. catch (e) {
  8257. img.src = "";
  8258. }
  8259. return img;
  8260. }
  8261. }
  8262. noIndexedDB();
  8263. }
  8264. return img;
  8265. };
  8266. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  8267. url = Tools.CleanUrl(url);
  8268. url = Tools.PreprocessUrl(url);
  8269. // If file and file input are set
  8270. if (url.indexOf("file:") !== -1) {
  8271. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  8272. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  8273. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  8274. }
  8275. }
  8276. var loadUrl = Tools.BaseUrl + url;
  8277. var aborted = false;
  8278. var fileRequest = {
  8279. onCompleteObservable: new BABYLON.Observable(),
  8280. abort: function () { return aborted = true; },
  8281. };
  8282. var requestFile = function () {
  8283. var request = new XMLHttpRequest();
  8284. var retryHandle = null;
  8285. fileRequest.abort = function () {
  8286. aborted = true;
  8287. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  8288. request.abort();
  8289. }
  8290. if (retryHandle !== null) {
  8291. clearTimeout(retryHandle);
  8292. retryHandle = null;
  8293. }
  8294. };
  8295. var retryLoop = function (retryIndex) {
  8296. request.open('GET', loadUrl, true);
  8297. if (useArrayBuffer) {
  8298. request.responseType = "arraybuffer";
  8299. }
  8300. if (onProgress) {
  8301. request.addEventListener("progress", onProgress);
  8302. }
  8303. var onLoadEnd = function () {
  8304. request.removeEventListener("loadend", onLoadEnd);
  8305. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  8306. fileRequest.onCompleteObservable.clear();
  8307. };
  8308. request.addEventListener("loadend", onLoadEnd);
  8309. var onReadyStateChange = function () {
  8310. if (aborted) {
  8311. return;
  8312. }
  8313. // In case of undefined state in some browsers.
  8314. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  8315. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  8316. request.removeEventListener("readystatechange", onReadyStateChange);
  8317. if (request.status >= 200 && request.status < 300 || (!Tools.IsWindowObjectExist() && (request.status === 0))) {
  8318. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  8319. return;
  8320. }
  8321. var retryStrategy = Tools.DefaultRetryStrategy;
  8322. if (retryStrategy) {
  8323. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  8324. if (waitTime !== -1) {
  8325. // Prevent the request from completing for retry.
  8326. request.removeEventListener("loadend", onLoadEnd);
  8327. request = new XMLHttpRequest();
  8328. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  8329. return;
  8330. }
  8331. }
  8332. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  8333. if (onError) {
  8334. onError(request, e);
  8335. }
  8336. else {
  8337. throw e;
  8338. }
  8339. }
  8340. };
  8341. request.addEventListener("readystatechange", onReadyStateChange);
  8342. request.send();
  8343. };
  8344. retryLoop(0);
  8345. };
  8346. // Caching all files
  8347. if (database && database.enableSceneOffline) {
  8348. var noIndexedDB_1 = function () {
  8349. if (!aborted) {
  8350. requestFile();
  8351. }
  8352. };
  8353. var loadFromIndexedDB = function () {
  8354. // TODO: database needs to support aborting and should return a IFileRequest
  8355. if (aborted) {
  8356. return;
  8357. }
  8358. if (database) {
  8359. database.loadFileFromDB(url, function (data) {
  8360. if (!aborted) {
  8361. onSuccess(data);
  8362. }
  8363. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  8364. }, onProgress ? function (event) {
  8365. if (!aborted) {
  8366. onProgress(event);
  8367. }
  8368. } : undefined, noIndexedDB_1, useArrayBuffer);
  8369. }
  8370. };
  8371. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  8372. }
  8373. else {
  8374. requestFile();
  8375. }
  8376. return fileRequest;
  8377. };
  8378. /**
  8379. * Load a script (identified by an url). When the url returns, the
  8380. * content of this file is added into a new script element, attached to the DOM (body element)
  8381. */
  8382. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  8383. var head = document.getElementsByTagName('head')[0];
  8384. var script = document.createElement('script');
  8385. script.type = 'text/javascript';
  8386. script.src = scriptUrl;
  8387. script.onload = function () {
  8388. if (onSuccess) {
  8389. onSuccess();
  8390. }
  8391. };
  8392. script.onerror = function (e) {
  8393. if (onError) {
  8394. onError("Unable to load script", e);
  8395. }
  8396. };
  8397. head.appendChild(script);
  8398. };
  8399. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  8400. var reader = new FileReader();
  8401. var request = {
  8402. onCompleteObservable: new BABYLON.Observable(),
  8403. abort: function () { return reader.abort(); },
  8404. };
  8405. reader.onloadend = function (e) {
  8406. request.onCompleteObservable.notifyObservers(request);
  8407. };
  8408. reader.onload = function (e) {
  8409. //target doesn't have result from ts 1.3
  8410. callback(e.target['result']);
  8411. };
  8412. reader.onprogress = progressCallback;
  8413. reader.readAsDataURL(fileToLoad);
  8414. return request;
  8415. };
  8416. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  8417. var reader = new FileReader();
  8418. var request = {
  8419. onCompleteObservable: new BABYLON.Observable(),
  8420. abort: function () { return reader.abort(); },
  8421. };
  8422. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  8423. reader.onerror = function (e) {
  8424. Tools.Log("Error while reading file: " + fileToLoad.name);
  8425. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  8426. };
  8427. reader.onload = function (e) {
  8428. //target doesn't have result from ts 1.3
  8429. callback(e.target['result']);
  8430. };
  8431. if (progressCallBack) {
  8432. reader.onprogress = progressCallBack;
  8433. }
  8434. if (!useArrayBuffer) {
  8435. // Asynchronous read
  8436. reader.readAsText(fileToLoad);
  8437. }
  8438. else {
  8439. reader.readAsArrayBuffer(fileToLoad);
  8440. }
  8441. return request;
  8442. };
  8443. //returns a downloadable url to a file content.
  8444. Tools.FileAsURL = function (content) {
  8445. var fileBlob = new Blob([content]);
  8446. var url = window.URL || window.webkitURL;
  8447. var link = url.createObjectURL(fileBlob);
  8448. return link;
  8449. };
  8450. // Misc.
  8451. Tools.Format = function (value, decimals) {
  8452. if (decimals === void 0) { decimals = 2; }
  8453. return value.toFixed(decimals);
  8454. };
  8455. Tools.CheckExtends = function (v, min, max) {
  8456. if (v.x < min.x)
  8457. min.x = v.x;
  8458. if (v.y < min.y)
  8459. min.y = v.y;
  8460. if (v.z < min.z)
  8461. min.z = v.z;
  8462. if (v.x > max.x)
  8463. max.x = v.x;
  8464. if (v.y > max.y)
  8465. max.y = v.y;
  8466. if (v.z > max.z)
  8467. max.z = v.z;
  8468. };
  8469. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  8470. for (var prop in source) {
  8471. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  8472. continue;
  8473. }
  8474. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  8475. continue;
  8476. }
  8477. var sourceValue = source[prop];
  8478. var typeOfSourceValue = typeof sourceValue;
  8479. if (typeOfSourceValue === "function") {
  8480. continue;
  8481. }
  8482. if (typeOfSourceValue === "object") {
  8483. if (sourceValue instanceof Array) {
  8484. destination[prop] = [];
  8485. if (sourceValue.length > 0) {
  8486. if (typeof sourceValue[0] == "object") {
  8487. for (var index = 0; index < sourceValue.length; index++) {
  8488. var clonedValue = cloneValue(sourceValue[index], destination);
  8489. if (destination[prop].indexOf(clonedValue) === -1) {
  8490. destination[prop].push(clonedValue);
  8491. }
  8492. }
  8493. }
  8494. else {
  8495. destination[prop] = sourceValue.slice(0);
  8496. }
  8497. }
  8498. }
  8499. else {
  8500. destination[prop] = cloneValue(sourceValue, destination);
  8501. }
  8502. }
  8503. else {
  8504. destination[prop] = sourceValue;
  8505. }
  8506. }
  8507. };
  8508. Tools.IsEmpty = function (obj) {
  8509. for (var i in obj) {
  8510. if (obj.hasOwnProperty(i)) {
  8511. return false;
  8512. }
  8513. }
  8514. return true;
  8515. };
  8516. Tools.RegisterTopRootEvents = function (events) {
  8517. for (var index = 0; index < events.length; index++) {
  8518. var event = events[index];
  8519. window.addEventListener(event.name, event.handler, false);
  8520. try {
  8521. if (window.parent) {
  8522. window.parent.addEventListener(event.name, event.handler, false);
  8523. }
  8524. }
  8525. catch (e) {
  8526. // Silently fails...
  8527. }
  8528. }
  8529. };
  8530. Tools.UnregisterTopRootEvents = function (events) {
  8531. for (var index = 0; index < events.length; index++) {
  8532. var event = events[index];
  8533. window.removeEventListener(event.name, event.handler);
  8534. try {
  8535. if (window.parent) {
  8536. window.parent.removeEventListener(event.name, event.handler);
  8537. }
  8538. }
  8539. catch (e) {
  8540. // Silently fails...
  8541. }
  8542. }
  8543. };
  8544. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  8545. if (mimeType === void 0) { mimeType = "image/png"; }
  8546. // Read the contents of the framebuffer
  8547. var numberOfChannelsByLine = width * 4;
  8548. var halfHeight = height / 2;
  8549. //Reading datas from WebGL
  8550. var data = engine.readPixels(0, 0, width, height);
  8551. //To flip image on Y axis.
  8552. for (var i = 0; i < halfHeight; i++) {
  8553. for (var j = 0; j < numberOfChannelsByLine; j++) {
  8554. var currentCell = j + i * numberOfChannelsByLine;
  8555. var targetLine = height - i - 1;
  8556. var targetCell = j + targetLine * numberOfChannelsByLine;
  8557. var temp = data[currentCell];
  8558. data[currentCell] = data[targetCell];
  8559. data[targetCell] = temp;
  8560. }
  8561. }
  8562. // Create a 2D canvas to store the result
  8563. if (!screenshotCanvas) {
  8564. screenshotCanvas = document.createElement('canvas');
  8565. }
  8566. screenshotCanvas.width = width;
  8567. screenshotCanvas.height = height;
  8568. var context = screenshotCanvas.getContext('2d');
  8569. if (context) {
  8570. // Copy the pixels to a 2D canvas
  8571. var imageData = context.createImageData(width, height);
  8572. var castData = (imageData.data);
  8573. castData.set(data);
  8574. context.putImageData(imageData, 0, 0);
  8575. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  8576. }
  8577. };
  8578. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  8579. if (mimeType === void 0) { mimeType = "image/png"; }
  8580. var base64Image = screenshotCanvas.toDataURL(mimeType);
  8581. if (successCallback) {
  8582. successCallback(base64Image);
  8583. }
  8584. else {
  8585. // We need HTMLCanvasElement.toBlob for HD screenshots
  8586. if (!screenshotCanvas.toBlob) {
  8587. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  8588. screenshotCanvas.toBlob = function (callback, type, quality) {
  8589. var _this = this;
  8590. setTimeout(function () {
  8591. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  8592. for (var i = 0; i < len; i++) {
  8593. arr[i] = binStr.charCodeAt(i);
  8594. }
  8595. callback(new Blob([arr], { type: type || 'image/png' }));
  8596. });
  8597. };
  8598. }
  8599. screenshotCanvas.toBlob(function (blob) {
  8600. var url = URL.createObjectURL(blob);
  8601. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  8602. if (("download" in document.createElement("a"))) {
  8603. var a = window.document.createElement("a");
  8604. a.href = url;
  8605. if (fileName) {
  8606. a.setAttribute("download", fileName);
  8607. }
  8608. else {
  8609. var date = new Date();
  8610. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  8611. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  8612. }
  8613. window.document.body.appendChild(a);
  8614. a.addEventListener("click", function () {
  8615. if (a.parentElement) {
  8616. a.parentElement.removeChild(a);
  8617. }
  8618. });
  8619. a.click();
  8620. }
  8621. else {
  8622. var newWindow = window.open("");
  8623. if (!newWindow)
  8624. return;
  8625. var img = newWindow.document.createElement("img");
  8626. img.onload = function () {
  8627. // no longer need to read the blob so it's revoked
  8628. URL.revokeObjectURL(url);
  8629. };
  8630. img.src = url;
  8631. newWindow.document.body.appendChild(img);
  8632. }
  8633. });
  8634. }
  8635. };
  8636. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  8637. if (mimeType === void 0) { mimeType = "image/png"; }
  8638. var width;
  8639. var height;
  8640. // If a precision value is specified
  8641. if (size.precision) {
  8642. width = Math.round(engine.getRenderWidth() * size.precision);
  8643. height = Math.round(width / engine.getAspectRatio(camera));
  8644. }
  8645. else if (size.width && size.height) {
  8646. width = size.width;
  8647. height = size.height;
  8648. }
  8649. else if (size.width && !size.height) {
  8650. width = size.width;
  8651. height = Math.round(width / engine.getAspectRatio(camera));
  8652. }
  8653. else if (size.height && !size.width) {
  8654. height = size.height;
  8655. width = Math.round(height * engine.getAspectRatio(camera));
  8656. }
  8657. else if (!isNaN(size)) {
  8658. height = size;
  8659. width = size;
  8660. }
  8661. else {
  8662. Tools.Error("Invalid 'size' parameter !");
  8663. return;
  8664. }
  8665. if (!screenshotCanvas) {
  8666. screenshotCanvas = document.createElement('canvas');
  8667. }
  8668. screenshotCanvas.width = width;
  8669. screenshotCanvas.height = height;
  8670. var renderContext = screenshotCanvas.getContext("2d");
  8671. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  8672. var newWidth = width;
  8673. var newHeight = newWidth / ratio;
  8674. if (newHeight > height) {
  8675. newHeight = height;
  8676. newWidth = newHeight * ratio;
  8677. }
  8678. var offsetX = Math.max(0, width - newWidth) / 2;
  8679. var offsetY = Math.max(0, height - newHeight) / 2;
  8680. var renderingCanvas = engine.getRenderingCanvas();
  8681. if (renderContext && renderingCanvas) {
  8682. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  8683. }
  8684. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  8685. };
  8686. /**
  8687. * Generates an image screenshot from the specified camera.
  8688. *
  8689. * @param engine The engine to use for rendering
  8690. * @param camera The camera to use for rendering
  8691. * @param size This parameter can be set to a single number or to an object with the
  8692. * following (optional) properties: precision, width, height. If a single number is passed,
  8693. * it will be used for both width and height. If an object is passed, the screenshot size
  8694. * will be derived from the parameters. The precision property is a multiplier allowing
  8695. * rendering at a higher or lower resolution.
  8696. * @param successCallback The callback receives a single parameter which contains the
  8697. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  8698. * src parameter of an <img> to display it.
  8699. * @param mimeType The MIME type of the screenshot image (default: image/png).
  8700. * Check your browser for supported MIME types.
  8701. * @param samples Texture samples (default: 1)
  8702. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  8703. * @param fileName A name for for the downloaded file.
  8704. * @constructor
  8705. */
  8706. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  8707. if (mimeType === void 0) { mimeType = "image/png"; }
  8708. if (samples === void 0) { samples = 1; }
  8709. if (antialiasing === void 0) { antialiasing = false; }
  8710. var width;
  8711. var height;
  8712. //If a precision value is specified
  8713. if (size.precision) {
  8714. width = Math.round(engine.getRenderWidth() * size.precision);
  8715. height = Math.round(width / engine.getAspectRatio(camera));
  8716. size = { width: width, height: height };
  8717. }
  8718. else if (size.width && size.height) {
  8719. width = size.width;
  8720. height = size.height;
  8721. }
  8722. else if (size.width && !size.height) {
  8723. width = size.width;
  8724. height = Math.round(width / engine.getAspectRatio(camera));
  8725. size = { width: width, height: height };
  8726. }
  8727. else if (size.height && !size.width) {
  8728. height = size.height;
  8729. width = Math.round(height * engine.getAspectRatio(camera));
  8730. size = { width: width, height: height };
  8731. }
  8732. else if (!isNaN(size)) {
  8733. height = size;
  8734. width = size;
  8735. }
  8736. else {
  8737. Tools.Error("Invalid 'size' parameter !");
  8738. return;
  8739. }
  8740. var scene = camera.getScene();
  8741. var previousCamera = null;
  8742. if (scene.activeCamera !== camera) {
  8743. previousCamera = scene.activeCamera;
  8744. scene.activeCamera = camera;
  8745. }
  8746. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  8747. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8748. texture.renderList = null;
  8749. texture.samples = samples;
  8750. if (antialiasing) {
  8751. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  8752. }
  8753. texture.onAfterRenderObservable.add(function () {
  8754. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  8755. });
  8756. scene.incrementRenderId();
  8757. scene.resetCachedMaterial();
  8758. texture.render(true);
  8759. texture.dispose();
  8760. if (previousCamera) {
  8761. scene.activeCamera = previousCamera;
  8762. }
  8763. camera.getProjectionMatrix(true); // Force cache refresh;
  8764. };
  8765. // XHR response validator for local file scenario
  8766. Tools.ValidateXHRData = function (xhr, dataType) {
  8767. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  8768. if (dataType === void 0) { dataType = 7; }
  8769. try {
  8770. if (dataType & 1) {
  8771. if (xhr.responseText && xhr.responseText.length > 0) {
  8772. return true;
  8773. }
  8774. else if (dataType === 1) {
  8775. return false;
  8776. }
  8777. }
  8778. if (dataType & 2) {
  8779. // Check header width and height since there is no "TGA" magic number
  8780. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  8781. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  8782. return true;
  8783. }
  8784. else if (dataType === 2) {
  8785. return false;
  8786. }
  8787. }
  8788. if (dataType & 4) {
  8789. // Check for the "DDS" magic number
  8790. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  8791. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  8792. return true;
  8793. }
  8794. else {
  8795. return false;
  8796. }
  8797. }
  8798. }
  8799. catch (e) {
  8800. // Global protection
  8801. }
  8802. return false;
  8803. };
  8804. /**
  8805. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  8806. * Be aware Math.random() could cause collisions, but:
  8807. * "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"
  8808. */
  8809. Tools.RandomId = function () {
  8810. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  8811. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  8812. return v.toString(16);
  8813. });
  8814. };
  8815. /**
  8816. * Test if the given uri is a base64 string.
  8817. * @param uri The uri to test
  8818. * @return True if the uri is a base64 string or false otherwise.
  8819. */
  8820. Tools.IsBase64 = function (uri) {
  8821. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  8822. };
  8823. /**
  8824. * Decode the given base64 uri.
  8825. * @param uri The uri to decode
  8826. * @return The decoded base64 data.
  8827. */
  8828. Tools.DecodeBase64 = function (uri) {
  8829. var decodedString = atob(uri.split(",")[1]);
  8830. var bufferLength = decodedString.length;
  8831. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  8832. for (var i = 0; i < bufferLength; i++) {
  8833. bufferView[i] = decodedString.charCodeAt(i);
  8834. }
  8835. return bufferView.buffer;
  8836. };
  8837. Object.defineProperty(Tools, "NoneLogLevel", {
  8838. get: function () {
  8839. return Tools._NoneLogLevel;
  8840. },
  8841. enumerable: true,
  8842. configurable: true
  8843. });
  8844. Object.defineProperty(Tools, "MessageLogLevel", {
  8845. get: function () {
  8846. return Tools._MessageLogLevel;
  8847. },
  8848. enumerable: true,
  8849. configurable: true
  8850. });
  8851. Object.defineProperty(Tools, "WarningLogLevel", {
  8852. get: function () {
  8853. return Tools._WarningLogLevel;
  8854. },
  8855. enumerable: true,
  8856. configurable: true
  8857. });
  8858. Object.defineProperty(Tools, "ErrorLogLevel", {
  8859. get: function () {
  8860. return Tools._ErrorLogLevel;
  8861. },
  8862. enumerable: true,
  8863. configurable: true
  8864. });
  8865. Object.defineProperty(Tools, "AllLogLevel", {
  8866. get: function () {
  8867. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  8868. },
  8869. enumerable: true,
  8870. configurable: true
  8871. });
  8872. Tools._AddLogEntry = function (entry) {
  8873. Tools._LogCache = entry + Tools._LogCache;
  8874. if (Tools.OnNewCacheEntry) {
  8875. Tools.OnNewCacheEntry(entry);
  8876. }
  8877. };
  8878. Tools._FormatMessage = function (message) {
  8879. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  8880. var date = new Date();
  8881. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  8882. };
  8883. Tools._LogDisabled = function (message) {
  8884. // nothing to do
  8885. };
  8886. Tools._LogEnabled = function (message) {
  8887. var formattedMessage = Tools._FormatMessage(message);
  8888. console.log("BJS - " + formattedMessage);
  8889. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  8890. Tools._AddLogEntry(entry);
  8891. };
  8892. Tools._WarnDisabled = function (message) {
  8893. // nothing to do
  8894. };
  8895. Tools._WarnEnabled = function (message) {
  8896. var formattedMessage = Tools._FormatMessage(message);
  8897. console.warn("BJS - " + formattedMessage);
  8898. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  8899. Tools._AddLogEntry(entry);
  8900. };
  8901. Tools._ErrorDisabled = function (message) {
  8902. // nothing to do
  8903. };
  8904. Tools._ErrorEnabled = function (message) {
  8905. Tools.errorsCount++;
  8906. var formattedMessage = Tools._FormatMessage(message);
  8907. console.error("BJS - " + formattedMessage);
  8908. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  8909. Tools._AddLogEntry(entry);
  8910. };
  8911. Object.defineProperty(Tools, "LogCache", {
  8912. get: function () {
  8913. return Tools._LogCache;
  8914. },
  8915. enumerable: true,
  8916. configurable: true
  8917. });
  8918. Tools.ClearLogCache = function () {
  8919. Tools._LogCache = "";
  8920. Tools.errorsCount = 0;
  8921. };
  8922. Object.defineProperty(Tools, "LogLevels", {
  8923. set: function (level) {
  8924. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  8925. Tools.Log = Tools._LogEnabled;
  8926. }
  8927. else {
  8928. Tools.Log = Tools._LogDisabled;
  8929. }
  8930. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  8931. Tools.Warn = Tools._WarnEnabled;
  8932. }
  8933. else {
  8934. Tools.Warn = Tools._WarnDisabled;
  8935. }
  8936. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  8937. Tools.Error = Tools._ErrorEnabled;
  8938. }
  8939. else {
  8940. Tools.Error = Tools._ErrorDisabled;
  8941. }
  8942. },
  8943. enumerable: true,
  8944. configurable: true
  8945. });
  8946. Tools.IsWindowObjectExist = function () {
  8947. return (typeof window) !== "undefined";
  8948. };
  8949. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  8950. get: function () {
  8951. return Tools._PerformanceNoneLogLevel;
  8952. },
  8953. enumerable: true,
  8954. configurable: true
  8955. });
  8956. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  8957. get: function () {
  8958. return Tools._PerformanceUserMarkLogLevel;
  8959. },
  8960. enumerable: true,
  8961. configurable: true
  8962. });
  8963. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  8964. get: function () {
  8965. return Tools._PerformanceConsoleLogLevel;
  8966. },
  8967. enumerable: true,
  8968. configurable: true
  8969. });
  8970. Object.defineProperty(Tools, "PerformanceLogLevel", {
  8971. set: function (level) {
  8972. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  8973. Tools.StartPerformanceCounter = Tools._StartUserMark;
  8974. Tools.EndPerformanceCounter = Tools._EndUserMark;
  8975. return;
  8976. }
  8977. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  8978. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  8979. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  8980. return;
  8981. }
  8982. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  8983. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  8984. },
  8985. enumerable: true,
  8986. configurable: true
  8987. });
  8988. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  8989. };
  8990. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  8991. };
  8992. Tools._StartUserMark = function (counterName, condition) {
  8993. if (condition === void 0) { condition = true; }
  8994. if (!Tools._performance) {
  8995. if (!Tools.IsWindowObjectExist()) {
  8996. return;
  8997. }
  8998. Tools._performance = window.performance;
  8999. }
  9000. if (!condition || !Tools._performance.mark) {
  9001. return;
  9002. }
  9003. Tools._performance.mark(counterName + "-Begin");
  9004. };
  9005. Tools._EndUserMark = function (counterName, condition) {
  9006. if (condition === void 0) { condition = true; }
  9007. if (!condition || !Tools._performance.mark) {
  9008. return;
  9009. }
  9010. Tools._performance.mark(counterName + "-End");
  9011. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  9012. };
  9013. Tools._StartPerformanceConsole = function (counterName, condition) {
  9014. if (condition === void 0) { condition = true; }
  9015. if (!condition) {
  9016. return;
  9017. }
  9018. Tools._StartUserMark(counterName, condition);
  9019. if (console.time) {
  9020. console.time(counterName);
  9021. }
  9022. };
  9023. Tools._EndPerformanceConsole = function (counterName, condition) {
  9024. if (condition === void 0) { condition = true; }
  9025. if (!condition) {
  9026. return;
  9027. }
  9028. Tools._EndUserMark(counterName, condition);
  9029. if (console.time) {
  9030. console.timeEnd(counterName);
  9031. }
  9032. };
  9033. Object.defineProperty(Tools, "Now", {
  9034. get: function () {
  9035. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  9036. return window.performance.now();
  9037. }
  9038. return new Date().getTime();
  9039. },
  9040. enumerable: true,
  9041. configurable: true
  9042. });
  9043. /**
  9044. * This method will return the name of the class used to create the instance of the given object.
  9045. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  9046. * @param object the object to get the class name from
  9047. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  9048. */
  9049. Tools.GetClassName = function (object, isType) {
  9050. if (isType === void 0) { isType = false; }
  9051. var name = null;
  9052. if (!isType && object.getClassName) {
  9053. name = object.getClassName();
  9054. }
  9055. else {
  9056. if (object instanceof Object) {
  9057. var classObj = isType ? object : Object.getPrototypeOf(object);
  9058. name = classObj.constructor["__bjsclassName__"];
  9059. }
  9060. if (!name) {
  9061. name = typeof object;
  9062. }
  9063. }
  9064. return name;
  9065. };
  9066. Tools.First = function (array, predicate) {
  9067. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  9068. var el = array_1[_i];
  9069. if (predicate(el)) {
  9070. return el;
  9071. }
  9072. }
  9073. return null;
  9074. };
  9075. /**
  9076. * This method will return the name of the full name of the class, including its owning module (if any).
  9077. * 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).
  9078. * @param object the object to get the class name from
  9079. * @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.
  9080. */
  9081. Tools.getFullClassName = function (object, isType) {
  9082. if (isType === void 0) { isType = false; }
  9083. var className = null;
  9084. var moduleName = null;
  9085. if (!isType && object.getClassName) {
  9086. className = object.getClassName();
  9087. }
  9088. else {
  9089. if (object instanceof Object) {
  9090. var classObj = isType ? object : Object.getPrototypeOf(object);
  9091. className = classObj.constructor["__bjsclassName__"];
  9092. moduleName = classObj.constructor["__bjsmoduleName__"];
  9093. }
  9094. if (!className) {
  9095. className = typeof object;
  9096. }
  9097. }
  9098. if (!className) {
  9099. return null;
  9100. }
  9101. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  9102. };
  9103. /**
  9104. * 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.
  9105. * @param array
  9106. */
  9107. Tools.arrayOrStringFeeder = function (array) {
  9108. return function (index) {
  9109. if (index >= array.length) {
  9110. return null;
  9111. }
  9112. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  9113. if (val && val.getHashCode) {
  9114. val = val.getHashCode();
  9115. }
  9116. if (typeof val === "string") {
  9117. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  9118. }
  9119. return val;
  9120. };
  9121. };
  9122. /**
  9123. * Compute the hashCode of a stream of number
  9124. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  9125. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  9126. * @return the hash code computed
  9127. */
  9128. Tools.hashCodeFromStream = function (feeder) {
  9129. // Based from here: http://stackoverflow.com/a/7616484/802124
  9130. var hash = 0;
  9131. var index = 0;
  9132. var chr = feeder(index++);
  9133. while (chr != null) {
  9134. hash = ((hash << 5) - hash) + chr;
  9135. hash |= 0; // Convert to 32bit integer
  9136. chr = feeder(index++);
  9137. }
  9138. return hash;
  9139. };
  9140. /**
  9141. * Returns a promise that resolves after the given amount of time.
  9142. * @param delay Number of milliseconds to delay
  9143. * @returns Promise that resolves after the given amount of time
  9144. */
  9145. Tools.DelayAsync = function (delay) {
  9146. return new Promise(function (resolve) {
  9147. setTimeout(function () {
  9148. resolve();
  9149. }, delay);
  9150. });
  9151. };
  9152. Tools.BaseUrl = "";
  9153. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  9154. /**
  9155. * Default behaviour for cors in the application.
  9156. * It can be a string if the expected behavior is identical in the entire app.
  9157. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  9158. */
  9159. Tools.CorsBehavior = "anonymous";
  9160. Tools.UseFallbackTexture = true;
  9161. /**
  9162. * Use this object to register external classes like custom textures or material
  9163. * to allow the laoders to instantiate them
  9164. */
  9165. Tools.RegisteredExternalClasses = {};
  9166. // Used in case of a texture loading problem
  9167. 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";
  9168. Tools.PreprocessUrl = function (url) {
  9169. return url;
  9170. };
  9171. // Logs
  9172. Tools._NoneLogLevel = 0;
  9173. Tools._MessageLogLevel = 1;
  9174. Tools._WarningLogLevel = 2;
  9175. Tools._ErrorLogLevel = 4;
  9176. Tools._LogCache = "";
  9177. Tools.errorsCount = 0;
  9178. Tools.Log = Tools._LogEnabled;
  9179. Tools.Warn = Tools._WarnEnabled;
  9180. Tools.Error = Tools._ErrorEnabled;
  9181. // Performances
  9182. Tools._PerformanceNoneLogLevel = 0;
  9183. Tools._PerformanceUserMarkLogLevel = 1;
  9184. Tools._PerformanceConsoleLogLevel = 2;
  9185. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9186. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9187. return Tools;
  9188. }());
  9189. BABYLON.Tools = Tools;
  9190. /**
  9191. * This class is used to track a performance counter which is number based.
  9192. * The user has access to many properties which give statistics of different nature
  9193. *
  9194. * The implementer can track two kinds of Performance Counter: time and count
  9195. * 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.
  9196. * 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.
  9197. */
  9198. var PerfCounter = /** @class */ (function () {
  9199. function PerfCounter() {
  9200. this._startMonitoringTime = 0;
  9201. this._min = 0;
  9202. this._max = 0;
  9203. this._average = 0;
  9204. this._lastSecAverage = 0;
  9205. this._current = 0;
  9206. this._totalValueCount = 0;
  9207. this._totalAccumulated = 0;
  9208. this._lastSecAccumulated = 0;
  9209. this._lastSecTime = 0;
  9210. this._lastSecValueCount = 0;
  9211. }
  9212. Object.defineProperty(PerfCounter.prototype, "min", {
  9213. /**
  9214. * Returns the smallest value ever
  9215. */
  9216. get: function () {
  9217. return this._min;
  9218. },
  9219. enumerable: true,
  9220. configurable: true
  9221. });
  9222. Object.defineProperty(PerfCounter.prototype, "max", {
  9223. /**
  9224. * Returns the biggest value ever
  9225. */
  9226. get: function () {
  9227. return this._max;
  9228. },
  9229. enumerable: true,
  9230. configurable: true
  9231. });
  9232. Object.defineProperty(PerfCounter.prototype, "average", {
  9233. /**
  9234. * Returns the average value since the performance counter is running
  9235. */
  9236. get: function () {
  9237. return this._average;
  9238. },
  9239. enumerable: true,
  9240. configurable: true
  9241. });
  9242. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  9243. /**
  9244. * Returns the average value of the last second the counter was monitored
  9245. */
  9246. get: function () {
  9247. return this._lastSecAverage;
  9248. },
  9249. enumerable: true,
  9250. configurable: true
  9251. });
  9252. Object.defineProperty(PerfCounter.prototype, "current", {
  9253. /**
  9254. * Returns the current value
  9255. */
  9256. get: function () {
  9257. return this._current;
  9258. },
  9259. enumerable: true,
  9260. configurable: true
  9261. });
  9262. Object.defineProperty(PerfCounter.prototype, "total", {
  9263. get: function () {
  9264. return this._totalAccumulated;
  9265. },
  9266. enumerable: true,
  9267. configurable: true
  9268. });
  9269. Object.defineProperty(PerfCounter.prototype, "count", {
  9270. get: function () {
  9271. return this._totalValueCount;
  9272. },
  9273. enumerable: true,
  9274. configurable: true
  9275. });
  9276. /**
  9277. * Call this method to start monitoring a new frame.
  9278. * 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.
  9279. */
  9280. PerfCounter.prototype.fetchNewFrame = function () {
  9281. this._totalValueCount++;
  9282. this._current = 0;
  9283. this._lastSecValueCount++;
  9284. };
  9285. /**
  9286. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  9287. * @param newCount the count value to add to the monitored count
  9288. * @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.
  9289. */
  9290. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  9291. if (!PerfCounter.Enabled) {
  9292. return;
  9293. }
  9294. this._current += newCount;
  9295. if (fetchResult) {
  9296. this._fetchResult();
  9297. }
  9298. };
  9299. /**
  9300. * Start monitoring this performance counter
  9301. */
  9302. PerfCounter.prototype.beginMonitoring = function () {
  9303. if (!PerfCounter.Enabled) {
  9304. return;
  9305. }
  9306. this._startMonitoringTime = Tools.Now;
  9307. };
  9308. /**
  9309. * Compute the time lapsed since the previous beginMonitoring() call.
  9310. * @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
  9311. */
  9312. PerfCounter.prototype.endMonitoring = function (newFrame) {
  9313. if (newFrame === void 0) { newFrame = true; }
  9314. if (!PerfCounter.Enabled) {
  9315. return;
  9316. }
  9317. if (newFrame) {
  9318. this.fetchNewFrame();
  9319. }
  9320. var currentTime = Tools.Now;
  9321. this._current = currentTime - this._startMonitoringTime;
  9322. if (newFrame) {
  9323. this._fetchResult();
  9324. }
  9325. };
  9326. PerfCounter.prototype._fetchResult = function () {
  9327. this._totalAccumulated += this._current;
  9328. this._lastSecAccumulated += this._current;
  9329. // Min/Max update
  9330. this._min = Math.min(this._min, this._current);
  9331. this._max = Math.max(this._max, this._current);
  9332. this._average = this._totalAccumulated / this._totalValueCount;
  9333. // Reset last sec?
  9334. var now = Tools.Now;
  9335. if ((now - this._lastSecTime) > 1000) {
  9336. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  9337. this._lastSecTime = now;
  9338. this._lastSecAccumulated = 0;
  9339. this._lastSecValueCount = 0;
  9340. }
  9341. };
  9342. PerfCounter.Enabled = true;
  9343. return PerfCounter;
  9344. }());
  9345. BABYLON.PerfCounter = PerfCounter;
  9346. /**
  9347. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  9348. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  9349. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  9350. * @param name The name of the class, case should be preserved
  9351. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  9352. */
  9353. function className(name, module) {
  9354. return function (target) {
  9355. target["__bjsclassName__"] = name;
  9356. target["__bjsmoduleName__"] = (module != null) ? module : null;
  9357. };
  9358. }
  9359. BABYLON.className = className;
  9360. /**
  9361. * An implementation of a loop for asynchronous functions.
  9362. */
  9363. var AsyncLoop = /** @class */ (function () {
  9364. /**
  9365. * Constroctor.
  9366. * @param iterations the number of iterations.
  9367. * @param _fn the function to run each iteration
  9368. * @param _successCallback the callback that will be called upon succesful execution
  9369. * @param offset starting offset.
  9370. */
  9371. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  9372. if (offset === void 0) { offset = 0; }
  9373. this.iterations = iterations;
  9374. this._fn = _fn;
  9375. this._successCallback = _successCallback;
  9376. this.index = offset - 1;
  9377. this._done = false;
  9378. }
  9379. /**
  9380. * Execute the next iteration. Must be called after the last iteration was finished.
  9381. */
  9382. AsyncLoop.prototype.executeNext = function () {
  9383. if (!this._done) {
  9384. if (this.index + 1 < this.iterations) {
  9385. ++this.index;
  9386. this._fn(this);
  9387. }
  9388. else {
  9389. this.breakLoop();
  9390. }
  9391. }
  9392. };
  9393. /**
  9394. * Break the loop and run the success callback.
  9395. */
  9396. AsyncLoop.prototype.breakLoop = function () {
  9397. this._done = true;
  9398. this._successCallback();
  9399. };
  9400. /**
  9401. * Helper function
  9402. */
  9403. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  9404. if (offset === void 0) { offset = 0; }
  9405. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  9406. loop.executeNext();
  9407. return loop;
  9408. };
  9409. /**
  9410. * A for-loop that will run a given number of iterations synchronous and the rest async.
  9411. * @param iterations total number of iterations
  9412. * @param syncedIterations number of synchronous iterations in each async iteration.
  9413. * @param fn the function to call each iteration.
  9414. * @param callback a success call back that will be called when iterating stops.
  9415. * @param breakFunction a break condition (optional)
  9416. * @param timeout timeout settings for the setTimeout function. default - 0.
  9417. * @constructor
  9418. */
  9419. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  9420. if (timeout === void 0) { timeout = 0; }
  9421. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  9422. if (breakFunction && breakFunction())
  9423. loop.breakLoop();
  9424. else {
  9425. setTimeout(function () {
  9426. for (var i = 0; i < syncedIterations; ++i) {
  9427. var iteration = (loop.index * syncedIterations) + i;
  9428. if (iteration >= iterations)
  9429. break;
  9430. fn(iteration);
  9431. if (breakFunction && breakFunction()) {
  9432. loop.breakLoop();
  9433. break;
  9434. }
  9435. }
  9436. loop.executeNext();
  9437. }, timeout);
  9438. }
  9439. }, callback);
  9440. };
  9441. return AsyncLoop;
  9442. }());
  9443. BABYLON.AsyncLoop = AsyncLoop;
  9444. })(BABYLON || (BABYLON = {}));
  9445. //# sourceMappingURL=babylon.tools.js.map
  9446. var BABYLON;
  9447. (function (BABYLON) {
  9448. var PromiseStates;
  9449. (function (PromiseStates) {
  9450. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  9451. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  9452. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  9453. })(PromiseStates || (PromiseStates = {}));
  9454. var FulFillmentAgregator = /** @class */ (function () {
  9455. function FulFillmentAgregator() {
  9456. this.count = 0;
  9457. this.target = 0;
  9458. this.results = [];
  9459. }
  9460. return FulFillmentAgregator;
  9461. }());
  9462. var InternalPromise = /** @class */ (function () {
  9463. function InternalPromise(resolver) {
  9464. var _this = this;
  9465. this._state = PromiseStates.Pending;
  9466. this._children = new Array();
  9467. this._rejectWasConsumed = false;
  9468. if (!resolver) {
  9469. return;
  9470. }
  9471. try {
  9472. resolver(function (value) {
  9473. _this._resolve(value);
  9474. }, function (reason) {
  9475. _this._reject(reason);
  9476. });
  9477. }
  9478. catch (e) {
  9479. this._reject(e);
  9480. }
  9481. }
  9482. InternalPromise.prototype.catch = function (onRejected) {
  9483. return this.then(undefined, onRejected);
  9484. };
  9485. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  9486. var _this = this;
  9487. var newPromise = new InternalPromise();
  9488. newPromise._onFulfilled = onFulfilled;
  9489. newPromise._onRejected = onRejected;
  9490. // Composition
  9491. this._children.push(newPromise);
  9492. if (this._state !== PromiseStates.Pending) {
  9493. BABYLON.Tools.SetImmediate(function () {
  9494. if (_this._state === PromiseStates.Fulfilled || _this._rejectWasConsumed) {
  9495. var returnedValue = newPromise._resolve(_this._result);
  9496. if (returnedValue !== undefined && returnedValue !== null) {
  9497. if (returnedValue._state !== undefined) {
  9498. var returnedPromise = returnedValue;
  9499. newPromise._children.push(returnedPromise);
  9500. newPromise = returnedPromise;
  9501. }
  9502. else {
  9503. newPromise._result = returnedValue;
  9504. }
  9505. }
  9506. }
  9507. else {
  9508. newPromise._reject(_this._reason);
  9509. }
  9510. });
  9511. }
  9512. return newPromise;
  9513. };
  9514. InternalPromise.prototype._moveChildren = function (children) {
  9515. (_a = this._children).push.apply(_a, children.splice(0, children.length));
  9516. if (this._state === PromiseStates.Fulfilled) {
  9517. for (var _i = 0, _b = this._children; _i < _b.length; _i++) {
  9518. var child = _b[_i];
  9519. child._resolve(this._result);
  9520. }
  9521. }
  9522. else if (this._state === PromiseStates.Rejected) {
  9523. for (var _c = 0, _d = this._children; _c < _d.length; _c++) {
  9524. var child = _d[_c];
  9525. child._reject(this._reason);
  9526. }
  9527. }
  9528. var _a;
  9529. };
  9530. InternalPromise.prototype._resolve = function (value) {
  9531. try {
  9532. this._state = PromiseStates.Fulfilled;
  9533. this._result = value;
  9534. var returnedValue = null;
  9535. if (this._onFulfilled) {
  9536. returnedValue = this._onFulfilled(value);
  9537. }
  9538. if (returnedValue !== undefined && returnedValue !== null) {
  9539. if (returnedValue._state !== undefined) {
  9540. // Transmit children
  9541. var returnedPromise = returnedValue;
  9542. returnedPromise._moveChildren(this._children);
  9543. }
  9544. else {
  9545. value = returnedValue;
  9546. }
  9547. }
  9548. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  9549. var child = _a[_i];
  9550. child._resolve(value);
  9551. }
  9552. this._children.length = 0;
  9553. delete this._onFulfilled;
  9554. delete this._onRejected;
  9555. return returnedValue;
  9556. }
  9557. catch (e) {
  9558. this._reject(e, true);
  9559. }
  9560. return null;
  9561. };
  9562. InternalPromise.prototype._reject = function (reason, onLocalThrow) {
  9563. if (onLocalThrow === void 0) { onLocalThrow = false; }
  9564. this._state = PromiseStates.Rejected;
  9565. this._reason = reason;
  9566. if (this._onRejected && !onLocalThrow) {
  9567. try {
  9568. this._onRejected(reason);
  9569. this._rejectWasConsumed = true;
  9570. }
  9571. catch (e) {
  9572. reason = e;
  9573. }
  9574. }
  9575. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  9576. var child = _a[_i];
  9577. if (this._rejectWasConsumed) {
  9578. child._resolve(null);
  9579. }
  9580. else {
  9581. child._reject(reason);
  9582. }
  9583. }
  9584. this._children.length = 0;
  9585. delete this._onFulfilled;
  9586. delete this._onRejected;
  9587. };
  9588. InternalPromise.resolve = function (value) {
  9589. var newPromise = new InternalPromise();
  9590. newPromise._resolve(value);
  9591. return newPromise;
  9592. };
  9593. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  9594. promise.then(function (value) {
  9595. agregator.results[index] = value;
  9596. agregator.count++;
  9597. if (agregator.count === agregator.target) {
  9598. agregator.rootPromise._resolve(agregator.results);
  9599. }
  9600. return null;
  9601. }, function (reason) {
  9602. if (agregator.rootPromise._state !== PromiseStates.Rejected) {
  9603. agregator.rootPromise._reject(reason);
  9604. }
  9605. });
  9606. };
  9607. InternalPromise.all = function (promises) {
  9608. var newPromise = new InternalPromise();
  9609. var agregator = new FulFillmentAgregator();
  9610. agregator.target = promises.length;
  9611. agregator.rootPromise = newPromise;
  9612. if (promises.length) {
  9613. for (var index = 0; index < promises.length; index++) {
  9614. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  9615. }
  9616. }
  9617. else {
  9618. newPromise._resolve([]);
  9619. }
  9620. return newPromise;
  9621. };
  9622. InternalPromise.race = function (promises) {
  9623. var newPromise = new InternalPromise();
  9624. if (promises.length) {
  9625. for (var _i = 0, promises_1 = promises; _i < promises_1.length; _i++) {
  9626. var promise = promises_1[_i];
  9627. promise.then(function (value) {
  9628. if (newPromise) {
  9629. newPromise._resolve(value);
  9630. newPromise = null;
  9631. }
  9632. return null;
  9633. }, function (reason) {
  9634. if (newPromise) {
  9635. newPromise._reject(reason);
  9636. newPromise = null;
  9637. }
  9638. });
  9639. }
  9640. }
  9641. return newPromise;
  9642. };
  9643. return InternalPromise;
  9644. }());
  9645. /**
  9646. * Helper class that provides a small promise polyfill
  9647. */
  9648. var PromisePolyfill = /** @class */ (function () {
  9649. function PromisePolyfill() {
  9650. }
  9651. /**
  9652. * Static function used to check if the polyfill is required
  9653. * If this is the case then the function will inject the polyfill to window.Promise
  9654. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  9655. */
  9656. PromisePolyfill.Apply = function (force) {
  9657. if (force === void 0) { force = false; }
  9658. if (force || typeof Promise === 'undefined') {
  9659. var root = window;
  9660. root.Promise = InternalPromise;
  9661. }
  9662. };
  9663. return PromisePolyfill;
  9664. }());
  9665. BABYLON.PromisePolyfill = PromisePolyfill;
  9666. })(BABYLON || (BABYLON = {}));
  9667. //# sourceMappingURL=babylon.promise.js.map
  9668. /// <reference path="../../../dist/preview release/babylon.d.ts" />
  9669. var BABYLON;
  9670. (function (BABYLON) {
  9671. /**
  9672. * Helper class to push actions to a pool of workers.
  9673. */
  9674. var WorkerPool = /** @class */ (function () {
  9675. /**
  9676. * Constructor
  9677. * @param workers Array of workers to use for actions
  9678. */
  9679. function WorkerPool(workers) {
  9680. this._pendingActions = new Array();
  9681. this._workerInfos = workers.map(function (worker) { return ({
  9682. worker: worker,
  9683. active: false
  9684. }); });
  9685. }
  9686. /**
  9687. * Terminates all workers and clears any pending actions.
  9688. */
  9689. WorkerPool.prototype.dispose = function () {
  9690. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  9691. var workerInfo = _a[_i];
  9692. workerInfo.worker.terminate();
  9693. }
  9694. delete this._workerInfos;
  9695. delete this._pendingActions;
  9696. };
  9697. /**
  9698. * Pushes an action to the worker pool. If all the workers are active, the action will be
  9699. * pended until a worker has completed its action.
  9700. * @param action The action to perform. Call onComplete when the action is complete.
  9701. */
  9702. WorkerPool.prototype.push = function (action) {
  9703. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  9704. var workerInfo = _a[_i];
  9705. if (!workerInfo.active) {
  9706. this._execute(workerInfo, action);
  9707. return;
  9708. }
  9709. }
  9710. this._pendingActions.push(action);
  9711. };
  9712. WorkerPool.prototype._execute = function (workerInfo, action) {
  9713. var _this = this;
  9714. workerInfo.active = true;
  9715. action(workerInfo.worker, function () {
  9716. workerInfo.active = false;
  9717. var nextAction = _this._pendingActions.shift();
  9718. if (nextAction) {
  9719. _this._execute(workerInfo, nextAction);
  9720. }
  9721. });
  9722. };
  9723. return WorkerPool;
  9724. }());
  9725. BABYLON.WorkerPool = WorkerPool;
  9726. })(BABYLON || (BABYLON = {}));
  9727. //# sourceMappingURL=babylon.workerPool.js.map
  9728. var BABYLON;
  9729. (function (BABYLON) {
  9730. var _AlphaState = /** @class */ (function () {
  9731. /**
  9732. * Initializes the state.
  9733. */
  9734. function _AlphaState() {
  9735. this._isAlphaBlendDirty = false;
  9736. this._isBlendFunctionParametersDirty = false;
  9737. this._isBlendEquationParametersDirty = false;
  9738. this._isBlendConstantsDirty = false;
  9739. this._alphaBlend = false;
  9740. this._blendFunctionParameters = new Array(4);
  9741. this._blendEquationParameters = new Array(2);
  9742. this._blendConstants = new Array(4);
  9743. this.reset();
  9744. }
  9745. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  9746. get: function () {
  9747. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  9748. },
  9749. enumerable: true,
  9750. configurable: true
  9751. });
  9752. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  9753. get: function () {
  9754. return this._alphaBlend;
  9755. },
  9756. set: function (value) {
  9757. if (this._alphaBlend === value) {
  9758. return;
  9759. }
  9760. this._alphaBlend = value;
  9761. this._isAlphaBlendDirty = true;
  9762. },
  9763. enumerable: true,
  9764. configurable: true
  9765. });
  9766. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  9767. if (this._blendConstants[0] === r &&
  9768. this._blendConstants[1] === g &&
  9769. this._blendConstants[2] === b &&
  9770. this._blendConstants[3] === a) {
  9771. return;
  9772. }
  9773. this._blendConstants[0] = r;
  9774. this._blendConstants[1] = g;
  9775. this._blendConstants[2] = b;
  9776. this._blendConstants[3] = a;
  9777. this._isBlendConstantsDirty = true;
  9778. };
  9779. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  9780. if (this._blendFunctionParameters[0] === value0 &&
  9781. this._blendFunctionParameters[1] === value1 &&
  9782. this._blendFunctionParameters[2] === value2 &&
  9783. this._blendFunctionParameters[3] === value3) {
  9784. return;
  9785. }
  9786. this._blendFunctionParameters[0] = value0;
  9787. this._blendFunctionParameters[1] = value1;
  9788. this._blendFunctionParameters[2] = value2;
  9789. this._blendFunctionParameters[3] = value3;
  9790. this._isBlendFunctionParametersDirty = true;
  9791. };
  9792. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  9793. if (this._blendEquationParameters[0] === rgb &&
  9794. this._blendEquationParameters[1] === alpha) {
  9795. return;
  9796. }
  9797. this._blendEquationParameters[0] = rgb;
  9798. this._blendEquationParameters[1] = alpha;
  9799. this._isBlendEquationParametersDirty = true;
  9800. };
  9801. _AlphaState.prototype.reset = function () {
  9802. this._alphaBlend = false;
  9803. this._blendFunctionParameters[0] = null;
  9804. this._blendFunctionParameters[1] = null;
  9805. this._blendFunctionParameters[2] = null;
  9806. this._blendFunctionParameters[3] = null;
  9807. this._blendEquationParameters[0] = null;
  9808. this._blendEquationParameters[1] = null;
  9809. this._blendConstants[0] = null;
  9810. this._blendConstants[1] = null;
  9811. this._blendConstants[2] = null;
  9812. this._blendConstants[3] = null;
  9813. this._isAlphaBlendDirty = true;
  9814. this._isBlendFunctionParametersDirty = false;
  9815. this._isBlendEquationParametersDirty = false;
  9816. this._isBlendConstantsDirty = false;
  9817. };
  9818. _AlphaState.prototype.apply = function (gl) {
  9819. if (!this.isDirty) {
  9820. return;
  9821. }
  9822. // Alpha blend
  9823. if (this._isAlphaBlendDirty) {
  9824. if (this._alphaBlend) {
  9825. gl.enable(gl.BLEND);
  9826. }
  9827. else {
  9828. gl.disable(gl.BLEND);
  9829. }
  9830. this._isAlphaBlendDirty = false;
  9831. }
  9832. // Alpha function
  9833. if (this._isBlendFunctionParametersDirty) {
  9834. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  9835. this._isBlendFunctionParametersDirty = false;
  9836. }
  9837. // Alpha equation
  9838. if (this._isBlendEquationParametersDirty) {
  9839. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  9840. this._isBlendEquationParametersDirty = false;
  9841. }
  9842. // Constants
  9843. if (this._isBlendConstantsDirty) {
  9844. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  9845. this._isBlendConstantsDirty = false;
  9846. }
  9847. };
  9848. return _AlphaState;
  9849. }());
  9850. BABYLON._AlphaState = _AlphaState;
  9851. })(BABYLON || (BABYLON = {}));
  9852. //# sourceMappingURL=babylon.alphaCullingState.js.map
  9853. var BABYLON;
  9854. (function (BABYLON) {
  9855. var _DepthCullingState = /** @class */ (function () {
  9856. /**
  9857. * Initializes the state.
  9858. */
  9859. function _DepthCullingState() {
  9860. this._isDepthTestDirty = false;
  9861. this._isDepthMaskDirty = false;
  9862. this._isDepthFuncDirty = false;
  9863. this._isCullFaceDirty = false;
  9864. this._isCullDirty = false;
  9865. this._isZOffsetDirty = false;
  9866. this._isFrontFaceDirty = false;
  9867. this.reset();
  9868. }
  9869. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  9870. get: function () {
  9871. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  9872. },
  9873. enumerable: true,
  9874. configurable: true
  9875. });
  9876. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  9877. get: function () {
  9878. return this._zOffset;
  9879. },
  9880. set: function (value) {
  9881. if (this._zOffset === value) {
  9882. return;
  9883. }
  9884. this._zOffset = value;
  9885. this._isZOffsetDirty = true;
  9886. },
  9887. enumerable: true,
  9888. configurable: true
  9889. });
  9890. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  9891. get: function () {
  9892. return this._cullFace;
  9893. },
  9894. set: function (value) {
  9895. if (this._cullFace === value) {
  9896. return;
  9897. }
  9898. this._cullFace = value;
  9899. this._isCullFaceDirty = true;
  9900. },
  9901. enumerable: true,
  9902. configurable: true
  9903. });
  9904. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  9905. get: function () {
  9906. return this._cull;
  9907. },
  9908. set: function (value) {
  9909. if (this._cull === value) {
  9910. return;
  9911. }
  9912. this._cull = value;
  9913. this._isCullDirty = true;
  9914. },
  9915. enumerable: true,
  9916. configurable: true
  9917. });
  9918. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  9919. get: function () {
  9920. return this._depthFunc;
  9921. },
  9922. set: function (value) {
  9923. if (this._depthFunc === value) {
  9924. return;
  9925. }
  9926. this._depthFunc = value;
  9927. this._isDepthFuncDirty = true;
  9928. },
  9929. enumerable: true,
  9930. configurable: true
  9931. });
  9932. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  9933. get: function () {
  9934. return this._depthMask;
  9935. },
  9936. set: function (value) {
  9937. if (this._depthMask === value) {
  9938. return;
  9939. }
  9940. this._depthMask = value;
  9941. this._isDepthMaskDirty = true;
  9942. },
  9943. enumerable: true,
  9944. configurable: true
  9945. });
  9946. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  9947. get: function () {
  9948. return this._depthTest;
  9949. },
  9950. set: function (value) {
  9951. if (this._depthTest === value) {
  9952. return;
  9953. }
  9954. this._depthTest = value;
  9955. this._isDepthTestDirty = true;
  9956. },
  9957. enumerable: true,
  9958. configurable: true
  9959. });
  9960. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  9961. get: function () {
  9962. return this._frontFace;
  9963. },
  9964. set: function (value) {
  9965. if (this._frontFace === value) {
  9966. return;
  9967. }
  9968. this._frontFace = value;
  9969. this._isFrontFaceDirty = true;
  9970. },
  9971. enumerable: true,
  9972. configurable: true
  9973. });
  9974. _DepthCullingState.prototype.reset = function () {
  9975. this._depthMask = true;
  9976. this._depthTest = true;
  9977. this._depthFunc = null;
  9978. this._cullFace = null;
  9979. this._cull = null;
  9980. this._zOffset = 0;
  9981. this._frontFace = null;
  9982. this._isDepthTestDirty = true;
  9983. this._isDepthMaskDirty = true;
  9984. this._isDepthFuncDirty = false;
  9985. this._isCullFaceDirty = false;
  9986. this._isCullDirty = false;
  9987. this._isZOffsetDirty = false;
  9988. this._isFrontFaceDirty = false;
  9989. };
  9990. _DepthCullingState.prototype.apply = function (gl) {
  9991. if (!this.isDirty) {
  9992. return;
  9993. }
  9994. // Cull
  9995. if (this._isCullDirty) {
  9996. if (this.cull) {
  9997. gl.enable(gl.CULL_FACE);
  9998. }
  9999. else {
  10000. gl.disable(gl.CULL_FACE);
  10001. }
  10002. this._isCullDirty = false;
  10003. }
  10004. // Cull face
  10005. if (this._isCullFaceDirty) {
  10006. gl.cullFace(this.cullFace);
  10007. this._isCullFaceDirty = false;
  10008. }
  10009. // Depth mask
  10010. if (this._isDepthMaskDirty) {
  10011. gl.depthMask(this.depthMask);
  10012. this._isDepthMaskDirty = false;
  10013. }
  10014. // Depth test
  10015. if (this._isDepthTestDirty) {
  10016. if (this.depthTest) {
  10017. gl.enable(gl.DEPTH_TEST);
  10018. }
  10019. else {
  10020. gl.disable(gl.DEPTH_TEST);
  10021. }
  10022. this._isDepthTestDirty = false;
  10023. }
  10024. // Depth func
  10025. if (this._isDepthFuncDirty) {
  10026. gl.depthFunc(this.depthFunc);
  10027. this._isDepthFuncDirty = false;
  10028. }
  10029. // zOffset
  10030. if (this._isZOffsetDirty) {
  10031. if (this.zOffset) {
  10032. gl.enable(gl.POLYGON_OFFSET_FILL);
  10033. gl.polygonOffset(this.zOffset, 0);
  10034. }
  10035. else {
  10036. gl.disable(gl.POLYGON_OFFSET_FILL);
  10037. }
  10038. this._isZOffsetDirty = false;
  10039. }
  10040. // Front face
  10041. if (this._isFrontFaceDirty) {
  10042. gl.frontFace(this.frontFace);
  10043. this._isFrontFaceDirty = false;
  10044. }
  10045. };
  10046. return _DepthCullingState;
  10047. }());
  10048. BABYLON._DepthCullingState = _DepthCullingState;
  10049. })(BABYLON || (BABYLON = {}));
  10050. //# sourceMappingURL=babylon.depthCullingState.js.map
  10051. var BABYLON;
  10052. (function (BABYLON) {
  10053. var _StencilState = /** @class */ (function () {
  10054. function _StencilState() {
  10055. this._isStencilTestDirty = false;
  10056. this._isStencilMaskDirty = false;
  10057. this._isStencilFuncDirty = false;
  10058. this._isStencilOpDirty = false;
  10059. this.reset();
  10060. }
  10061. Object.defineProperty(_StencilState.prototype, "isDirty", {
  10062. get: function () {
  10063. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  10064. },
  10065. enumerable: true,
  10066. configurable: true
  10067. });
  10068. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  10069. get: function () {
  10070. return this._stencilFunc;
  10071. },
  10072. set: function (value) {
  10073. if (this._stencilFunc === value) {
  10074. return;
  10075. }
  10076. this._stencilFunc = value;
  10077. this._isStencilFuncDirty = true;
  10078. },
  10079. enumerable: true,
  10080. configurable: true
  10081. });
  10082. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  10083. get: function () {
  10084. return this._stencilFuncRef;
  10085. },
  10086. set: function (value) {
  10087. if (this._stencilFuncRef === value) {
  10088. return;
  10089. }
  10090. this._stencilFuncRef = value;
  10091. this._isStencilFuncDirty = true;
  10092. },
  10093. enumerable: true,
  10094. configurable: true
  10095. });
  10096. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  10097. get: function () {
  10098. return this._stencilFuncMask;
  10099. },
  10100. set: function (value) {
  10101. if (this._stencilFuncMask === value) {
  10102. return;
  10103. }
  10104. this._stencilFuncMask = value;
  10105. this._isStencilFuncDirty = true;
  10106. },
  10107. enumerable: true,
  10108. configurable: true
  10109. });
  10110. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  10111. get: function () {
  10112. return this._stencilOpStencilFail;
  10113. },
  10114. set: function (value) {
  10115. if (this._stencilOpStencilFail === value) {
  10116. return;
  10117. }
  10118. this._stencilOpStencilFail = value;
  10119. this._isStencilOpDirty = true;
  10120. },
  10121. enumerable: true,
  10122. configurable: true
  10123. });
  10124. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  10125. get: function () {
  10126. return this._stencilOpDepthFail;
  10127. },
  10128. set: function (value) {
  10129. if (this._stencilOpDepthFail === value) {
  10130. return;
  10131. }
  10132. this._stencilOpDepthFail = value;
  10133. this._isStencilOpDirty = true;
  10134. },
  10135. enumerable: true,
  10136. configurable: true
  10137. });
  10138. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  10139. get: function () {
  10140. return this._stencilOpStencilDepthPass;
  10141. },
  10142. set: function (value) {
  10143. if (this._stencilOpStencilDepthPass === value) {
  10144. return;
  10145. }
  10146. this._stencilOpStencilDepthPass = value;
  10147. this._isStencilOpDirty = true;
  10148. },
  10149. enumerable: true,
  10150. configurable: true
  10151. });
  10152. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  10153. get: function () {
  10154. return this._stencilMask;
  10155. },
  10156. set: function (value) {
  10157. if (this._stencilMask === value) {
  10158. return;
  10159. }
  10160. this._stencilMask = value;
  10161. this._isStencilMaskDirty = true;
  10162. },
  10163. enumerable: true,
  10164. configurable: true
  10165. });
  10166. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  10167. get: function () {
  10168. return this._stencilTest;
  10169. },
  10170. set: function (value) {
  10171. if (this._stencilTest === value) {
  10172. return;
  10173. }
  10174. this._stencilTest = value;
  10175. this._isStencilTestDirty = true;
  10176. },
  10177. enumerable: true,
  10178. configurable: true
  10179. });
  10180. _StencilState.prototype.reset = function () {
  10181. this._stencilTest = false;
  10182. this._stencilMask = 0xFF;
  10183. this._stencilFunc = BABYLON.Engine.ALWAYS;
  10184. this._stencilFuncRef = 1;
  10185. this._stencilFuncMask = 0xFF;
  10186. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  10187. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  10188. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  10189. this._isStencilTestDirty = true;
  10190. this._isStencilMaskDirty = true;
  10191. this._isStencilFuncDirty = true;
  10192. this._isStencilOpDirty = true;
  10193. };
  10194. _StencilState.prototype.apply = function (gl) {
  10195. if (!this.isDirty) {
  10196. return;
  10197. }
  10198. // Stencil test
  10199. if (this._isStencilTestDirty) {
  10200. if (this.stencilTest) {
  10201. gl.enable(gl.STENCIL_TEST);
  10202. }
  10203. else {
  10204. gl.disable(gl.STENCIL_TEST);
  10205. }
  10206. this._isStencilTestDirty = false;
  10207. }
  10208. // Stencil mask
  10209. if (this._isStencilMaskDirty) {
  10210. gl.stencilMask(this.stencilMask);
  10211. this._isStencilMaskDirty = false;
  10212. }
  10213. // Stencil func
  10214. if (this._isStencilFuncDirty) {
  10215. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  10216. this._isStencilFuncDirty = false;
  10217. }
  10218. // Stencil op
  10219. if (this._isStencilOpDirty) {
  10220. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  10221. this._isStencilOpDirty = false;
  10222. }
  10223. };
  10224. return _StencilState;
  10225. }());
  10226. BABYLON._StencilState = _StencilState;
  10227. })(BABYLON || (BABYLON = {}));
  10228. //# sourceMappingURL=babylon.stencilState.js.map
  10229. var __assign = (this && this.__assign) || Object.assign || function(t) {
  10230. for (var s, i = 1, n = arguments.length; i < n; i++) {
  10231. s = arguments[i];
  10232. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  10233. t[p] = s[p];
  10234. }
  10235. return t;
  10236. };
  10237. var BABYLON;
  10238. (function (BABYLON) {
  10239. var compileShader = function (gl, source, type, defines, shaderVersion) {
  10240. return compileRawShader(gl, shaderVersion + (defines ? defines + "\n" : "") + source, type);
  10241. };
  10242. var compileRawShader = function (gl, source, type) {
  10243. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  10244. gl.shaderSource(shader, source);
  10245. gl.compileShader(shader);
  10246. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  10247. var log = gl.getShaderInfoLog(shader);
  10248. if (log) {
  10249. throw new Error(log);
  10250. }
  10251. }
  10252. if (!shader) {
  10253. throw new Error("Something went wrong while compile the shader.");
  10254. }
  10255. return shader;
  10256. };
  10257. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  10258. var magFilter = gl.NEAREST;
  10259. var minFilter = gl.NEAREST;
  10260. switch (samplingMode) {
  10261. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  10262. magFilter = gl.LINEAR;
  10263. if (generateMipMaps) {
  10264. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  10265. }
  10266. else {
  10267. minFilter = gl.LINEAR;
  10268. }
  10269. break;
  10270. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  10271. magFilter = gl.LINEAR;
  10272. if (generateMipMaps) {
  10273. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  10274. }
  10275. else {
  10276. minFilter = gl.LINEAR;
  10277. }
  10278. break;
  10279. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  10280. magFilter = gl.NEAREST;
  10281. if (generateMipMaps) {
  10282. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  10283. }
  10284. else {
  10285. minFilter = gl.NEAREST;
  10286. }
  10287. break;
  10288. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  10289. magFilter = gl.NEAREST;
  10290. if (generateMipMaps) {
  10291. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  10292. }
  10293. else {
  10294. minFilter = gl.NEAREST;
  10295. }
  10296. break;
  10297. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  10298. magFilter = gl.NEAREST;
  10299. if (generateMipMaps) {
  10300. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  10301. }
  10302. else {
  10303. minFilter = gl.LINEAR;
  10304. }
  10305. break;
  10306. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  10307. magFilter = gl.NEAREST;
  10308. if (generateMipMaps) {
  10309. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  10310. }
  10311. else {
  10312. minFilter = gl.LINEAR;
  10313. }
  10314. break;
  10315. case BABYLON.Texture.NEAREST_LINEAR:
  10316. magFilter = gl.NEAREST;
  10317. minFilter = gl.LINEAR;
  10318. break;
  10319. case BABYLON.Texture.NEAREST_NEAREST:
  10320. magFilter = gl.NEAREST;
  10321. minFilter = gl.NEAREST;
  10322. break;
  10323. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  10324. magFilter = gl.LINEAR;
  10325. if (generateMipMaps) {
  10326. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  10327. }
  10328. else {
  10329. minFilter = gl.NEAREST;
  10330. }
  10331. break;
  10332. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  10333. magFilter = gl.LINEAR;
  10334. if (generateMipMaps) {
  10335. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  10336. }
  10337. else {
  10338. minFilter = gl.NEAREST;
  10339. }
  10340. break;
  10341. case BABYLON.Texture.LINEAR_LINEAR:
  10342. magFilter = gl.LINEAR;
  10343. minFilter = gl.LINEAR;
  10344. break;
  10345. case BABYLON.Texture.LINEAR_NEAREST:
  10346. magFilter = gl.LINEAR;
  10347. minFilter = gl.NEAREST;
  10348. break;
  10349. }
  10350. return {
  10351. min: minFilter,
  10352. mag: magFilter
  10353. };
  10354. };
  10355. var partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  10356. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  10357. var img;
  10358. var onload = function () {
  10359. loadedImages[index] = img;
  10360. loadedImages._internalCount++;
  10361. if (scene) {
  10362. scene._removePendingData(img);
  10363. }
  10364. if (loadedImages._internalCount === 6) {
  10365. onfinish(loadedImages);
  10366. }
  10367. };
  10368. var onerror = function (message, exception) {
  10369. if (scene) {
  10370. scene._removePendingData(img);
  10371. }
  10372. if (onErrorCallBack) {
  10373. onErrorCallBack(message, exception);
  10374. }
  10375. };
  10376. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  10377. if (scene) {
  10378. scene._addPendingData(img);
  10379. }
  10380. };
  10381. var cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  10382. if (onError === void 0) { onError = null; }
  10383. var loadedImages = [];
  10384. loadedImages._internalCount = 0;
  10385. for (var index = 0; index < 6; index++) {
  10386. partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  10387. }
  10388. };
  10389. var BufferPointer = /** @class */ (function () {
  10390. function BufferPointer() {
  10391. }
  10392. return BufferPointer;
  10393. }());
  10394. var InstancingAttributeInfo = /** @class */ (function () {
  10395. function InstancingAttributeInfo() {
  10396. }
  10397. return InstancingAttributeInfo;
  10398. }());
  10399. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  10400. /**
  10401. * Define options used to create a render target texture
  10402. */
  10403. var RenderTargetCreationOptions = /** @class */ (function () {
  10404. function RenderTargetCreationOptions() {
  10405. }
  10406. return RenderTargetCreationOptions;
  10407. }());
  10408. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  10409. /**
  10410. * Define options used to create a depth texture
  10411. */
  10412. var DepthTextureCreationOptions = /** @class */ (function () {
  10413. function DepthTextureCreationOptions() {
  10414. }
  10415. return DepthTextureCreationOptions;
  10416. }());
  10417. BABYLON.DepthTextureCreationOptions = DepthTextureCreationOptions;
  10418. /**
  10419. * Regroup several parameters relative to the browser in use
  10420. */
  10421. var EngineCapabilities = /** @class */ (function () {
  10422. function EngineCapabilities() {
  10423. }
  10424. return EngineCapabilities;
  10425. }());
  10426. BABYLON.EngineCapabilities = EngineCapabilities;
  10427. /**
  10428. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  10429. */
  10430. var Engine = /** @class */ (function () {
  10431. /**
  10432. * @constructor
  10433. * @param canvasOrContext defines the canvas or WebGL context to use for rendering
  10434. * @param antialias defines enable antialiasing (default: false)
  10435. * @param options defines further options to be sent to the getContext() function
  10436. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  10437. */
  10438. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  10439. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  10440. var _this = this;
  10441. // Public members
  10442. this.forcePOTTextures = false;
  10443. this.isFullscreen = false;
  10444. this.isPointerLock = false;
  10445. this.cullBackFaces = true;
  10446. this.renderEvenInBackground = true;
  10447. this.preventCacheWipeBetweenFrames = false;
  10448. // To enable/disable IDB support and avoid XHR on .manifest
  10449. this.enableOfflineSupport = false;
  10450. this.scenes = new Array();
  10451. this.postProcesses = new Array();
  10452. // Observables
  10453. /**
  10454. * Observable event triggered each time the rendering canvas is resized
  10455. */
  10456. this.onResizeObservable = new BABYLON.Observable();
  10457. /**
  10458. * Observable event triggered each time the canvas loses focus
  10459. */
  10460. this.onCanvasBlurObservable = new BABYLON.Observable();
  10461. /**
  10462. * Observable event triggered each time the canvas gains focus
  10463. */
  10464. this.onCanvasFocusObservable = new BABYLON.Observable();
  10465. /**
  10466. * Observable event triggered each time the canvas receives pointerout event
  10467. */
  10468. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  10469. /**
  10470. * Observable event triggered before each texture is initialized
  10471. */
  10472. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  10473. //WebVR
  10474. this._vrDisplay = undefined;
  10475. this._vrSupported = false;
  10476. this._vrExclusivePointerMode = false;
  10477. // Uniform buffers list
  10478. this.disableUniformBuffers = false;
  10479. this._uniformBuffers = new Array();
  10480. // Observables
  10481. /**
  10482. * Observable raised when the engine begins a new frame
  10483. */
  10484. this.onBeginFrameObservable = new BABYLON.Observable();
  10485. /**
  10486. * Observable raised when the engine ends the current frame
  10487. */
  10488. this.onEndFrameObservable = new BABYLON.Observable();
  10489. /**
  10490. * Observable raised when the engine is about to compile a shader
  10491. */
  10492. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  10493. /**
  10494. * Observable raised when the engine has jsut compiled a shader
  10495. */
  10496. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  10497. this._windowIsBackground = false;
  10498. this._webGLVersion = 1.0;
  10499. this._badOS = false;
  10500. this._badDesktopOS = false;
  10501. /**
  10502. * Gets or sets a value indicating if we want to disable texture binding optmization.
  10503. * This could be required on some buggy drivers which wants to have textures bound in a progressive order
  10504. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is.
  10505. */
  10506. this.disableTextureBindingOptimization = false;
  10507. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  10508. this.onVRRequestPresentComplete = new BABYLON.Observable();
  10509. this.onVRRequestPresentStart = new BABYLON.Observable();
  10510. this._colorWrite = true;
  10511. this._drawCalls = new BABYLON.PerfCounter();
  10512. this._textureCollisions = new BABYLON.PerfCounter();
  10513. this._renderingQueueLaunched = false;
  10514. this._activeRenderLoops = new Array();
  10515. // Deterministic lockstepMaxSteps
  10516. this._deterministicLockstep = false;
  10517. this._lockstepMaxSteps = 4;
  10518. // Lost context
  10519. this.onContextLostObservable = new BABYLON.Observable();
  10520. this.onContextRestoredObservable = new BABYLON.Observable();
  10521. this._contextWasLost = false;
  10522. this._doNotHandleContextLost = false;
  10523. // FPS
  10524. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  10525. this._fps = 60;
  10526. this._deltaTime = 0;
  10527. /**
  10528. * Turn this value on if you want to pause FPS computation when in background
  10529. */
  10530. this.disablePerformanceMonitorInBackground = false;
  10531. // States
  10532. this._depthCullingState = new BABYLON._DepthCullingState();
  10533. this._stencilState = new BABYLON._StencilState();
  10534. this._alphaState = new BABYLON._AlphaState();
  10535. this._alphaMode = Engine.ALPHA_DISABLE;
  10536. // Cache
  10537. this._internalTexturesCache = new Array();
  10538. this._activeChannel = 0;
  10539. this._currentTextureChannel = -1;
  10540. this._boundTexturesCache = {};
  10541. this._compiledEffects = {};
  10542. this._vertexAttribArraysEnabled = [];
  10543. this._uintIndicesCurrentlySet = false;
  10544. this._currentBoundBuffer = new Array();
  10545. this._currentBufferPointers = new Array();
  10546. this._currentInstanceLocations = new Array();
  10547. this._currentInstanceBuffers = new Array();
  10548. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  10549. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  10550. this._vaoRecordInProgress = false;
  10551. this._mustWipeVertexAttributes = false;
  10552. this._nextFreeTextureSlots = new Array();
  10553. this._maxSimultaneousTextures = 0;
  10554. this._activeRequests = new Array();
  10555. // Hardware supported Compressed Textures
  10556. this._texturesSupported = new Array();
  10557. this._onVRFullScreenTriggered = function () {
  10558. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  10559. //get the old size before we change
  10560. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  10561. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  10562. //get the width and height, change the render size
  10563. var leftEye = _this._vrDisplay.getEyeParameters('left');
  10564. _this.setHardwareScalingLevel(1);
  10565. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  10566. }
  10567. else {
  10568. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  10569. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  10570. }
  10571. };
  10572. this._boundUniforms = {};
  10573. // Register promises
  10574. BABYLON.PromisePolyfill.Apply();
  10575. var canvas = null;
  10576. Engine.Instances.push(this);
  10577. if (!canvasOrContext) {
  10578. return;
  10579. }
  10580. options = options || {};
  10581. if (canvasOrContext.getContext) {
  10582. canvas = canvasOrContext;
  10583. this._renderingCanvas = canvas;
  10584. if (antialias != null) {
  10585. options.antialias = antialias;
  10586. }
  10587. if (options.deterministicLockstep === undefined) {
  10588. options.deterministicLockstep = false;
  10589. }
  10590. if (options.lockstepMaxSteps === undefined) {
  10591. options.lockstepMaxSteps = 4;
  10592. }
  10593. if (options.preserveDrawingBuffer === undefined) {
  10594. options.preserveDrawingBuffer = false;
  10595. }
  10596. if (options.audioEngine === undefined) {
  10597. options.audioEngine = true;
  10598. }
  10599. if (options.stencil === undefined) {
  10600. options.stencil = true;
  10601. }
  10602. this._deterministicLockstep = options.deterministicLockstep;
  10603. this._lockstepMaxSteps = options.lockstepMaxSteps;
  10604. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  10605. // Exceptions
  10606. if (navigator && navigator.userAgent) {
  10607. var ua = navigator.userAgent;
  10608. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  10609. var exception = _a[_i];
  10610. var key = exception.key;
  10611. var targets = exception.targets;
  10612. if (ua.indexOf(key) > -1) {
  10613. if (exception.capture && exception.captureConstraint) {
  10614. var capture = exception.capture;
  10615. var constraint = exception.captureConstraint;
  10616. var regex = new RegExp(capture);
  10617. var matches = regex.exec(ua);
  10618. if (matches && matches.length > 0) {
  10619. var capturedValue = parseInt(matches[matches.length - 1]);
  10620. if (capturedValue >= constraint) {
  10621. continue;
  10622. }
  10623. }
  10624. }
  10625. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  10626. var target = targets_1[_b];
  10627. switch (target) {
  10628. case "uniformBuffer":
  10629. this.disableUniformBuffers = true;
  10630. break;
  10631. case "textureBindingOptimization":
  10632. this.disableTextureBindingOptimization = true;
  10633. break;
  10634. }
  10635. }
  10636. }
  10637. }
  10638. }
  10639. // GL
  10640. if (!options.disableWebGL2Support) {
  10641. try {
  10642. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  10643. if (this._gl) {
  10644. this._webGLVersion = 2.0;
  10645. }
  10646. }
  10647. catch (e) {
  10648. // Do nothing
  10649. }
  10650. }
  10651. if (!this._gl) {
  10652. if (!canvas) {
  10653. throw new Error("The provided canvas is null or undefined.");
  10654. }
  10655. try {
  10656. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  10657. }
  10658. catch (e) {
  10659. throw new Error("WebGL not supported");
  10660. }
  10661. }
  10662. if (!this._gl) {
  10663. throw new Error("WebGL not supported");
  10664. }
  10665. this._onCanvasFocus = function () {
  10666. _this.onCanvasFocusObservable.notifyObservers(_this);
  10667. };
  10668. this._onCanvasBlur = function () {
  10669. _this.onCanvasBlurObservable.notifyObservers(_this);
  10670. };
  10671. canvas.addEventListener("focus", this._onCanvasFocus);
  10672. canvas.addEventListener("blur", this._onCanvasBlur);
  10673. this._onBlur = function () {
  10674. if (_this.disablePerformanceMonitorInBackground) {
  10675. _this._performanceMonitor.disable();
  10676. }
  10677. _this._windowIsBackground = true;
  10678. };
  10679. this._onFocus = function () {
  10680. if (_this.disablePerformanceMonitorInBackground) {
  10681. _this._performanceMonitor.enable();
  10682. }
  10683. _this._windowIsBackground = false;
  10684. };
  10685. this._onCanvasPointerOut = function (ev) {
  10686. _this.onCanvasPointerOutObservable.notifyObservers(ev);
  10687. };
  10688. window.addEventListener("blur", this._onBlur);
  10689. window.addEventListener("focus", this._onFocus);
  10690. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  10691. // Context lost
  10692. if (!this._doNotHandleContextLost) {
  10693. this._onContextLost = function (evt) {
  10694. evt.preventDefault();
  10695. _this._contextWasLost = true;
  10696. BABYLON.Tools.Warn("WebGL context lost.");
  10697. _this.onContextLostObservable.notifyObservers(_this);
  10698. };
  10699. this._onContextRestored = function (evt) {
  10700. // Adding a timeout to avoid race condition at browser level
  10701. setTimeout(function () {
  10702. // Rebuild gl context
  10703. _this._initGLContext();
  10704. // Rebuild effects
  10705. _this._rebuildEffects();
  10706. // Rebuild textures
  10707. _this._rebuildInternalTextures();
  10708. // Rebuild buffers
  10709. _this._rebuildBuffers();
  10710. // Cache
  10711. _this.wipeCaches(true);
  10712. BABYLON.Tools.Warn("WebGL context successfully restored.");
  10713. _this.onContextRestoredObservable.notifyObservers(_this);
  10714. _this._contextWasLost = false;
  10715. }, 0);
  10716. };
  10717. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  10718. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  10719. }
  10720. }
  10721. else {
  10722. this._gl = canvasOrContext;
  10723. this._renderingCanvas = this._gl.canvas;
  10724. if (this._gl.renderbufferStorageMultisample) {
  10725. this._webGLVersion = 2.0;
  10726. }
  10727. options.stencil = this._gl.getContextAttributes().stencil;
  10728. }
  10729. // Viewport
  10730. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  10731. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  10732. this.resize();
  10733. this._isStencilEnable = options.stencil ? true : false;
  10734. this._initGLContext();
  10735. if (canvas) {
  10736. // Fullscreen
  10737. this._onFullscreenChange = function () {
  10738. if (document.fullscreen !== undefined) {
  10739. _this.isFullscreen = document.fullscreen;
  10740. }
  10741. else if (document.mozFullScreen !== undefined) {
  10742. _this.isFullscreen = document.mozFullScreen;
  10743. }
  10744. else if (document.webkitIsFullScreen !== undefined) {
  10745. _this.isFullscreen = document.webkitIsFullScreen;
  10746. }
  10747. else if (document.msIsFullScreen !== undefined) {
  10748. _this.isFullscreen = document.msIsFullScreen;
  10749. }
  10750. // Pointer lock
  10751. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  10752. canvas.requestPointerLock = canvas.requestPointerLock ||
  10753. canvas.msRequestPointerLock ||
  10754. canvas.mozRequestPointerLock ||
  10755. canvas.webkitRequestPointerLock;
  10756. if (canvas.requestPointerLock) {
  10757. canvas.requestPointerLock();
  10758. }
  10759. }
  10760. };
  10761. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  10762. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  10763. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  10764. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  10765. // Pointer lock
  10766. this._onPointerLockChange = function () {
  10767. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  10768. document.webkitPointerLockElement === canvas ||
  10769. document.msPointerLockElement === canvas ||
  10770. document.pointerLockElement === canvas);
  10771. };
  10772. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  10773. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  10774. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  10775. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  10776. this._onVRDisplayPointerRestricted = function () {
  10777. if (canvas) {
  10778. canvas.requestPointerLock();
  10779. }
  10780. };
  10781. this._onVRDisplayPointerUnrestricted = function () {
  10782. document.exitPointerLock();
  10783. };
  10784. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  10785. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  10786. }
  10787. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  10788. Engine.audioEngine = new BABYLON.AudioEngine();
  10789. }
  10790. // Prepare buffer pointers
  10791. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  10792. this._currentBufferPointers[i] = new BufferPointer();
  10793. }
  10794. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  10795. // Load WebVR Devices
  10796. if (options.autoEnableWebVR) {
  10797. this.initWebVR();
  10798. }
  10799. // Detect if we are running on a faulty buggy OS.
  10800. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  10801. // Detect if we are running on a faulty buggy desktop OS.
  10802. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  10803. console.log("Babylon.js engine (v" + Engine.Version + ") launched");
  10804. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  10805. }
  10806. Object.defineProperty(Engine, "LastCreatedEngine", {
  10807. get: function () {
  10808. if (Engine.Instances.length === 0) {
  10809. return null;
  10810. }
  10811. return Engine.Instances[Engine.Instances.length - 1];
  10812. },
  10813. enumerable: true,
  10814. configurable: true
  10815. });
  10816. Object.defineProperty(Engine, "LastCreatedScene", {
  10817. get: function () {
  10818. var lastCreatedEngine = Engine.LastCreatedEngine;
  10819. if (!lastCreatedEngine) {
  10820. return null;
  10821. }
  10822. if (lastCreatedEngine.scenes.length === 0) {
  10823. return null;
  10824. }
  10825. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  10826. },
  10827. enumerable: true,
  10828. configurable: true
  10829. });
  10830. /**
  10831. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  10832. */
  10833. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  10834. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  10835. var engine = Engine.Instances[engineIndex];
  10836. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  10837. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  10838. }
  10839. }
  10840. };
  10841. Object.defineProperty(Engine, "NEVER", {
  10842. get: function () {
  10843. return Engine._NEVER;
  10844. },
  10845. enumerable: true,
  10846. configurable: true
  10847. });
  10848. Object.defineProperty(Engine, "ALWAYS", {
  10849. get: function () {
  10850. return Engine._ALWAYS;
  10851. },
  10852. enumerable: true,
  10853. configurable: true
  10854. });
  10855. Object.defineProperty(Engine, "LESS", {
  10856. get: function () {
  10857. return Engine._LESS;
  10858. },
  10859. enumerable: true,
  10860. configurable: true
  10861. });
  10862. Object.defineProperty(Engine, "EQUAL", {
  10863. get: function () {
  10864. return Engine._EQUAL;
  10865. },
  10866. enumerable: true,
  10867. configurable: true
  10868. });
  10869. Object.defineProperty(Engine, "LEQUAL", {
  10870. get: function () {
  10871. return Engine._LEQUAL;
  10872. },
  10873. enumerable: true,
  10874. configurable: true
  10875. });
  10876. Object.defineProperty(Engine, "GREATER", {
  10877. get: function () {
  10878. return Engine._GREATER;
  10879. },
  10880. enumerable: true,
  10881. configurable: true
  10882. });
  10883. Object.defineProperty(Engine, "GEQUAL", {
  10884. get: function () {
  10885. return Engine._GEQUAL;
  10886. },
  10887. enumerable: true,
  10888. configurable: true
  10889. });
  10890. Object.defineProperty(Engine, "NOTEQUAL", {
  10891. get: function () {
  10892. return Engine._NOTEQUAL;
  10893. },
  10894. enumerable: true,
  10895. configurable: true
  10896. });
  10897. Object.defineProperty(Engine, "KEEP", {
  10898. get: function () {
  10899. return Engine._KEEP;
  10900. },
  10901. enumerable: true,
  10902. configurable: true
  10903. });
  10904. Object.defineProperty(Engine, "REPLACE", {
  10905. get: function () {
  10906. return Engine._REPLACE;
  10907. },
  10908. enumerable: true,
  10909. configurable: true
  10910. });
  10911. Object.defineProperty(Engine, "INCR", {
  10912. get: function () {
  10913. return Engine._INCR;
  10914. },
  10915. enumerable: true,
  10916. configurable: true
  10917. });
  10918. Object.defineProperty(Engine, "DECR", {
  10919. get: function () {
  10920. return Engine._DECR;
  10921. },
  10922. enumerable: true,
  10923. configurable: true
  10924. });
  10925. Object.defineProperty(Engine, "INVERT", {
  10926. get: function () {
  10927. return Engine._INVERT;
  10928. },
  10929. enumerable: true,
  10930. configurable: true
  10931. });
  10932. Object.defineProperty(Engine, "INCR_WRAP", {
  10933. get: function () {
  10934. return Engine._INCR_WRAP;
  10935. },
  10936. enumerable: true,
  10937. configurable: true
  10938. });
  10939. Object.defineProperty(Engine, "DECR_WRAP", {
  10940. get: function () {
  10941. return Engine._DECR_WRAP;
  10942. },
  10943. enumerable: true,
  10944. configurable: true
  10945. });
  10946. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  10947. get: function () {
  10948. return Engine._ALPHA_DISABLE;
  10949. },
  10950. enumerable: true,
  10951. configurable: true
  10952. });
  10953. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  10954. get: function () {
  10955. return Engine._ALPHA_ONEONE;
  10956. },
  10957. enumerable: true,
  10958. configurable: true
  10959. });
  10960. Object.defineProperty(Engine, "ALPHA_ADD", {
  10961. get: function () {
  10962. return Engine._ALPHA_ADD;
  10963. },
  10964. enumerable: true,
  10965. configurable: true
  10966. });
  10967. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  10968. get: function () {
  10969. return Engine._ALPHA_COMBINE;
  10970. },
  10971. enumerable: true,
  10972. configurable: true
  10973. });
  10974. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  10975. get: function () {
  10976. return Engine._ALPHA_SUBTRACT;
  10977. },
  10978. enumerable: true,
  10979. configurable: true
  10980. });
  10981. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  10982. get: function () {
  10983. return Engine._ALPHA_MULTIPLY;
  10984. },
  10985. enumerable: true,
  10986. configurable: true
  10987. });
  10988. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  10989. get: function () {
  10990. return Engine._ALPHA_MAXIMIZED;
  10991. },
  10992. enumerable: true,
  10993. configurable: true
  10994. });
  10995. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  10996. get: function () {
  10997. return Engine._ALPHA_PREMULTIPLIED;
  10998. },
  10999. enumerable: true,
  11000. configurable: true
  11001. });
  11002. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  11003. get: function () {
  11004. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  11005. },
  11006. enumerable: true,
  11007. configurable: true
  11008. });
  11009. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  11010. get: function () {
  11011. return Engine._ALPHA_INTERPOLATE;
  11012. },
  11013. enumerable: true,
  11014. configurable: true
  11015. });
  11016. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  11017. get: function () {
  11018. return Engine._ALPHA_SCREENMODE;
  11019. },
  11020. enumerable: true,
  11021. configurable: true
  11022. });
  11023. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  11024. get: function () {
  11025. return Engine._DELAYLOADSTATE_NONE;
  11026. },
  11027. enumerable: true,
  11028. configurable: true
  11029. });
  11030. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  11031. get: function () {
  11032. return Engine._DELAYLOADSTATE_LOADED;
  11033. },
  11034. enumerable: true,
  11035. configurable: true
  11036. });
  11037. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  11038. get: function () {
  11039. return Engine._DELAYLOADSTATE_LOADING;
  11040. },
  11041. enumerable: true,
  11042. configurable: true
  11043. });
  11044. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  11045. get: function () {
  11046. return Engine._DELAYLOADSTATE_NOTLOADED;
  11047. },
  11048. enumerable: true,
  11049. configurable: true
  11050. });
  11051. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  11052. get: function () {
  11053. return Engine._TEXTUREFORMAT_ALPHA;
  11054. },
  11055. enumerable: true,
  11056. configurable: true
  11057. });
  11058. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  11059. get: function () {
  11060. return Engine._TEXTUREFORMAT_LUMINANCE;
  11061. },
  11062. enumerable: true,
  11063. configurable: true
  11064. });
  11065. Object.defineProperty(Engine, "TEXTUREFORMAT_R32F", {
  11066. /**
  11067. * R32F
  11068. */
  11069. get: function () {
  11070. return Engine._TEXTUREFORMAT_R32F;
  11071. },
  11072. enumerable: true,
  11073. configurable: true
  11074. });
  11075. Object.defineProperty(Engine, "TEXTUREFORMAT_RG32F", {
  11076. /**
  11077. * RG32F
  11078. */
  11079. get: function () {
  11080. return Engine._TEXTUREFORMAT_RG32F;
  11081. },
  11082. enumerable: true,
  11083. configurable: true
  11084. });
  11085. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB32F", {
  11086. /**
  11087. * RGB32F
  11088. */
  11089. get: function () {
  11090. return Engine._TEXTUREFORMAT_RGB32F;
  11091. },
  11092. enumerable: true,
  11093. configurable: true
  11094. });
  11095. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA32F", {
  11096. /**
  11097. * RGBA32F
  11098. */
  11099. get: function () {
  11100. return Engine._TEXTUREFORMAT_RGBA32F;
  11101. },
  11102. enumerable: true,
  11103. configurable: true
  11104. });
  11105. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  11106. get: function () {
  11107. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  11108. },
  11109. enumerable: true,
  11110. configurable: true
  11111. });
  11112. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  11113. get: function () {
  11114. return Engine._TEXTUREFORMAT_RGB;
  11115. },
  11116. enumerable: true,
  11117. configurable: true
  11118. });
  11119. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  11120. get: function () {
  11121. return Engine._TEXTUREFORMAT_RGBA;
  11122. },
  11123. enumerable: true,
  11124. configurable: true
  11125. });
  11126. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  11127. get: function () {
  11128. return Engine._TEXTURETYPE_UNSIGNED_INT;
  11129. },
  11130. enumerable: true,
  11131. configurable: true
  11132. });
  11133. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  11134. get: function () {
  11135. return Engine._TEXTURETYPE_FLOAT;
  11136. },
  11137. enumerable: true,
  11138. configurable: true
  11139. });
  11140. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  11141. get: function () {
  11142. return Engine._TEXTURETYPE_HALF_FLOAT;
  11143. },
  11144. enumerable: true,
  11145. configurable: true
  11146. });
  11147. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  11148. get: function () {
  11149. return Engine._SCALEMODE_FLOOR;
  11150. },
  11151. enumerable: true,
  11152. configurable: true
  11153. });
  11154. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  11155. get: function () {
  11156. return Engine._SCALEMODE_NEAREST;
  11157. },
  11158. enumerable: true,
  11159. configurable: true
  11160. });
  11161. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  11162. get: function () {
  11163. return Engine._SCALEMODE_CEILING;
  11164. },
  11165. enumerable: true,
  11166. configurable: true
  11167. });
  11168. Object.defineProperty(Engine, "Version", {
  11169. get: function () {
  11170. return "3.2.0-alphaB";
  11171. },
  11172. enumerable: true,
  11173. configurable: true
  11174. });
  11175. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  11176. get: function () {
  11177. return this._vrExclusivePointerMode;
  11178. },
  11179. enumerable: true,
  11180. configurable: true
  11181. });
  11182. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  11183. get: function () {
  11184. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  11185. },
  11186. enumerable: true,
  11187. configurable: true
  11188. });
  11189. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  11190. get: function () {
  11191. return this._webGLVersion < 2 || this.forcePOTTextures;
  11192. },
  11193. enumerable: true,
  11194. configurable: true
  11195. });
  11196. Object.defineProperty(Engine.prototype, "badOS", {
  11197. get: function () {
  11198. return this._badOS;
  11199. },
  11200. enumerable: true,
  11201. configurable: true
  11202. });
  11203. Object.defineProperty(Engine.prototype, "badDesktopOS", {
  11204. get: function () {
  11205. return this._badDesktopOS;
  11206. },
  11207. enumerable: true,
  11208. configurable: true
  11209. });
  11210. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  11211. get: function () {
  11212. return this._performanceMonitor;
  11213. },
  11214. enumerable: true,
  11215. configurable: true
  11216. });
  11217. Object.defineProperty(Engine.prototype, "texturesSupported", {
  11218. get: function () {
  11219. return this._texturesSupported;
  11220. },
  11221. enumerable: true,
  11222. configurable: true
  11223. });
  11224. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  11225. get: function () {
  11226. return this._textureFormatInUse;
  11227. },
  11228. enumerable: true,
  11229. configurable: true
  11230. });
  11231. Object.defineProperty(Engine.prototype, "currentViewport", {
  11232. get: function () {
  11233. return this._cachedViewport;
  11234. },
  11235. enumerable: true,
  11236. configurable: true
  11237. });
  11238. Object.defineProperty(Engine.prototype, "emptyTexture", {
  11239. // Empty texture
  11240. get: function () {
  11241. if (!this._emptyTexture) {
  11242. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11243. }
  11244. return this._emptyTexture;
  11245. },
  11246. enumerable: true,
  11247. configurable: true
  11248. });
  11249. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  11250. get: function () {
  11251. if (!this._emptyTexture3D) {
  11252. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11253. }
  11254. return this._emptyTexture3D;
  11255. },
  11256. enumerable: true,
  11257. configurable: true
  11258. });
  11259. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  11260. get: function () {
  11261. if (!this._emptyCubeTexture) {
  11262. var faceData = new Uint8Array(4);
  11263. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  11264. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11265. }
  11266. return this._emptyCubeTexture;
  11267. },
  11268. enumerable: true,
  11269. configurable: true
  11270. });
  11271. Engine.prototype._rebuildInternalTextures = function () {
  11272. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  11273. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  11274. var internalTexture = currentState_1[_i];
  11275. internalTexture._rebuild();
  11276. }
  11277. };
  11278. Engine.prototype._rebuildEffects = function () {
  11279. for (var key in this._compiledEffects) {
  11280. var effect = this._compiledEffects[key];
  11281. effect._prepareEffect();
  11282. }
  11283. BABYLON.Effect.ResetCache();
  11284. };
  11285. Engine.prototype._rebuildBuffers = function () {
  11286. // Index / Vertex
  11287. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  11288. var scene = _a[_i];
  11289. scene.resetCachedMaterial();
  11290. scene._rebuildGeometries();
  11291. scene._rebuildTextures();
  11292. }
  11293. // Uniforms
  11294. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  11295. var uniformBuffer = _c[_b];
  11296. uniformBuffer._rebuild();
  11297. }
  11298. };
  11299. Engine.prototype._initGLContext = function () {
  11300. // Caps
  11301. this._caps = new EngineCapabilities();
  11302. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  11303. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  11304. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  11305. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  11306. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  11307. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  11308. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  11309. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  11310. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  11311. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  11312. // Infos
  11313. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  11314. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  11315. if (rendererInfo != null) {
  11316. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  11317. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  11318. }
  11319. if (!this._glVendor) {
  11320. this._glVendor = "Unknown vendor";
  11321. }
  11322. if (!this._glRenderer) {
  11323. this._glRenderer = "Unknown renderer";
  11324. }
  11325. // Constants
  11326. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  11327. if (this._gl.RGBA16F !== 0x881A) {
  11328. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  11329. }
  11330. if (this._gl.RGBA32F !== 0x8814) {
  11331. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  11332. }
  11333. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  11334. this._gl.DEPTH24_STENCIL8 = 35056;
  11335. }
  11336. // Extensions
  11337. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  11338. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  11339. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  11340. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  11341. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  11342. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  11343. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  11344. 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');
  11345. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  11346. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  11347. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  11348. this._caps.highPrecisionShaderSupported = true;
  11349. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  11350. if (this._caps.timerQuery) {
  11351. if (this._webGLVersion === 1) {
  11352. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  11353. }
  11354. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  11355. }
  11356. // Checks if some of the format renders first to allow the use of webgl inspector.
  11357. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  11358. this._caps.textureFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float');
  11359. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear');
  11360. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer();
  11361. this._caps.textureHalfFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float');
  11362. this._caps.textureHalfFloatLinearFiltering = this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'));
  11363. if (this._webGLVersion > 1) {
  11364. this._gl.HALF_FLOAT_OES = 0x140B;
  11365. }
  11366. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  11367. this._caps.textureLOD = this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod');
  11368. // Draw buffers
  11369. if (this._webGLVersion > 1) {
  11370. this._caps.drawBuffersExtension = true;
  11371. }
  11372. else {
  11373. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  11374. if (drawBuffersExtension !== null) {
  11375. this._caps.drawBuffersExtension = true;
  11376. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  11377. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  11378. for (var i = 0; i < 16; i++) {
  11379. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  11380. }
  11381. }
  11382. else {
  11383. this._caps.drawBuffersExtension = false;
  11384. }
  11385. }
  11386. // Depth Texture
  11387. if (this._webGLVersion > 1) {
  11388. this._caps.depthTextureExtension = true;
  11389. }
  11390. else {
  11391. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  11392. if (depthTextureExtension != null) {
  11393. this._caps.depthTextureExtension = true;
  11394. this._gl.UNSIGNED_INT_24_8 = depthTextureExtension.UNSIGNED_INT_24_8_WEBGL;
  11395. }
  11396. }
  11397. // Vertex array object
  11398. if (this._webGLVersion > 1) {
  11399. this._caps.vertexArrayObject = true;
  11400. }
  11401. else {
  11402. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  11403. if (vertexArrayObjectExtension != null) {
  11404. this._caps.vertexArrayObject = true;
  11405. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  11406. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  11407. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  11408. }
  11409. else {
  11410. this._caps.vertexArrayObject = false;
  11411. }
  11412. }
  11413. // Instances count
  11414. if (this._webGLVersion > 1) {
  11415. this._caps.instancedArrays = true;
  11416. }
  11417. else {
  11418. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  11419. if (instanceExtension != null) {
  11420. this._caps.instancedArrays = true;
  11421. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  11422. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  11423. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  11424. }
  11425. else {
  11426. this._caps.instancedArrays = false;
  11427. }
  11428. }
  11429. // Intelligently add supported compressed formats in order to check for.
  11430. // Check for ASTC support first as it is most powerful and to be very cross platform.
  11431. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  11432. // Likely no hardware which supports both PVR & DXT, so order matters little.
  11433. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  11434. if (this._caps.astc)
  11435. this.texturesSupported.push('-astc.ktx');
  11436. if (this._caps.s3tc)
  11437. this.texturesSupported.push('-dxt.ktx');
  11438. if (this._caps.pvrtc)
  11439. this.texturesSupported.push('-pvrtc.ktx');
  11440. if (this._caps.etc2)
  11441. this.texturesSupported.push('-etc2.ktx');
  11442. if (this._caps.etc1)
  11443. this.texturesSupported.push('-etc1.ktx');
  11444. if (this._gl.getShaderPrecisionFormat) {
  11445. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  11446. if (highp) {
  11447. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  11448. }
  11449. }
  11450. // Depth buffer
  11451. this.setDepthBuffer(true);
  11452. this.setDepthFunctionToLessOrEqual();
  11453. this.setDepthWrite(true);
  11454. // Texture maps
  11455. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  11456. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  11457. this._nextFreeTextureSlots.push(slot);
  11458. }
  11459. };
  11460. Object.defineProperty(Engine.prototype, "webGLVersion", {
  11461. get: function () {
  11462. return this._webGLVersion;
  11463. },
  11464. enumerable: true,
  11465. configurable: true
  11466. });
  11467. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  11468. /**
  11469. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  11470. */
  11471. get: function () {
  11472. return this._isStencilEnable;
  11473. },
  11474. enumerable: true,
  11475. configurable: true
  11476. });
  11477. Engine.prototype._prepareWorkingCanvas = function () {
  11478. if (this._workingCanvas) {
  11479. return;
  11480. }
  11481. this._workingCanvas = document.createElement("canvas");
  11482. var context = this._workingCanvas.getContext("2d");
  11483. if (context) {
  11484. this._workingContext = context;
  11485. }
  11486. };
  11487. Engine.prototype.resetTextureCache = function () {
  11488. for (var key in this._boundTexturesCache) {
  11489. var boundTexture = this._boundTexturesCache[key];
  11490. if (boundTexture) {
  11491. this._removeDesignatedSlot(boundTexture);
  11492. }
  11493. this._boundTexturesCache[key] = null;
  11494. }
  11495. if (!this.disableTextureBindingOptimization) {
  11496. this._nextFreeTextureSlots = [];
  11497. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  11498. this._nextFreeTextureSlots.push(slot);
  11499. }
  11500. }
  11501. this._currentTextureChannel = -1;
  11502. };
  11503. Engine.prototype.isDeterministicLockStep = function () {
  11504. return this._deterministicLockstep;
  11505. };
  11506. Engine.prototype.getLockstepMaxSteps = function () {
  11507. return this._lockstepMaxSteps;
  11508. };
  11509. Engine.prototype.getGlInfo = function () {
  11510. return {
  11511. vendor: this._glVendor,
  11512. renderer: this._glRenderer,
  11513. version: this._glVersion
  11514. };
  11515. };
  11516. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  11517. if (useScreen === void 0) { useScreen = false; }
  11518. var viewport = camera.viewport;
  11519. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  11520. };
  11521. Engine.prototype.getRenderWidth = function (useScreen) {
  11522. if (useScreen === void 0) { useScreen = false; }
  11523. if (!useScreen && this._currentRenderTarget) {
  11524. return this._currentRenderTarget.width;
  11525. }
  11526. return this._gl.drawingBufferWidth;
  11527. };
  11528. Engine.prototype.getRenderHeight = function (useScreen) {
  11529. if (useScreen === void 0) { useScreen = false; }
  11530. if (!useScreen && this._currentRenderTarget) {
  11531. return this._currentRenderTarget.height;
  11532. }
  11533. return this._gl.drawingBufferHeight;
  11534. };
  11535. Engine.prototype.getRenderingCanvas = function () {
  11536. return this._renderingCanvas;
  11537. };
  11538. Engine.prototype.getRenderingCanvasClientRect = function () {
  11539. if (!this._renderingCanvas) {
  11540. return null;
  11541. }
  11542. return this._renderingCanvas.getBoundingClientRect();
  11543. };
  11544. Engine.prototype.setHardwareScalingLevel = function (level) {
  11545. this._hardwareScalingLevel = level;
  11546. this.resize();
  11547. };
  11548. Engine.prototype.getHardwareScalingLevel = function () {
  11549. return this._hardwareScalingLevel;
  11550. };
  11551. Engine.prototype.getLoadedTexturesCache = function () {
  11552. return this._internalTexturesCache;
  11553. };
  11554. Engine.prototype.getCaps = function () {
  11555. return this._caps;
  11556. };
  11557. Object.defineProperty(Engine.prototype, "drawCalls", {
  11558. /** The number of draw calls submitted last frame */
  11559. get: function () {
  11560. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  11561. return 0;
  11562. },
  11563. enumerable: true,
  11564. configurable: true
  11565. });
  11566. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  11567. get: function () {
  11568. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  11569. return null;
  11570. },
  11571. enumerable: true,
  11572. configurable: true
  11573. });
  11574. Engine.prototype.getDepthFunction = function () {
  11575. return this._depthCullingState.depthFunc;
  11576. };
  11577. Engine.prototype.setDepthFunction = function (depthFunc) {
  11578. this._depthCullingState.depthFunc = depthFunc;
  11579. };
  11580. Engine.prototype.setDepthFunctionToGreater = function () {
  11581. this._depthCullingState.depthFunc = this._gl.GREATER;
  11582. };
  11583. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  11584. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  11585. };
  11586. Engine.prototype.setDepthFunctionToLess = function () {
  11587. this._depthCullingState.depthFunc = this._gl.LESS;
  11588. };
  11589. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  11590. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  11591. };
  11592. Engine.prototype.getStencilBuffer = function () {
  11593. return this._stencilState.stencilTest;
  11594. };
  11595. Engine.prototype.setStencilBuffer = function (enable) {
  11596. this._stencilState.stencilTest = enable;
  11597. };
  11598. Engine.prototype.getStencilMask = function () {
  11599. return this._stencilState.stencilMask;
  11600. };
  11601. Engine.prototype.setStencilMask = function (mask) {
  11602. this._stencilState.stencilMask = mask;
  11603. };
  11604. Engine.prototype.getStencilFunction = function () {
  11605. return this._stencilState.stencilFunc;
  11606. };
  11607. Engine.prototype.getStencilFunctionReference = function () {
  11608. return this._stencilState.stencilFuncRef;
  11609. };
  11610. Engine.prototype.getStencilFunctionMask = function () {
  11611. return this._stencilState.stencilFuncMask;
  11612. };
  11613. Engine.prototype.setStencilFunction = function (stencilFunc) {
  11614. this._stencilState.stencilFunc = stencilFunc;
  11615. };
  11616. Engine.prototype.setStencilFunctionReference = function (reference) {
  11617. this._stencilState.stencilFuncRef = reference;
  11618. };
  11619. Engine.prototype.setStencilFunctionMask = function (mask) {
  11620. this._stencilState.stencilFuncMask = mask;
  11621. };
  11622. Engine.prototype.getStencilOperationFail = function () {
  11623. return this._stencilState.stencilOpStencilFail;
  11624. };
  11625. Engine.prototype.getStencilOperationDepthFail = function () {
  11626. return this._stencilState.stencilOpDepthFail;
  11627. };
  11628. Engine.prototype.getStencilOperationPass = function () {
  11629. return this._stencilState.stencilOpStencilDepthPass;
  11630. };
  11631. Engine.prototype.setStencilOperationFail = function (operation) {
  11632. this._stencilState.stencilOpStencilFail = operation;
  11633. };
  11634. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  11635. this._stencilState.stencilOpDepthFail = operation;
  11636. };
  11637. Engine.prototype.setStencilOperationPass = function (operation) {
  11638. this._stencilState.stencilOpStencilDepthPass = operation;
  11639. };
  11640. Engine.prototype.setDitheringState = function (value) {
  11641. if (value) {
  11642. this._gl.enable(this._gl.DITHER);
  11643. }
  11644. else {
  11645. this._gl.disable(this._gl.DITHER);
  11646. }
  11647. };
  11648. Engine.prototype.setRasterizerState = function (value) {
  11649. if (value) {
  11650. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  11651. }
  11652. else {
  11653. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  11654. }
  11655. };
  11656. /**
  11657. * stop executing a render loop function and remove it from the execution array
  11658. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  11659. */
  11660. Engine.prototype.stopRenderLoop = function (renderFunction) {
  11661. if (!renderFunction) {
  11662. this._activeRenderLoops = [];
  11663. return;
  11664. }
  11665. var index = this._activeRenderLoops.indexOf(renderFunction);
  11666. if (index >= 0) {
  11667. this._activeRenderLoops.splice(index, 1);
  11668. }
  11669. };
  11670. Engine.prototype._renderLoop = function () {
  11671. if (!this._contextWasLost) {
  11672. var shouldRender = true;
  11673. if (!this.renderEvenInBackground && this._windowIsBackground) {
  11674. shouldRender = false;
  11675. }
  11676. if (shouldRender) {
  11677. // Start new frame
  11678. this.beginFrame();
  11679. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  11680. var renderFunction = this._activeRenderLoops[index];
  11681. renderFunction();
  11682. }
  11683. // Present
  11684. this.endFrame();
  11685. }
  11686. }
  11687. if (this._activeRenderLoops.length > 0) {
  11688. // Register new frame
  11689. var requester = null;
  11690. if (this._vrDisplay && this._vrDisplay.isPresenting)
  11691. requester = this._vrDisplay;
  11692. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  11693. }
  11694. else {
  11695. this._renderingQueueLaunched = false;
  11696. }
  11697. };
  11698. /**
  11699. * Register and execute a render loop. The engine can have more than one render function.
  11700. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  11701. * @example
  11702. * engine.runRenderLoop(function () {
  11703. * scene.render()
  11704. * })
  11705. */
  11706. Engine.prototype.runRenderLoop = function (renderFunction) {
  11707. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  11708. return;
  11709. }
  11710. this._activeRenderLoops.push(renderFunction);
  11711. if (!this._renderingQueueLaunched) {
  11712. this._renderingQueueLaunched = true;
  11713. this._bindedRenderFunction = this._renderLoop.bind(this);
  11714. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  11715. }
  11716. };
  11717. /**
  11718. * Toggle full screen mode.
  11719. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  11720. * @param {any} options - an options object to be sent to the requestFullscreen function
  11721. */
  11722. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  11723. if (this.isFullscreen) {
  11724. BABYLON.Tools.ExitFullscreen();
  11725. }
  11726. else {
  11727. this._pointerLockRequested = requestPointerLock;
  11728. if (this._renderingCanvas) {
  11729. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  11730. }
  11731. }
  11732. };
  11733. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  11734. if (stencil === void 0) { stencil = false; }
  11735. this.applyStates();
  11736. var mode = 0;
  11737. if (backBuffer && color) {
  11738. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  11739. mode |= this._gl.COLOR_BUFFER_BIT;
  11740. }
  11741. if (depth) {
  11742. this._gl.clearDepth(1.0);
  11743. mode |= this._gl.DEPTH_BUFFER_BIT;
  11744. }
  11745. if (stencil) {
  11746. this._gl.clearStencil(0);
  11747. mode |= this._gl.STENCIL_BUFFER_BIT;
  11748. }
  11749. this._gl.clear(mode);
  11750. };
  11751. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  11752. var gl = this._gl;
  11753. // Save state
  11754. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  11755. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  11756. // Change state
  11757. gl.enable(gl.SCISSOR_TEST);
  11758. gl.scissor(x, y, width, height);
  11759. // Clear
  11760. this.clear(clearColor, true, true, true);
  11761. // Restore state
  11762. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  11763. if (curScissor === true) {
  11764. gl.enable(gl.SCISSOR_TEST);
  11765. }
  11766. else {
  11767. gl.disable(gl.SCISSOR_TEST);
  11768. }
  11769. };
  11770. /**
  11771. * Set the WebGL's viewport
  11772. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  11773. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  11774. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  11775. */
  11776. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  11777. var width = requiredWidth || this.getRenderWidth();
  11778. var height = requiredHeight || this.getRenderHeight();
  11779. var x = viewport.x || 0;
  11780. var y = viewport.y || 0;
  11781. this._cachedViewport = viewport;
  11782. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  11783. };
  11784. /**
  11785. * Directly set the WebGL Viewport
  11786. * The x, y, width & height are directly passed to the WebGL call
  11787. * @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.
  11788. */
  11789. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  11790. var currentViewport = this._cachedViewport;
  11791. this._cachedViewport = null;
  11792. this._gl.viewport(x, y, width, height);
  11793. return currentViewport;
  11794. };
  11795. Engine.prototype.beginFrame = function () {
  11796. this.onBeginFrameObservable.notifyObservers(this);
  11797. this._measureFps();
  11798. };
  11799. Engine.prototype.endFrame = function () {
  11800. //force a flush in case we are using a bad OS.
  11801. if (this._badOS) {
  11802. this.flushFramebuffer();
  11803. }
  11804. //submit frame to the vr device, if enabled
  11805. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  11806. // TODO: We should only submit the frame if we read frameData successfully.
  11807. this._vrDisplay.submitFrame();
  11808. }
  11809. this.onEndFrameObservable.notifyObservers(this);
  11810. };
  11811. /**
  11812. * resize the view according to the canvas' size.
  11813. * @example
  11814. * window.addEventListener("resize", function () {
  11815. * engine.resize();
  11816. * });
  11817. */
  11818. Engine.prototype.resize = function () {
  11819. // We're not resizing the size of the canvas while in VR mode & presenting
  11820. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  11821. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  11822. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  11823. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  11824. }
  11825. };
  11826. /**
  11827. * force a specific size of the canvas
  11828. * @param {number} width - the new canvas' width
  11829. * @param {number} height - the new canvas' height
  11830. */
  11831. Engine.prototype.setSize = function (width, height) {
  11832. if (!this._renderingCanvas) {
  11833. return;
  11834. }
  11835. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  11836. return;
  11837. }
  11838. this._renderingCanvas.width = width;
  11839. this._renderingCanvas.height = height;
  11840. for (var index = 0; index < this.scenes.length; index++) {
  11841. var scene = this.scenes[index];
  11842. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  11843. var cam = scene.cameras[camIndex];
  11844. cam._currentRenderId = 0;
  11845. }
  11846. }
  11847. if (this.onResizeObservable.hasObservers) {
  11848. this.onResizeObservable.notifyObservers(this);
  11849. }
  11850. };
  11851. // WebVR functions
  11852. Engine.prototype.isVRDevicePresent = function () {
  11853. return !!this._vrDisplay;
  11854. };
  11855. Engine.prototype.getVRDevice = function () {
  11856. return this._vrDisplay;
  11857. };
  11858. /**
  11859. * Initializes a webVR display and starts listening to display change events.
  11860. * The onVRDisplayChangedObservable will be notified upon these changes.
  11861. * @returns The onVRDisplayChangedObservable.
  11862. */
  11863. Engine.prototype.initWebVR = function () {
  11864. this.initWebVRAsync();
  11865. return this.onVRDisplayChangedObservable;
  11866. };
  11867. /**
  11868. * Initializes a webVR display and starts listening to display change events.
  11869. * The onVRDisplayChangedObservable will be notified upon these changes.
  11870. * @returns A promise containing a VRDisplay and if vr is supported.
  11871. */
  11872. Engine.prototype.initWebVRAsync = function () {
  11873. var _this = this;
  11874. var notifyObservers = function () {
  11875. var eventArgs = {
  11876. vrDisplay: _this._vrDisplay,
  11877. vrSupported: _this._vrSupported
  11878. };
  11879. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  11880. _this._webVRInitPromise = new Promise(function (res) { res(eventArgs); });
  11881. };
  11882. if (!this._onVrDisplayConnect) {
  11883. this._onVrDisplayConnect = function (event) {
  11884. _this._vrDisplay = event.display;
  11885. notifyObservers();
  11886. };
  11887. this._onVrDisplayDisconnect = function () {
  11888. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  11889. _this._vrDisplay = undefined;
  11890. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  11891. notifyObservers();
  11892. };
  11893. this._onVrDisplayPresentChange = function () {
  11894. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  11895. };
  11896. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  11897. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  11898. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  11899. }
  11900. this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync();
  11901. this._webVRInitPromise.then(notifyObservers);
  11902. return this._webVRInitPromise;
  11903. };
  11904. Engine.prototype.enableVR = function () {
  11905. var _this = this;
  11906. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  11907. var onResolved = function () {
  11908. _this.onVRRequestPresentComplete.notifyObservers(true);
  11909. _this._onVRFullScreenTriggered();
  11910. };
  11911. var onRejected = function () {
  11912. _this.onVRRequestPresentComplete.notifyObservers(false);
  11913. };
  11914. this.onVRRequestPresentStart.notifyObservers(this);
  11915. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  11916. }
  11917. };
  11918. Engine.prototype.disableVR = function () {
  11919. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  11920. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  11921. }
  11922. };
  11923. Engine.prototype._getVRDisplaysAsync = function () {
  11924. var _this = this;
  11925. return new Promise(function (res, rej) {
  11926. if (navigator.getVRDisplays) {
  11927. navigator.getVRDisplays().then(function (devices) {
  11928. _this._vrSupported = true;
  11929. // note that devices may actually be an empty array. This is fine;
  11930. // we expect this._vrDisplay to be undefined in this case.
  11931. _this._vrDisplay = devices[0];
  11932. res({
  11933. vrDisplay: _this._vrDisplay,
  11934. vrSupported: _this._vrSupported
  11935. });
  11936. });
  11937. }
  11938. else {
  11939. _this._vrDisplay = undefined;
  11940. _this._vrSupported = false;
  11941. res({
  11942. vrDisplay: _this._vrDisplay,
  11943. vrSupported: _this._vrSupported
  11944. });
  11945. }
  11946. });
  11947. };
  11948. /**
  11949. * Binds the frame buffer to the specified texture.
  11950. * @param texture The texture to render to or null for the default canvas
  11951. * @param faceIndex The face of the texture to render to in case of cube texture
  11952. * @param requiredWidth The width of the target to render to
  11953. * @param requiredHeight The height of the target to render to
  11954. * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true
  11955. * @param depthStencilTexture The depth stencil texture to use to render
  11956. */
  11957. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport, depthStencilTexture) {
  11958. if (this._currentRenderTarget) {
  11959. this.unBindFramebuffer(this._currentRenderTarget);
  11960. }
  11961. this._currentRenderTarget = texture;
  11962. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  11963. var gl = this._gl;
  11964. if (texture.isCube) {
  11965. if (faceIndex === undefined) {
  11966. faceIndex = 0;
  11967. }
  11968. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  11969. if (depthStencilTexture) {
  11970. if (depthStencilTexture._generateStencilBuffer) {
  11971. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture, 0);
  11972. }
  11973. else {
  11974. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture, 0);
  11975. }
  11976. }
  11977. }
  11978. if (this._cachedViewport && !forceFullscreenViewport) {
  11979. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  11980. }
  11981. else {
  11982. gl.viewport(0, 0, requiredWidth || texture.width, requiredHeight || texture.height);
  11983. }
  11984. this.wipeCaches();
  11985. };
  11986. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  11987. if (this._currentFramebuffer !== framebuffer) {
  11988. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  11989. this._currentFramebuffer = framebuffer;
  11990. }
  11991. };
  11992. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  11993. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  11994. this._currentRenderTarget = null;
  11995. // If MSAA, we need to bitblt back to main texture
  11996. var gl = this._gl;
  11997. if (texture._MSAAFramebuffer) {
  11998. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  11999. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  12000. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  12001. }
  12002. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  12003. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  12004. gl.generateMipmap(gl.TEXTURE_2D);
  12005. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  12006. }
  12007. if (onBeforeUnbind) {
  12008. if (texture._MSAAFramebuffer) {
  12009. // Bind the correct framebuffer
  12010. this.bindUnboundFramebuffer(texture._framebuffer);
  12011. }
  12012. onBeforeUnbind();
  12013. }
  12014. this.bindUnboundFramebuffer(null);
  12015. };
  12016. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  12017. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  12018. this._currentRenderTarget = null;
  12019. // If MSAA, we need to bitblt back to main texture
  12020. var gl = this._gl;
  12021. if (textures[0]._MSAAFramebuffer) {
  12022. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  12023. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  12024. var attachments = textures[0]._attachments;
  12025. if (!attachments) {
  12026. attachments = new Array(textures.length);
  12027. textures[0]._attachments = attachments;
  12028. }
  12029. for (var i = 0; i < textures.length; i++) {
  12030. var texture = textures[i];
  12031. for (var j = 0; j < attachments.length; j++) {
  12032. attachments[j] = gl.NONE;
  12033. }
  12034. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  12035. gl.readBuffer(attachments[i]);
  12036. gl.drawBuffers(attachments);
  12037. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  12038. }
  12039. for (var i = 0; i < attachments.length; i++) {
  12040. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  12041. }
  12042. gl.drawBuffers(attachments);
  12043. }
  12044. for (var i = 0; i < textures.length; i++) {
  12045. var texture = textures[i];
  12046. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  12047. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  12048. gl.generateMipmap(gl.TEXTURE_2D);
  12049. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  12050. }
  12051. }
  12052. if (onBeforeUnbind) {
  12053. if (textures[0]._MSAAFramebuffer) {
  12054. // Bind the correct framebuffer
  12055. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  12056. }
  12057. onBeforeUnbind();
  12058. }
  12059. this.bindUnboundFramebuffer(null);
  12060. };
  12061. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  12062. if (texture.generateMipMaps) {
  12063. var gl = this._gl;
  12064. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12065. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  12066. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  12067. }
  12068. };
  12069. Engine.prototype.flushFramebuffer = function () {
  12070. this._gl.flush();
  12071. };
  12072. Engine.prototype.restoreDefaultFramebuffer = function () {
  12073. if (this._currentRenderTarget) {
  12074. this.unBindFramebuffer(this._currentRenderTarget);
  12075. }
  12076. else {
  12077. this.bindUnboundFramebuffer(null);
  12078. }
  12079. if (this._cachedViewport) {
  12080. this.setViewport(this._cachedViewport);
  12081. }
  12082. this.wipeCaches();
  12083. };
  12084. // UBOs
  12085. Engine.prototype.createUniformBuffer = function (elements) {
  12086. var ubo = this._gl.createBuffer();
  12087. if (!ubo) {
  12088. throw new Error("Unable to create uniform buffer");
  12089. }
  12090. this.bindUniformBuffer(ubo);
  12091. if (elements instanceof Float32Array) {
  12092. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  12093. }
  12094. else {
  12095. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  12096. }
  12097. this.bindUniformBuffer(null);
  12098. ubo.references = 1;
  12099. return ubo;
  12100. };
  12101. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  12102. var ubo = this._gl.createBuffer();
  12103. if (!ubo) {
  12104. throw new Error("Unable to create dynamic uniform buffer");
  12105. }
  12106. this.bindUniformBuffer(ubo);
  12107. if (elements instanceof Float32Array) {
  12108. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  12109. }
  12110. else {
  12111. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  12112. }
  12113. this.bindUniformBuffer(null);
  12114. ubo.references = 1;
  12115. return ubo;
  12116. };
  12117. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  12118. this.bindUniformBuffer(uniformBuffer);
  12119. if (offset === undefined) {
  12120. offset = 0;
  12121. }
  12122. if (count === undefined) {
  12123. if (elements instanceof Float32Array) {
  12124. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  12125. }
  12126. else {
  12127. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  12128. }
  12129. }
  12130. else {
  12131. if (elements instanceof Float32Array) {
  12132. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  12133. }
  12134. else {
  12135. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  12136. }
  12137. }
  12138. this.bindUniformBuffer(null);
  12139. };
  12140. // VBOs
  12141. Engine.prototype._resetVertexBufferBinding = function () {
  12142. this.bindArrayBuffer(null);
  12143. this._cachedVertexBuffers = null;
  12144. };
  12145. Engine.prototype.createVertexBuffer = function (vertices) {
  12146. var vbo = this._gl.createBuffer();
  12147. if (!vbo) {
  12148. throw new Error("Unable to create vertex buffer");
  12149. }
  12150. this.bindArrayBuffer(vbo);
  12151. if (vertices instanceof Float32Array) {
  12152. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  12153. }
  12154. else {
  12155. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  12156. }
  12157. this._resetVertexBufferBinding();
  12158. vbo.references = 1;
  12159. return vbo;
  12160. };
  12161. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  12162. var vbo = this._gl.createBuffer();
  12163. if (!vbo) {
  12164. throw new Error("Unable to create dynamic vertex buffer");
  12165. }
  12166. this.bindArrayBuffer(vbo);
  12167. if (vertices instanceof Float32Array) {
  12168. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  12169. }
  12170. else {
  12171. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  12172. }
  12173. this._resetVertexBufferBinding();
  12174. vbo.references = 1;
  12175. return vbo;
  12176. };
  12177. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  12178. if (offset === void 0) { offset = 0; }
  12179. // Force cache update
  12180. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  12181. this.bindIndexBuffer(indexBuffer);
  12182. var arrayBuffer;
  12183. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  12184. arrayBuffer = indices;
  12185. }
  12186. else {
  12187. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  12188. }
  12189. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  12190. this._resetIndexBufferBinding();
  12191. };
  12192. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  12193. this.bindArrayBuffer(vertexBuffer);
  12194. if (offset === undefined) {
  12195. offset = 0;
  12196. }
  12197. if (count === undefined) {
  12198. if (vertices instanceof Float32Array) {
  12199. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  12200. }
  12201. else {
  12202. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  12203. }
  12204. }
  12205. else {
  12206. if (vertices instanceof Float32Array) {
  12207. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  12208. }
  12209. else {
  12210. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  12211. }
  12212. }
  12213. this._resetVertexBufferBinding();
  12214. };
  12215. Engine.prototype._resetIndexBufferBinding = function () {
  12216. this.bindIndexBuffer(null);
  12217. this._cachedIndexBuffer = null;
  12218. };
  12219. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  12220. var vbo = this._gl.createBuffer();
  12221. if (!vbo) {
  12222. throw new Error("Unable to create index buffer");
  12223. }
  12224. this.bindIndexBuffer(vbo);
  12225. // Check for 32 bits indices
  12226. var arrayBuffer;
  12227. var need32Bits = false;
  12228. if (indices instanceof Uint16Array) {
  12229. arrayBuffer = indices;
  12230. }
  12231. else {
  12232. //check 32 bit support
  12233. if (this._caps.uintIndices) {
  12234. if (indices instanceof Uint32Array) {
  12235. arrayBuffer = indices;
  12236. need32Bits = true;
  12237. }
  12238. else {
  12239. //number[] or Int32Array, check if 32 bit is necessary
  12240. for (var index = 0; index < indices.length; index++) {
  12241. if (indices[index] > 65535) {
  12242. need32Bits = true;
  12243. break;
  12244. }
  12245. }
  12246. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  12247. }
  12248. }
  12249. else {
  12250. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  12251. arrayBuffer = new Uint16Array(indices);
  12252. }
  12253. }
  12254. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  12255. this._resetIndexBufferBinding();
  12256. vbo.references = 1;
  12257. vbo.is32Bits = need32Bits;
  12258. return vbo;
  12259. };
  12260. Engine.prototype.bindArrayBuffer = function (buffer) {
  12261. if (!this._vaoRecordInProgress) {
  12262. this._unbindVertexArrayObject();
  12263. }
  12264. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  12265. };
  12266. Engine.prototype.bindUniformBuffer = function (buffer) {
  12267. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  12268. };
  12269. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  12270. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  12271. };
  12272. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  12273. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  12274. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  12275. };
  12276. ;
  12277. Engine.prototype.bindIndexBuffer = function (buffer) {
  12278. if (!this._vaoRecordInProgress) {
  12279. this._unbindVertexArrayObject();
  12280. }
  12281. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  12282. };
  12283. Engine.prototype.bindBuffer = function (buffer, target) {
  12284. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  12285. this._gl.bindBuffer(target, buffer);
  12286. this._currentBoundBuffer[target] = buffer;
  12287. }
  12288. };
  12289. Engine.prototype.updateArrayBuffer = function (data) {
  12290. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  12291. };
  12292. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  12293. var pointer = this._currentBufferPointers[indx];
  12294. var changed = false;
  12295. if (!pointer.active) {
  12296. changed = true;
  12297. pointer.active = true;
  12298. pointer.index = indx;
  12299. pointer.size = size;
  12300. pointer.type = type;
  12301. pointer.normalized = normalized;
  12302. pointer.stride = stride;
  12303. pointer.offset = offset;
  12304. pointer.buffer = buffer;
  12305. }
  12306. else {
  12307. if (pointer.buffer !== buffer) {
  12308. pointer.buffer = buffer;
  12309. changed = true;
  12310. }
  12311. if (pointer.size !== size) {
  12312. pointer.size = size;
  12313. changed = true;
  12314. }
  12315. if (pointer.type !== type) {
  12316. pointer.type = type;
  12317. changed = true;
  12318. }
  12319. if (pointer.normalized !== normalized) {
  12320. pointer.normalized = normalized;
  12321. changed = true;
  12322. }
  12323. if (pointer.stride !== stride) {
  12324. pointer.stride = stride;
  12325. changed = true;
  12326. }
  12327. if (pointer.offset !== offset) {
  12328. pointer.offset = offset;
  12329. changed = true;
  12330. }
  12331. }
  12332. if (changed || this._vaoRecordInProgress) {
  12333. this.bindArrayBuffer(buffer);
  12334. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  12335. }
  12336. };
  12337. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  12338. if (indexBuffer == null) {
  12339. return;
  12340. }
  12341. if (this._cachedIndexBuffer !== indexBuffer) {
  12342. this._cachedIndexBuffer = indexBuffer;
  12343. this.bindIndexBuffer(indexBuffer);
  12344. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  12345. }
  12346. };
  12347. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  12348. var attributes = effect.getAttributesNames();
  12349. if (!this._vaoRecordInProgress) {
  12350. this._unbindVertexArrayObject();
  12351. }
  12352. this.unbindAllAttributes();
  12353. for (var index = 0; index < attributes.length; index++) {
  12354. var order = effect.getAttributeLocation(index);
  12355. if (order >= 0) {
  12356. var vertexBuffer = vertexBuffers[attributes[index]];
  12357. if (!vertexBuffer) {
  12358. continue;
  12359. }
  12360. this._gl.enableVertexAttribArray(order);
  12361. if (!this._vaoRecordInProgress) {
  12362. this._vertexAttribArraysEnabled[order] = true;
  12363. }
  12364. var buffer = vertexBuffer.getBuffer();
  12365. if (buffer) {
  12366. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  12367. if (vertexBuffer.getIsInstanced()) {
  12368. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  12369. if (!this._vaoRecordInProgress) {
  12370. this._currentInstanceLocations.push(order);
  12371. this._currentInstanceBuffers.push(buffer);
  12372. }
  12373. }
  12374. }
  12375. }
  12376. }
  12377. };
  12378. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  12379. var vao = this._gl.createVertexArray();
  12380. this._vaoRecordInProgress = true;
  12381. this._gl.bindVertexArray(vao);
  12382. this._mustWipeVertexAttributes = true;
  12383. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  12384. this.bindIndexBuffer(indexBuffer);
  12385. this._vaoRecordInProgress = false;
  12386. this._gl.bindVertexArray(null);
  12387. return vao;
  12388. };
  12389. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  12390. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  12391. this._cachedVertexArrayObject = vertexArrayObject;
  12392. this._gl.bindVertexArray(vertexArrayObject);
  12393. this._cachedVertexBuffers = null;
  12394. this._cachedIndexBuffer = null;
  12395. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  12396. this._mustWipeVertexAttributes = true;
  12397. }
  12398. };
  12399. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  12400. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  12401. this._cachedVertexBuffers = vertexBuffer;
  12402. this._cachedEffectForVertexBuffers = effect;
  12403. var attributesCount = effect.getAttributesCount();
  12404. this._unbindVertexArrayObject();
  12405. this.unbindAllAttributes();
  12406. var offset = 0;
  12407. for (var index = 0; index < attributesCount; index++) {
  12408. if (index < vertexDeclaration.length) {
  12409. var order = effect.getAttributeLocation(index);
  12410. if (order >= 0) {
  12411. this._gl.enableVertexAttribArray(order);
  12412. this._vertexAttribArraysEnabled[order] = true;
  12413. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  12414. }
  12415. offset += vertexDeclaration[index] * 4;
  12416. }
  12417. }
  12418. }
  12419. this._bindIndexBufferWithCache(indexBuffer);
  12420. };
  12421. Engine.prototype._unbindVertexArrayObject = function () {
  12422. if (!this._cachedVertexArrayObject) {
  12423. return;
  12424. }
  12425. this._cachedVertexArrayObject = null;
  12426. this._gl.bindVertexArray(null);
  12427. };
  12428. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  12429. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  12430. this._cachedVertexBuffers = vertexBuffers;
  12431. this._cachedEffectForVertexBuffers = effect;
  12432. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  12433. }
  12434. this._bindIndexBufferWithCache(indexBuffer);
  12435. };
  12436. Engine.prototype.unbindInstanceAttributes = function () {
  12437. var boundBuffer;
  12438. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  12439. var instancesBuffer = this._currentInstanceBuffers[i];
  12440. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  12441. boundBuffer = instancesBuffer;
  12442. this.bindArrayBuffer(instancesBuffer);
  12443. }
  12444. var offsetLocation = this._currentInstanceLocations[i];
  12445. this._gl.vertexAttribDivisor(offsetLocation, 0);
  12446. }
  12447. this._currentInstanceBuffers.length = 0;
  12448. this._currentInstanceLocations.length = 0;
  12449. };
  12450. Engine.prototype.releaseVertexArrayObject = function (vao) {
  12451. this._gl.deleteVertexArray(vao);
  12452. };
  12453. Engine.prototype._releaseBuffer = function (buffer) {
  12454. buffer.references--;
  12455. if (buffer.references === 0) {
  12456. this._gl.deleteBuffer(buffer);
  12457. return true;
  12458. }
  12459. return false;
  12460. };
  12461. Engine.prototype.createInstancesBuffer = function (capacity) {
  12462. var buffer = this._gl.createBuffer();
  12463. if (!buffer) {
  12464. throw new Error("Unable to create instance buffer");
  12465. }
  12466. buffer.capacity = capacity;
  12467. this.bindArrayBuffer(buffer);
  12468. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  12469. return buffer;
  12470. };
  12471. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  12472. this._gl.deleteBuffer(buffer);
  12473. };
  12474. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  12475. this.bindArrayBuffer(instancesBuffer);
  12476. if (data) {
  12477. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  12478. }
  12479. if (offsetLocations[0].index !== undefined) {
  12480. var stride = 0;
  12481. for (var i = 0; i < offsetLocations.length; i++) {
  12482. var ai = offsetLocations[i];
  12483. stride += ai.attributeSize * 4;
  12484. }
  12485. for (var i = 0; i < offsetLocations.length; i++) {
  12486. var ai = offsetLocations[i];
  12487. if (!this._vertexAttribArraysEnabled[ai.index]) {
  12488. this._gl.enableVertexAttribArray(ai.index);
  12489. this._vertexAttribArraysEnabled[ai.index] = true;
  12490. }
  12491. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  12492. this._gl.vertexAttribDivisor(ai.index, 1);
  12493. this._currentInstanceLocations.push(ai.index);
  12494. this._currentInstanceBuffers.push(instancesBuffer);
  12495. }
  12496. }
  12497. else {
  12498. for (var index = 0; index < 4; index++) {
  12499. var offsetLocation = offsetLocations[index];
  12500. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  12501. this._gl.enableVertexAttribArray(offsetLocation);
  12502. this._vertexAttribArraysEnabled[offsetLocation] = true;
  12503. }
  12504. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  12505. this._gl.vertexAttribDivisor(offsetLocation, 1);
  12506. this._currentInstanceLocations.push(offsetLocation);
  12507. this._currentInstanceBuffers.push(instancesBuffer);
  12508. }
  12509. }
  12510. };
  12511. Engine.prototype.applyStates = function () {
  12512. this._depthCullingState.apply(this._gl);
  12513. this._stencilState.apply(this._gl);
  12514. this._alphaState.apply(this._gl);
  12515. };
  12516. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  12517. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  12518. };
  12519. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  12520. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  12521. };
  12522. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  12523. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  12524. };
  12525. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  12526. // Apply states
  12527. this.applyStates();
  12528. this._drawCalls.addCount(1, false);
  12529. // Render
  12530. var drawMode = this.DrawMode(fillMode);
  12531. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  12532. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  12533. if (instancesCount) {
  12534. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  12535. }
  12536. else {
  12537. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  12538. }
  12539. };
  12540. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  12541. // Apply states
  12542. this.applyStates();
  12543. this._drawCalls.addCount(1, false);
  12544. var drawMode = this.DrawMode(fillMode);
  12545. if (instancesCount) {
  12546. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  12547. }
  12548. else {
  12549. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  12550. }
  12551. };
  12552. Engine.prototype.DrawMode = function (fillMode) {
  12553. switch (fillMode) {
  12554. // Triangle views
  12555. case BABYLON.Material.TriangleFillMode:
  12556. return this._gl.TRIANGLES;
  12557. case BABYLON.Material.PointFillMode:
  12558. return this._gl.POINTS;
  12559. case BABYLON.Material.WireFrameFillMode:
  12560. return this._gl.LINES;
  12561. // Draw modes
  12562. case BABYLON.Material.PointListDrawMode:
  12563. return this._gl.POINTS;
  12564. case BABYLON.Material.LineListDrawMode:
  12565. return this._gl.LINES;
  12566. case BABYLON.Material.LineLoopDrawMode:
  12567. return this._gl.LINE_LOOP;
  12568. case BABYLON.Material.LineStripDrawMode:
  12569. return this._gl.LINE_STRIP;
  12570. case BABYLON.Material.TriangleStripDrawMode:
  12571. return this._gl.TRIANGLE_STRIP;
  12572. case BABYLON.Material.TriangleFanDrawMode:
  12573. return this._gl.TRIANGLE_FAN;
  12574. default:
  12575. return this._gl.TRIANGLES;
  12576. }
  12577. };
  12578. // Shaders
  12579. Engine.prototype._releaseEffect = function (effect) {
  12580. if (this._compiledEffects[effect._key]) {
  12581. delete this._compiledEffects[effect._key];
  12582. this._deleteProgram(effect.getProgram());
  12583. }
  12584. };
  12585. Engine.prototype._deleteProgram = function (program) {
  12586. if (program) {
  12587. program.__SPECTOR_rebuildProgram = null;
  12588. if (program.transformFeedback) {
  12589. this.deleteTransformFeedback(program.transformFeedback);
  12590. program.transformFeedback = null;
  12591. }
  12592. this._gl.deleteProgram(program);
  12593. }
  12594. };
  12595. /**
  12596. * @param baseName The base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  12597. * @param samplers An array of string used to represent textures
  12598. */
  12599. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  12600. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  12601. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  12602. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  12603. if (this._compiledEffects[name]) {
  12604. var compiledEffect = this._compiledEffects[name];
  12605. if (onCompiled && compiledEffect.isReady()) {
  12606. onCompiled(compiledEffect);
  12607. }
  12608. return compiledEffect;
  12609. }
  12610. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  12611. effect._key = name;
  12612. this._compiledEffects[name] = effect;
  12613. return effect;
  12614. };
  12615. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  12616. if (uniformsNames === void 0) { uniformsNames = []; }
  12617. if (samplers === void 0) { samplers = []; }
  12618. if (defines === void 0) { defines = ""; }
  12619. return this.createEffect({
  12620. vertex: "particles",
  12621. fragmentElement: fragmentName
  12622. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  12623. };
  12624. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  12625. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  12626. context = context || this._gl;
  12627. var vertexShader = compileRawShader(context, vertexCode, "vertex");
  12628. var fragmentShader = compileRawShader(context, fragmentCode, "fragment");
  12629. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  12630. };
  12631. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  12632. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  12633. context = context || this._gl;
  12634. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  12635. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n" : "";
  12636. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  12637. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  12638. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  12639. this.onAfterShaderCompilationObservable.notifyObservers(this);
  12640. return program;
  12641. };
  12642. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  12643. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  12644. var shaderProgram = context.createProgram();
  12645. if (!shaderProgram) {
  12646. throw new Error("Unable to create program");
  12647. }
  12648. context.attachShader(shaderProgram, vertexShader);
  12649. context.attachShader(shaderProgram, fragmentShader);
  12650. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  12651. var transformFeedback = this.createTransformFeedback();
  12652. this.bindTransformFeedback(transformFeedback);
  12653. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  12654. shaderProgram.transformFeedback = transformFeedback;
  12655. }
  12656. context.linkProgram(shaderProgram);
  12657. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  12658. this.bindTransformFeedback(null);
  12659. }
  12660. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  12661. if (!linked) {
  12662. context.validateProgram(shaderProgram);
  12663. var error = context.getProgramInfoLog(shaderProgram);
  12664. if (error) {
  12665. throw new Error(error);
  12666. }
  12667. }
  12668. context.deleteShader(vertexShader);
  12669. context.deleteShader(fragmentShader);
  12670. return shaderProgram;
  12671. };
  12672. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  12673. var results = new Array();
  12674. for (var index = 0; index < uniformsNames.length; index++) {
  12675. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  12676. }
  12677. return results;
  12678. };
  12679. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  12680. var results = [];
  12681. for (var index = 0; index < attributesNames.length; index++) {
  12682. try {
  12683. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  12684. }
  12685. catch (e) {
  12686. results.push(-1);
  12687. }
  12688. }
  12689. return results;
  12690. };
  12691. Engine.prototype.enableEffect = function (effect) {
  12692. if (!effect) {
  12693. return;
  12694. }
  12695. // Use program
  12696. this.bindSamplers(effect);
  12697. this._currentEffect = effect;
  12698. if (effect.onBind) {
  12699. effect.onBind(effect);
  12700. }
  12701. effect.onBindObservable.notifyObservers(effect);
  12702. };
  12703. Engine.prototype.setIntArray = function (uniform, array) {
  12704. if (!uniform)
  12705. return;
  12706. this._gl.uniform1iv(uniform, array);
  12707. };
  12708. Engine.prototype.setIntArray2 = function (uniform, array) {
  12709. if (!uniform || array.length % 2 !== 0)
  12710. return;
  12711. this._gl.uniform2iv(uniform, array);
  12712. };
  12713. Engine.prototype.setIntArray3 = function (uniform, array) {
  12714. if (!uniform || array.length % 3 !== 0)
  12715. return;
  12716. this._gl.uniform3iv(uniform, array);
  12717. };
  12718. Engine.prototype.setIntArray4 = function (uniform, array) {
  12719. if (!uniform || array.length % 4 !== 0)
  12720. return;
  12721. this._gl.uniform4iv(uniform, array);
  12722. };
  12723. Engine.prototype.setFloatArray = function (uniform, array) {
  12724. if (!uniform)
  12725. return;
  12726. this._gl.uniform1fv(uniform, array);
  12727. };
  12728. Engine.prototype.setFloatArray2 = function (uniform, array) {
  12729. if (!uniform || array.length % 2 !== 0)
  12730. return;
  12731. this._gl.uniform2fv(uniform, array);
  12732. };
  12733. Engine.prototype.setFloatArray3 = function (uniform, array) {
  12734. if (!uniform || array.length % 3 !== 0)
  12735. return;
  12736. this._gl.uniform3fv(uniform, array);
  12737. };
  12738. Engine.prototype.setFloatArray4 = function (uniform, array) {
  12739. if (!uniform || array.length % 4 !== 0)
  12740. return;
  12741. this._gl.uniform4fv(uniform, array);
  12742. };
  12743. Engine.prototype.setArray = function (uniform, array) {
  12744. if (!uniform)
  12745. return;
  12746. this._gl.uniform1fv(uniform, array);
  12747. };
  12748. Engine.prototype.setArray2 = function (uniform, array) {
  12749. if (!uniform || array.length % 2 !== 0)
  12750. return;
  12751. this._gl.uniform2fv(uniform, array);
  12752. };
  12753. Engine.prototype.setArray3 = function (uniform, array) {
  12754. if (!uniform || array.length % 3 !== 0)
  12755. return;
  12756. this._gl.uniform3fv(uniform, array);
  12757. };
  12758. Engine.prototype.setArray4 = function (uniform, array) {
  12759. if (!uniform || array.length % 4 !== 0)
  12760. return;
  12761. this._gl.uniform4fv(uniform, array);
  12762. };
  12763. Engine.prototype.setMatrices = function (uniform, matrices) {
  12764. if (!uniform)
  12765. return;
  12766. this._gl.uniformMatrix4fv(uniform, false, matrices);
  12767. };
  12768. Engine.prototype.setMatrix = function (uniform, matrix) {
  12769. if (!uniform)
  12770. return;
  12771. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  12772. };
  12773. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  12774. if (!uniform)
  12775. return;
  12776. this._gl.uniformMatrix3fv(uniform, false, matrix);
  12777. };
  12778. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  12779. if (!uniform)
  12780. return;
  12781. this._gl.uniformMatrix2fv(uniform, false, matrix);
  12782. };
  12783. Engine.prototype.setInt = function (uniform, value) {
  12784. if (!uniform)
  12785. return;
  12786. this._gl.uniform1i(uniform, value);
  12787. };
  12788. Engine.prototype.setFloat = function (uniform, value) {
  12789. if (!uniform)
  12790. return;
  12791. this._gl.uniform1f(uniform, value);
  12792. };
  12793. Engine.prototype.setFloat2 = function (uniform, x, y) {
  12794. if (!uniform)
  12795. return;
  12796. this._gl.uniform2f(uniform, x, y);
  12797. };
  12798. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  12799. if (!uniform)
  12800. return;
  12801. this._gl.uniform3f(uniform, x, y, z);
  12802. };
  12803. Engine.prototype.setBool = function (uniform, bool) {
  12804. if (!uniform)
  12805. return;
  12806. this._gl.uniform1i(uniform, bool);
  12807. };
  12808. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  12809. if (!uniform)
  12810. return;
  12811. this._gl.uniform4f(uniform, x, y, z, w);
  12812. };
  12813. Engine.prototype.setColor3 = function (uniform, color3) {
  12814. if (!uniform)
  12815. return;
  12816. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  12817. };
  12818. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  12819. if (!uniform)
  12820. return;
  12821. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  12822. };
  12823. /**
  12824. * Sets a Color4 on a uniform variable
  12825. * @param uniform defines the uniform location
  12826. * @param color4 defines the value to be set
  12827. */
  12828. Engine.prototype.setDirectColor4 = function (uniform, color4) {
  12829. if (!uniform)
  12830. return;
  12831. this._gl.uniform4f(uniform, color4.r, color4.g, color4.b, color4.a);
  12832. };
  12833. // States
  12834. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  12835. if (zOffset === void 0) { zOffset = 0; }
  12836. if (reverseSide === void 0) { reverseSide = false; }
  12837. // Culling
  12838. if (this._depthCullingState.cull !== culling || force) {
  12839. this._depthCullingState.cull = culling;
  12840. }
  12841. // Cull face
  12842. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  12843. if (this._depthCullingState.cullFace !== cullFace || force) {
  12844. this._depthCullingState.cullFace = cullFace;
  12845. }
  12846. // Z offset
  12847. this.setZOffset(zOffset);
  12848. // Front face
  12849. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  12850. if (this._depthCullingState.frontFace !== frontFace || force) {
  12851. this._depthCullingState.frontFace = frontFace;
  12852. }
  12853. };
  12854. Engine.prototype.setZOffset = function (value) {
  12855. this._depthCullingState.zOffset = value;
  12856. };
  12857. Engine.prototype.getZOffset = function () {
  12858. return this._depthCullingState.zOffset;
  12859. };
  12860. Engine.prototype.setDepthBuffer = function (enable) {
  12861. this._depthCullingState.depthTest = enable;
  12862. };
  12863. Engine.prototype.getDepthWrite = function () {
  12864. return this._depthCullingState.depthMask;
  12865. };
  12866. Engine.prototype.setDepthWrite = function (enable) {
  12867. this._depthCullingState.depthMask = enable;
  12868. };
  12869. Engine.prototype.setColorWrite = function (enable) {
  12870. this._gl.colorMask(enable, enable, enable, enable);
  12871. this._colorWrite = enable;
  12872. };
  12873. Engine.prototype.getColorWrite = function () {
  12874. return this._colorWrite;
  12875. };
  12876. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  12877. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  12878. };
  12879. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  12880. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  12881. if (this._alphaMode === mode) {
  12882. return;
  12883. }
  12884. switch (mode) {
  12885. case Engine.ALPHA_DISABLE:
  12886. this._alphaState.alphaBlend = false;
  12887. break;
  12888. case Engine.ALPHA_PREMULTIPLIED:
  12889. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  12890. this._alphaState.alphaBlend = true;
  12891. break;
  12892. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  12893. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  12894. this._alphaState.alphaBlend = true;
  12895. break;
  12896. case Engine.ALPHA_COMBINE:
  12897. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  12898. this._alphaState.alphaBlend = true;
  12899. break;
  12900. case Engine.ALPHA_ONEONE:
  12901. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  12902. this._alphaState.alphaBlend = true;
  12903. break;
  12904. case Engine.ALPHA_ADD:
  12905. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  12906. this._alphaState.alphaBlend = true;
  12907. break;
  12908. case Engine.ALPHA_SUBTRACT:
  12909. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  12910. this._alphaState.alphaBlend = true;
  12911. break;
  12912. case Engine.ALPHA_MULTIPLY:
  12913. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  12914. this._alphaState.alphaBlend = true;
  12915. break;
  12916. case Engine.ALPHA_MAXIMIZED:
  12917. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  12918. this._alphaState.alphaBlend = true;
  12919. break;
  12920. case Engine.ALPHA_INTERPOLATE:
  12921. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  12922. this._alphaState.alphaBlend = true;
  12923. break;
  12924. case Engine.ALPHA_SCREENMODE:
  12925. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  12926. this._alphaState.alphaBlend = true;
  12927. break;
  12928. }
  12929. if (!noDepthWriteChange) {
  12930. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  12931. }
  12932. this._alphaMode = mode;
  12933. };
  12934. Engine.prototype.getAlphaMode = function () {
  12935. return this._alphaMode;
  12936. };
  12937. // Textures
  12938. Engine.prototype.wipeCaches = function (bruteForce) {
  12939. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  12940. return;
  12941. }
  12942. this._currentEffect = null;
  12943. // 6/8/2017: deltakosh: Should not be required anymore.
  12944. // This message is then mostly for the future myself who will scream out loud when seeing that it was actually required :)
  12945. if (bruteForce) {
  12946. this.resetTextureCache();
  12947. this._currentProgram = null;
  12948. this._stencilState.reset();
  12949. this._depthCullingState.reset();
  12950. this.setDepthFunctionToLessOrEqual();
  12951. this._alphaState.reset();
  12952. }
  12953. this._resetVertexBufferBinding();
  12954. this._cachedIndexBuffer = null;
  12955. this._cachedEffectForVertexBuffers = null;
  12956. this._unbindVertexArrayObject();
  12957. this.bindIndexBuffer(null);
  12958. };
  12959. /**
  12960. * Set the compressed texture format to use, based on the formats you have, and the formats
  12961. * supported by the hardware / browser.
  12962. *
  12963. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  12964. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  12965. * to API arguments needed to compressed textures. This puts the burden on the container
  12966. * generator to house the arcane code for determining these for current & future formats.
  12967. *
  12968. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  12969. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  12970. *
  12971. * Note: The result of this call is not taken into account when a texture is base64.
  12972. *
  12973. * @param {Array<string>} formatsAvailable- The list of those format families you have created
  12974. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  12975. *
  12976. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  12977. * @returns The extension selected.
  12978. */
  12979. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  12980. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  12981. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  12982. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  12983. return this._textureFormatInUse = this._texturesSupported[i];
  12984. }
  12985. }
  12986. }
  12987. // actively set format to nothing, to allow this to be called more than once
  12988. // and possibly fail the 2nd time
  12989. this._textureFormatInUse = null;
  12990. return null;
  12991. };
  12992. Engine.prototype._createTexture = function () {
  12993. var texture = this._gl.createTexture();
  12994. if (!texture) {
  12995. throw new Error("Unable to create texture");
  12996. }
  12997. return texture;
  12998. };
  12999. /**
  13000. * Usually called from BABYLON.Texture.ts. Passed information to create a WebGLTexture.
  13001. * @param {string} urlArg- This contains one of the following:
  13002. * 1. A conventional http URL, e.g. 'http://...' or 'file://...'
  13003. * 2. A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  13004. * 3. An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  13005. *
  13006. * @param {boolean} noMipmap- When true, no mipmaps shall be generated. Ignored for compressed textures. They must be in the file.
  13007. * @param {boolean} invertY- When true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file.
  13008. * @param {Scene} scene- Needed for loading to the correct scene.
  13009. * @param {number} samplingMode- Mode with should be used sample / access the texture. Default: TRILINEAR
  13010. * @param {callback} onLoad- Optional callback to be called upon successful completion.
  13011. * @param {callback} onError- Optional callback to be called upon failure.
  13012. * @param {ArrayBuffer | HTMLImageElement} buffer- A source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  13013. * @param {WebGLTexture} fallback- An internal argument in case the function must be called again, due to etc1 not having alpha capabilities.
  13014. * @param {number} format- Internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures.
  13015. *
  13016. * @returns {WebGLTexture} for assignment back into BABYLON.Texture
  13017. */
  13018. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  13019. var _this = this;
  13020. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  13021. if (onLoad === void 0) { onLoad = null; }
  13022. if (onError === void 0) { onError = null; }
  13023. if (buffer === void 0) { buffer = null; }
  13024. if (fallBack === void 0) { fallBack = null; }
  13025. if (format === void 0) { format = null; }
  13026. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  13027. var fromData = url.substr(0, 5) === "data:";
  13028. var fromBlob = url.substr(0, 5) === "blob:";
  13029. var isBase64 = fromData && url.indexOf("base64") !== -1;
  13030. var texture = fallBack ? fallBack : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  13031. // establish the file extension, if possible
  13032. var lastDot = url.lastIndexOf('.');
  13033. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  13034. var isDDS = this.getCaps().s3tc && (extension.indexOf(".dds") === 0);
  13035. var isTGA = (extension.indexOf(".tga") === 0);
  13036. // determine if a ktx file should be substituted
  13037. var isKTX = false;
  13038. if (this._textureFormatInUse && !isBase64 && !fallBack) {
  13039. url = url.substring(0, lastDot) + this._textureFormatInUse;
  13040. isKTX = true;
  13041. }
  13042. if (scene) {
  13043. scene._addPendingData(texture);
  13044. }
  13045. texture.url = url;
  13046. texture.generateMipMaps = !noMipmap;
  13047. texture.samplingMode = samplingMode;
  13048. texture.invertY = invertY;
  13049. if (!this._doNotHandleContextLost) {
  13050. // Keep a link to the buffer only if we plan to handle context lost
  13051. texture._buffer = buffer;
  13052. }
  13053. var onLoadObserver = null;
  13054. if (onLoad && !fallBack) {
  13055. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  13056. }
  13057. if (!fallBack)
  13058. this._internalTexturesCache.push(texture);
  13059. var onerror = function (message, exception) {
  13060. if (scene) {
  13061. scene._removePendingData(texture);
  13062. }
  13063. if (onLoadObserver) {
  13064. texture.onLoadedObservable.remove(onLoadObserver);
  13065. }
  13066. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  13067. if (isKTX) {
  13068. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  13069. }
  13070. else if (BABYLON.Tools.UseFallbackTexture) {
  13071. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  13072. }
  13073. if (onError) {
  13074. onError(message || "Unknown error", exception);
  13075. }
  13076. };
  13077. var callback = null;
  13078. // processing for non-image formats
  13079. if (isKTX || isTGA || isDDS) {
  13080. if (isKTX) {
  13081. callback = function (data) {
  13082. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  13083. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  13084. ktx.uploadLevels(_this._gl, !noMipmap);
  13085. return false;
  13086. }, samplingMode);
  13087. };
  13088. }
  13089. else if (isTGA) {
  13090. callback = function (arrayBuffer) {
  13091. var data = new Uint8Array(arrayBuffer);
  13092. var header = BABYLON.TGATools.GetTGAHeader(data);
  13093. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  13094. BABYLON.TGATools.UploadContent(_this._gl, data);
  13095. return false;
  13096. }, samplingMode);
  13097. };
  13098. }
  13099. else if (isDDS) {
  13100. callback = function (data) {
  13101. var info = BABYLON.DDSTools.GetDDSInfo(data);
  13102. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  13103. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  13104. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  13105. return false;
  13106. }, samplingMode);
  13107. };
  13108. }
  13109. if (!buffer) {
  13110. this._loadFile(url, function (data) {
  13111. if (callback) {
  13112. callback(data);
  13113. }
  13114. }, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  13115. onerror("Unable to load " + (request ? request.responseURL : url, exception));
  13116. });
  13117. }
  13118. else {
  13119. if (callback) {
  13120. callback(buffer);
  13121. }
  13122. }
  13123. // image format processing
  13124. }
  13125. else {
  13126. var onload = function (img) {
  13127. if (fromBlob && !_this._doNotHandleContextLost) {
  13128. // We need to store the image if we need to rebuild the texture
  13129. // in case of a webgl context lost
  13130. texture._buffer = img;
  13131. }
  13132. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  13133. var gl = _this._gl;
  13134. var isPot = (img.width === potWidth && img.height === potHeight);
  13135. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  13136. if (isPot) {
  13137. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  13138. return false;
  13139. }
  13140. // Using shaders to rescale because canvas.drawImage is lossy
  13141. var source = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  13142. _this._bindTextureDirectly(gl.TEXTURE_2D, source, true);
  13143. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  13144. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  13145. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  13146. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13147. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13148. _this._rescaleTexture(source, texture, scene, internalFormat, function () {
  13149. _this._releaseTexture(source);
  13150. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13151. continuationCallback();
  13152. });
  13153. return true;
  13154. }, samplingMode);
  13155. };
  13156. if (!fromData || isBase64)
  13157. if (buffer instanceof HTMLImageElement) {
  13158. onload(buffer);
  13159. }
  13160. else {
  13161. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  13162. }
  13163. else if (buffer instanceof Array || typeof buffer === "string" || buffer instanceof ArrayBuffer)
  13164. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  13165. else
  13166. onload(buffer);
  13167. }
  13168. return texture;
  13169. };
  13170. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  13171. var _this = this;
  13172. var rtt = this.createRenderTargetTexture({
  13173. width: destination.width,
  13174. height: destination.height,
  13175. }, {
  13176. generateMipMaps: false,
  13177. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  13178. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  13179. generateDepthBuffer: false,
  13180. generateStencilBuffer: false
  13181. });
  13182. if (!this._rescalePostProcess) {
  13183. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  13184. }
  13185. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  13186. _this._rescalePostProcess.onApply = function (effect) {
  13187. effect._bindTexture("textureSampler", source);
  13188. };
  13189. var hostingScene = scene;
  13190. if (!hostingScene) {
  13191. hostingScene = _this.scenes[_this.scenes.length - 1];
  13192. }
  13193. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  13194. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  13195. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  13196. _this.unBindFramebuffer(rtt);
  13197. _this._releaseTexture(rtt);
  13198. if (onComplete) {
  13199. onComplete();
  13200. }
  13201. });
  13202. };
  13203. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  13204. if (compression === void 0) { compression = null; }
  13205. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  13206. if (!texture) {
  13207. return;
  13208. }
  13209. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format);
  13210. var internalFormat = this._getInternalFormat(format);
  13211. var textureType = this._getWebGLTextureType(type);
  13212. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13213. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  13214. if (!this._doNotHandleContextLost) {
  13215. texture._bufferView = data;
  13216. texture.format = format;
  13217. texture.type = type;
  13218. texture.invertY = invertY;
  13219. texture._compression = compression;
  13220. }
  13221. if (texture.width % 4 !== 0) {
  13222. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  13223. }
  13224. if (compression && data) {
  13225. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  13226. }
  13227. else {
  13228. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  13229. }
  13230. if (texture.generateMipMaps) {
  13231. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13232. }
  13233. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13234. // this.resetTextureCache();
  13235. texture.isReady = true;
  13236. };
  13237. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  13238. if (compression === void 0) { compression = null; }
  13239. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  13240. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  13241. texture.baseWidth = width;
  13242. texture.baseHeight = height;
  13243. texture.width = width;
  13244. texture.height = height;
  13245. texture.format = format;
  13246. texture.generateMipMaps = generateMipMaps;
  13247. texture.samplingMode = samplingMode;
  13248. texture.invertY = invertY;
  13249. texture._compression = compression;
  13250. texture.type = type;
  13251. if (!this._doNotHandleContextLost) {
  13252. texture._bufferView = data;
  13253. }
  13254. this.updateRawTexture(texture, data, format, invertY, compression, type);
  13255. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13256. // Filters
  13257. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  13258. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13259. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13260. if (generateMipMaps) {
  13261. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13262. }
  13263. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13264. this._internalTexturesCache.push(texture);
  13265. return texture;
  13266. };
  13267. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  13268. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  13269. texture.baseWidth = width;
  13270. texture.baseHeight = height;
  13271. if (generateMipMaps) {
  13272. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  13273. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  13274. }
  13275. // this.resetTextureCache();
  13276. texture.width = width;
  13277. texture.height = height;
  13278. texture.isReady = false;
  13279. texture.generateMipMaps = generateMipMaps;
  13280. texture.samplingMode = samplingMode;
  13281. this.updateTextureSamplingMode(samplingMode, texture);
  13282. this._internalTexturesCache.push(texture);
  13283. return texture;
  13284. };
  13285. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  13286. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  13287. if (texture.isCube) {
  13288. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  13289. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13290. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13291. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  13292. }
  13293. else if (texture.is3D) {
  13294. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  13295. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13296. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13297. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  13298. }
  13299. else {
  13300. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13301. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13302. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13303. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13304. }
  13305. texture.samplingMode = samplingMode;
  13306. };
  13307. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  13308. if (premulAlpha === void 0) { premulAlpha = false; }
  13309. if (!texture) {
  13310. return;
  13311. }
  13312. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13313. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  13314. if (premulAlpha) {
  13315. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  13316. }
  13317. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  13318. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  13319. if (texture.generateMipMaps) {
  13320. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13321. }
  13322. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13323. if (premulAlpha) {
  13324. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  13325. }
  13326. texture.isReady = true;
  13327. };
  13328. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  13329. if (!texture || texture._isDisabled) {
  13330. return;
  13331. }
  13332. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13333. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  13334. try {
  13335. // Testing video texture support
  13336. if (this._videoTextureSupported === undefined) {
  13337. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  13338. if (this._gl.getError() !== 0) {
  13339. this._videoTextureSupported = false;
  13340. }
  13341. else {
  13342. this._videoTextureSupported = true;
  13343. }
  13344. }
  13345. // Copy video through the current working canvas if video texture is not supported
  13346. if (!this._videoTextureSupported) {
  13347. if (!texture._workingCanvas) {
  13348. texture._workingCanvas = document.createElement("canvas");
  13349. var context = texture._workingCanvas.getContext("2d");
  13350. if (!context) {
  13351. throw new Error("Unable to get 2d context");
  13352. }
  13353. texture._workingContext = context;
  13354. texture._workingCanvas.width = texture.width;
  13355. texture._workingCanvas.height = texture.height;
  13356. }
  13357. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  13358. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  13359. }
  13360. else {
  13361. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  13362. }
  13363. if (texture.generateMipMaps) {
  13364. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13365. }
  13366. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13367. // this.resetTextureCache();
  13368. texture.isReady = true;
  13369. }
  13370. catch (ex) {
  13371. // Something unexpected
  13372. // Let's disable the texture
  13373. texture._isDisabled = true;
  13374. }
  13375. };
  13376. /**
  13377. * Updates a depth texture Comparison Mode and Function.
  13378. * If the comparison Function is equal to 0, the mode will be set to none.
  13379. * Otherwise, this only works in webgl 2 and requires a shadow sampler in the shader.
  13380. * @param texture The texture to set the comparison function for
  13381. * @param comparisonFunction The comparison function to set, 0 if no comparison required
  13382. */
  13383. Engine.prototype.updateTextureComparisonFunction = function (texture, comparisonFunction) {
  13384. if (this.webGLVersion === 1) {
  13385. BABYLON.Tools.Error("WebGL 1 does not support texture comparison.");
  13386. return;
  13387. }
  13388. var gl = this._gl;
  13389. if (texture.isCube) {
  13390. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  13391. if (comparisonFunction === 0) {
  13392. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  13393. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  13394. }
  13395. else {
  13396. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  13397. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  13398. }
  13399. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  13400. }
  13401. else {
  13402. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13403. if (comparisonFunction === 0) {
  13404. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  13405. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  13406. }
  13407. else {
  13408. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  13409. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  13410. }
  13411. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13412. }
  13413. texture._comparisonFunction = comparisonFunction;
  13414. };
  13415. Engine.prototype._setupDepthStencilTexture = function (internalTexture, size, generateStencil, bilinearFiltering, comparisonFunction) {
  13416. var width = size.width || size;
  13417. var height = size.height || size;
  13418. internalTexture.baseWidth = width;
  13419. internalTexture.baseHeight = height;
  13420. internalTexture.width = width;
  13421. internalTexture.height = height;
  13422. internalTexture.isReady = true;
  13423. internalTexture.samples = 1;
  13424. internalTexture.generateMipMaps = false;
  13425. internalTexture._generateDepthBuffer = true;
  13426. internalTexture._generateStencilBuffer = generateStencil;
  13427. internalTexture.samplingMode = bilinearFiltering ? BABYLON.Texture.NEAREST_SAMPLINGMODE : BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  13428. internalTexture.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13429. internalTexture._comparisonFunction = comparisonFunction;
  13430. var gl = this._gl;
  13431. var target = internalTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  13432. var samplingParameters = getSamplingParameters(internalTexture.samplingMode, false, gl);
  13433. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, samplingParameters.mag);
  13434. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, samplingParameters.min);
  13435. gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13436. gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13437. if (comparisonFunction === 0) {
  13438. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  13439. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  13440. }
  13441. else {
  13442. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  13443. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  13444. }
  13445. };
  13446. /**
  13447. * Creates a depth stencil texture.
  13448. * This is only available in WebGL 2 or with the depth texture extension available.
  13449. * @param size The size of face edge in the texture.
  13450. * @param options The options defining the texture.
  13451. * @returns The texture
  13452. */
  13453. Engine.prototype.createDepthStencilTexture = function (size, options) {
  13454. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DEPTHTEXTURE);
  13455. if (!this._caps.depthTextureExtension) {
  13456. BABYLON.Tools.Error("Depth texture is not supported by your browser or hardware.");
  13457. return internalTexture;
  13458. }
  13459. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  13460. var gl = this._gl;
  13461. this._bindTextureDirectly(gl.TEXTURE_2D, internalTexture, true);
  13462. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  13463. if (this.webGLVersion > 1) {
  13464. if (internalOptions.generateStencil) {
  13465. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH24_STENCIL8, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  13466. }
  13467. else {
  13468. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT24, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  13469. }
  13470. }
  13471. else {
  13472. if (internalOptions.generateStencil) {
  13473. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_STENCIL, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  13474. }
  13475. else {
  13476. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  13477. }
  13478. }
  13479. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13480. return internalTexture;
  13481. };
  13482. /**
  13483. * Creates a depth stencil cube texture.
  13484. * This is only available in WebGL 2.
  13485. * @param size The size of face edge in the cube texture.
  13486. * @param options The options defining the cube texture.
  13487. * @returns The cube texture
  13488. */
  13489. Engine.prototype.createDepthStencilCubeTexture = function (size, options) {
  13490. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_UNKNOWN);
  13491. internalTexture.isCube = true;
  13492. if (this.webGLVersion === 1) {
  13493. BABYLON.Tools.Error("Depth cube texture is not supported by WebGL 1.");
  13494. return internalTexture;
  13495. }
  13496. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  13497. var gl = this._gl;
  13498. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, internalTexture, true);
  13499. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  13500. // Create the depth/stencil buffer
  13501. for (var face = 0; face < 6; face++) {
  13502. if (internalOptions.generateStencil) {
  13503. 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);
  13504. }
  13505. else {
  13506. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH_COMPONENT24, size, size, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  13507. }
  13508. }
  13509. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13510. return internalTexture;
  13511. };
  13512. /**
  13513. * Sets the frame buffer Depth / Stencil attachement of the render target to the defined depth stencil texture.
  13514. * @param renderTarget The render target to set the frame buffer for
  13515. */
  13516. Engine.prototype.setFrameBufferDepthStencilTexture = function (renderTarget) {
  13517. // Create the framebuffer
  13518. var internalTexture = renderTarget.getInternalTexture();
  13519. if (!internalTexture || !internalTexture._framebuffer || !renderTarget.depthStencilTexture) {
  13520. return;
  13521. }
  13522. var gl = this._gl;
  13523. var depthStencilTexture = renderTarget.depthStencilTexture;
  13524. this.bindUnboundFramebuffer(internalTexture._framebuffer);
  13525. if (depthStencilTexture.isCube) {
  13526. if (depthStencilTexture._generateStencilBuffer) {
  13527. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture, 0);
  13528. }
  13529. else {
  13530. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture, 0);
  13531. }
  13532. }
  13533. else {
  13534. if (depthStencilTexture._generateStencilBuffer) {
  13535. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture, 0);
  13536. }
  13537. else {
  13538. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture, 0);
  13539. }
  13540. }
  13541. this.bindUnboundFramebuffer(null);
  13542. };
  13543. Engine.prototype.createRenderTargetTexture = function (size, options) {
  13544. var fullOptions = new RenderTargetCreationOptions();
  13545. if (options !== undefined && typeof options === "object") {
  13546. fullOptions.generateMipMaps = options.generateMipMaps;
  13547. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  13548. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  13549. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  13550. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  13551. fullOptions.format = options.format === undefined ? Engine.TEXTUREFORMAT_RGBA : options.format;
  13552. }
  13553. else {
  13554. fullOptions.generateMipMaps = options;
  13555. fullOptions.generateDepthBuffer = true;
  13556. fullOptions.generateStencilBuffer = false;
  13557. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13558. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  13559. fullOptions.format = Engine.TEXTUREFORMAT_RGBA;
  13560. }
  13561. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  13562. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  13563. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13564. }
  13565. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  13566. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  13567. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13568. }
  13569. var gl = this._gl;
  13570. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  13571. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13572. var width = size.width || size;
  13573. var height = size.height || size;
  13574. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false, gl);
  13575. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  13576. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13577. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  13578. }
  13579. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  13580. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  13581. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13582. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13583. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), width, height, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
  13584. // Create the framebuffer
  13585. var framebuffer = gl.createFramebuffer();
  13586. this.bindUnboundFramebuffer(framebuffer);
  13587. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  13588. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  13589. if (fullOptions.generateMipMaps) {
  13590. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13591. }
  13592. // Unbind
  13593. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13594. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13595. this.bindUnboundFramebuffer(null);
  13596. texture._framebuffer = framebuffer;
  13597. texture.baseWidth = width;
  13598. texture.baseHeight = height;
  13599. texture.width = width;
  13600. texture.height = height;
  13601. texture.isReady = true;
  13602. texture.samples = 1;
  13603. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  13604. texture.samplingMode = fullOptions.samplingMode;
  13605. texture.type = fullOptions.type;
  13606. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  13607. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  13608. // this.resetTextureCache();
  13609. this._internalTexturesCache.push(texture);
  13610. return texture;
  13611. };
  13612. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  13613. var generateMipMaps = false;
  13614. var generateDepthBuffer = true;
  13615. var generateStencilBuffer = false;
  13616. var generateDepthTexture = false;
  13617. var textureCount = 1;
  13618. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  13619. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  13620. var types = [], samplingModes = [];
  13621. if (options !== undefined) {
  13622. generateMipMaps = options.generateMipMaps;
  13623. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  13624. generateStencilBuffer = options.generateStencilBuffer;
  13625. generateDepthTexture = options.generateDepthTexture;
  13626. textureCount = options.textureCount || 1;
  13627. if (options.types) {
  13628. types = options.types;
  13629. }
  13630. if (options.samplingModes) {
  13631. samplingModes = options.samplingModes;
  13632. }
  13633. }
  13634. var gl = this._gl;
  13635. // Create the framebuffer
  13636. var framebuffer = gl.createFramebuffer();
  13637. this.bindUnboundFramebuffer(framebuffer);
  13638. var width = size.width || size;
  13639. var height = size.height || size;
  13640. var textures = [];
  13641. var attachments = [];
  13642. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  13643. for (var i = 0; i < textureCount; i++) {
  13644. var samplingMode = samplingModes[i] || defaultSamplingMode;
  13645. var type = types[i] || defaultType;
  13646. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  13647. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  13648. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13649. }
  13650. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  13651. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  13652. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13653. }
  13654. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  13655. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  13656. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13657. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  13658. }
  13659. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  13660. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13661. textures.push(texture);
  13662. attachments.push(attachment);
  13663. gl.activeTexture(gl["TEXTURE" + i]);
  13664. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  13665. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  13666. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  13667. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13668. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13669. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  13670. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  13671. if (generateMipMaps) {
  13672. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13673. }
  13674. // Unbind
  13675. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13676. texture._framebuffer = framebuffer;
  13677. texture._depthStencilBuffer = depthStencilBuffer;
  13678. texture.baseWidth = width;
  13679. texture.baseHeight = height;
  13680. texture.width = width;
  13681. texture.height = height;
  13682. texture.isReady = true;
  13683. texture.samples = 1;
  13684. texture.generateMipMaps = generateMipMaps;
  13685. texture.samplingMode = samplingMode;
  13686. texture.type = type;
  13687. texture._generateDepthBuffer = generateDepthBuffer;
  13688. texture._generateStencilBuffer = generateStencilBuffer;
  13689. texture._attachments = attachments;
  13690. this._internalTexturesCache.push(texture);
  13691. }
  13692. if (generateDepthTexture && this._caps.depthTextureExtension) {
  13693. // Depth texture
  13694. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  13695. gl.activeTexture(gl.TEXTURE0);
  13696. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  13697. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  13698. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  13699. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13700. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13701. 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);
  13702. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  13703. depthTexture._framebuffer = framebuffer;
  13704. depthTexture.baseWidth = width;
  13705. depthTexture.baseHeight = height;
  13706. depthTexture.width = width;
  13707. depthTexture.height = height;
  13708. depthTexture.isReady = true;
  13709. depthTexture.samples = 1;
  13710. depthTexture.generateMipMaps = generateMipMaps;
  13711. depthTexture.samplingMode = gl.NEAREST;
  13712. depthTexture._generateDepthBuffer = generateDepthBuffer;
  13713. depthTexture._generateStencilBuffer = generateStencilBuffer;
  13714. textures.push(depthTexture);
  13715. this._internalTexturesCache.push(depthTexture);
  13716. }
  13717. gl.drawBuffers(attachments);
  13718. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13719. this.bindUnboundFramebuffer(null);
  13720. this.resetTextureCache();
  13721. return textures;
  13722. };
  13723. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  13724. if (samples === void 0) { samples = 1; }
  13725. var depthStencilBuffer = null;
  13726. var gl = this._gl;
  13727. // Create the depth/stencil buffer
  13728. if (generateStencilBuffer) {
  13729. depthStencilBuffer = gl.createRenderbuffer();
  13730. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  13731. if (samples > 1) {
  13732. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  13733. }
  13734. else {
  13735. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  13736. }
  13737. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  13738. }
  13739. else if (generateDepthBuffer) {
  13740. depthStencilBuffer = gl.createRenderbuffer();
  13741. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  13742. if (samples > 1) {
  13743. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  13744. }
  13745. else {
  13746. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  13747. }
  13748. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  13749. }
  13750. return depthStencilBuffer;
  13751. };
  13752. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  13753. if (this.webGLVersion < 2 || !texture) {
  13754. return 1;
  13755. }
  13756. if (texture.samples === samples) {
  13757. return samples;
  13758. }
  13759. var gl = this._gl;
  13760. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  13761. // Dispose previous render buffers
  13762. if (texture._depthStencilBuffer) {
  13763. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  13764. texture._depthStencilBuffer = null;
  13765. }
  13766. if (texture._MSAAFramebuffer) {
  13767. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  13768. texture._MSAAFramebuffer = null;
  13769. }
  13770. if (texture._MSAARenderBuffer) {
  13771. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  13772. texture._MSAARenderBuffer = null;
  13773. }
  13774. if (samples > 1) {
  13775. var framebuffer = gl.createFramebuffer();
  13776. if (!framebuffer) {
  13777. throw new Error("Unable to create multi sampled framebuffer");
  13778. }
  13779. texture._MSAAFramebuffer = framebuffer;
  13780. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  13781. var colorRenderbuffer = gl.createRenderbuffer();
  13782. if (!colorRenderbuffer) {
  13783. throw new Error("Unable to create multi sampled framebuffer");
  13784. }
  13785. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  13786. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  13787. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  13788. texture._MSAARenderBuffer = colorRenderbuffer;
  13789. }
  13790. else {
  13791. this.bindUnboundFramebuffer(texture._framebuffer);
  13792. }
  13793. texture.samples = samples;
  13794. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  13795. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13796. this.bindUnboundFramebuffer(null);
  13797. return samples;
  13798. };
  13799. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  13800. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  13801. return 1;
  13802. }
  13803. if (textures[0].samples === samples) {
  13804. return samples;
  13805. }
  13806. var gl = this._gl;
  13807. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  13808. // Dispose previous render buffers
  13809. if (textures[0]._depthStencilBuffer) {
  13810. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  13811. textures[0]._depthStencilBuffer = null;
  13812. }
  13813. if (textures[0]._MSAAFramebuffer) {
  13814. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  13815. textures[0]._MSAAFramebuffer = null;
  13816. }
  13817. for (var i = 0; i < textures.length; i++) {
  13818. if (textures[i]._MSAARenderBuffer) {
  13819. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  13820. textures[i]._MSAARenderBuffer = null;
  13821. }
  13822. }
  13823. if (samples > 1) {
  13824. var framebuffer = gl.createFramebuffer();
  13825. if (!framebuffer) {
  13826. throw new Error("Unable to create multi sampled framebuffer");
  13827. }
  13828. this.bindUnboundFramebuffer(framebuffer);
  13829. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  13830. var attachments = [];
  13831. for (var i = 0; i < textures.length; i++) {
  13832. var texture = textures[i];
  13833. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13834. var colorRenderbuffer = gl.createRenderbuffer();
  13835. if (!colorRenderbuffer) {
  13836. throw new Error("Unable to create multi sampled framebuffer");
  13837. }
  13838. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  13839. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  13840. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  13841. texture._MSAAFramebuffer = framebuffer;
  13842. texture._MSAARenderBuffer = colorRenderbuffer;
  13843. texture.samples = samples;
  13844. texture._depthStencilBuffer = depthStencilBuffer;
  13845. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13846. attachments.push(attachment);
  13847. }
  13848. gl.drawBuffers(attachments);
  13849. }
  13850. else {
  13851. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  13852. }
  13853. this.bindUnboundFramebuffer(null);
  13854. return samples;
  13855. };
  13856. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  13857. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  13858. };
  13859. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  13860. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  13861. };
  13862. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  13863. var fullOptions = __assign({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: Engine.TEXTURETYPE_UNSIGNED_INT, samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE, format: Engine.TEXTUREFORMAT_RGBA }, options);
  13864. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
  13865. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  13866. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  13867. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13868. }
  13869. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  13870. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  13871. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13872. }
  13873. var gl = this._gl;
  13874. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  13875. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13876. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps, gl);
  13877. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  13878. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13879. BABYLON.Tools.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type");
  13880. }
  13881. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  13882. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  13883. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13884. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13885. for (var face = 0; face < 6; face++) {
  13886. 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);
  13887. }
  13888. // Create the framebuffer
  13889. var framebuffer = gl.createFramebuffer();
  13890. this.bindUnboundFramebuffer(framebuffer);
  13891. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
  13892. // MipMaps
  13893. if (fullOptions.generateMipMaps) {
  13894. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13895. }
  13896. // Unbind
  13897. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13898. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13899. this.bindUnboundFramebuffer(null);
  13900. texture._framebuffer = framebuffer;
  13901. texture.width = size;
  13902. texture.height = size;
  13903. texture.isReady = true;
  13904. texture.isCube = true;
  13905. texture.samples = 1;
  13906. texture.generateMipMaps = fullOptions.generateMipMaps;
  13907. texture.samplingMode = fullOptions.samplingMode;
  13908. texture.type = fullOptions.type;
  13909. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  13910. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  13911. this._internalTexturesCache.push(texture);
  13912. return texture;
  13913. };
  13914. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, scale, offset, onLoad, onError, format, forcedExtension) {
  13915. var _this = this;
  13916. if (onLoad === void 0) { onLoad = null; }
  13917. if (onError === void 0) { onError = null; }
  13918. if (forcedExtension === void 0) { forcedExtension = null; }
  13919. var callback = function (loadData) {
  13920. if (!loadData) {
  13921. if (onLoad) {
  13922. onLoad(null);
  13923. }
  13924. return;
  13925. }
  13926. var texture = loadData.texture;
  13927. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  13928. texture._lodGenerationScale = scale;
  13929. texture._lodGenerationOffset = offset;
  13930. if (_this._caps.textureLOD) {
  13931. // Do not add extra process if texture lod is supported.
  13932. if (onLoad) {
  13933. onLoad(texture);
  13934. }
  13935. return;
  13936. }
  13937. var mipSlices = 3;
  13938. var gl = _this._gl;
  13939. var width = loadData.width;
  13940. if (!width) {
  13941. return;
  13942. }
  13943. var textures = [];
  13944. for (var i = 0; i < mipSlices; i++) {
  13945. //compute LOD from even spacing in smoothness (matching shader calculation)
  13946. var smoothness = i / (mipSlices - 1);
  13947. var roughness = 1 - smoothness;
  13948. var minLODIndex = offset; // roughness = 0
  13949. var maxLODIndex = BABYLON.Scalar.Log2(width) * scale + offset; // roughness = 1
  13950. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  13951. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  13952. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  13953. glTextureFromLod.isCube = true;
  13954. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  13955. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  13956. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  13957. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13958. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13959. if (loadData.isDDS) {
  13960. var info = loadData.info;
  13961. var data = loadData.data;
  13962. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  13963. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  13964. }
  13965. else {
  13966. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  13967. }
  13968. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13969. // Wrap in a base texture for easy binding.
  13970. var lodTexture = new BABYLON.BaseTexture(scene);
  13971. lodTexture.isCube = true;
  13972. lodTexture._texture = glTextureFromLod;
  13973. glTextureFromLod.isReady = true;
  13974. textures.push(lodTexture);
  13975. }
  13976. texture._lodTextureHigh = textures[2];
  13977. texture._lodTextureMid = textures[1];
  13978. texture._lodTextureLow = textures[0];
  13979. if (onLoad) {
  13980. onLoad(texture);
  13981. }
  13982. };
  13983. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension);
  13984. };
  13985. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension) {
  13986. var _this = this;
  13987. if (onLoad === void 0) { onLoad = null; }
  13988. if (onError === void 0) { onError = null; }
  13989. if (forcedExtension === void 0) { forcedExtension = null; }
  13990. var gl = this._gl;
  13991. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  13992. texture.isCube = true;
  13993. texture.url = rootUrl;
  13994. texture.generateMipMaps = !noMipmap;
  13995. if (!this._doNotHandleContextLost) {
  13996. texture._extension = forcedExtension;
  13997. texture._files = files;
  13998. }
  13999. var isKTX = false;
  14000. var isDDS = false;
  14001. var lastDot = rootUrl.lastIndexOf('.');
  14002. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  14003. if (this._textureFormatInUse) {
  14004. extension = this._textureFormatInUse;
  14005. rootUrl = (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + this._textureFormatInUse;
  14006. isKTX = true;
  14007. }
  14008. else {
  14009. isDDS = (extension === ".dds");
  14010. }
  14011. var onerror = function (request, exception) {
  14012. if (onError && request) {
  14013. onError(request.status + " " + request.statusText, exception);
  14014. }
  14015. };
  14016. if (isKTX) {
  14017. this._loadFile(rootUrl, function (data) {
  14018. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  14019. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  14020. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14021. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  14022. ktx.uploadLevels(_this._gl, !noMipmap);
  14023. _this.setCubeMapTextureParams(gl, loadMipmap);
  14024. texture.width = ktx.pixelWidth;
  14025. texture.height = ktx.pixelHeight;
  14026. texture.isReady = true;
  14027. }, undefined, undefined, true, onerror);
  14028. }
  14029. else if (isDDS) {
  14030. if (files && files.length === 6) {
  14031. this._cascadeLoadFiles(scene, function (imgs) {
  14032. var info;
  14033. var loadMipmap = false;
  14034. var width = 0;
  14035. for (var index = 0; index < imgs.length; index++) {
  14036. var data = imgs[index];
  14037. info = BABYLON.DDSTools.GetDDSInfo(data);
  14038. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  14039. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14040. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  14041. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6, -1, index);
  14042. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  14043. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  14044. }
  14045. texture.width = info.width;
  14046. texture.height = info.height;
  14047. texture.type = info.textureType;
  14048. width = info.width;
  14049. }
  14050. _this.setCubeMapTextureParams(gl, loadMipmap);
  14051. texture.isReady = true;
  14052. if (onLoad) {
  14053. onLoad({ isDDS: true, width: width, info: info, imgs: imgs, texture: texture });
  14054. }
  14055. }, files, onError);
  14056. }
  14057. else {
  14058. this._loadFile(rootUrl, function (data) {
  14059. var info = BABYLON.DDSTools.GetDDSInfo(data);
  14060. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  14061. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14062. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  14063. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  14064. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  14065. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  14066. }
  14067. _this.setCubeMapTextureParams(gl, loadMipmap);
  14068. texture.width = info.width;
  14069. texture.height = info.height;
  14070. texture.isReady = true;
  14071. texture.type = info.textureType;
  14072. if (onLoad) {
  14073. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  14074. }
  14075. }, undefined, undefined, true, onerror);
  14076. }
  14077. }
  14078. else {
  14079. if (!files) {
  14080. throw new Error("Cannot load cubemap because files were not defined");
  14081. }
  14082. cascadeLoadImgs(rootUrl, scene, function (imgs) {
  14083. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  14084. var height = width;
  14085. _this._prepareWorkingCanvas();
  14086. if (!_this._workingCanvas || !_this._workingContext) {
  14087. return;
  14088. }
  14089. _this._workingCanvas.width = width;
  14090. _this._workingCanvas.height = height;
  14091. var faces = [
  14092. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  14093. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  14094. ];
  14095. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14096. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  14097. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  14098. for (var index = 0; index < faces.length; index++) {
  14099. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  14100. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  14101. }
  14102. if (!noMipmap) {
  14103. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  14104. }
  14105. _this.setCubeMapTextureParams(gl, !noMipmap);
  14106. texture.width = width;
  14107. texture.height = height;
  14108. texture.isReady = true;
  14109. if (format) {
  14110. texture.format = format;
  14111. }
  14112. texture.onLoadedObservable.notifyObservers(texture);
  14113. texture.onLoadedObservable.clear();
  14114. if (onLoad) {
  14115. onLoad();
  14116. }
  14117. }, files, onError);
  14118. }
  14119. this._internalTexturesCache.push(texture);
  14120. return texture;
  14121. };
  14122. Engine.prototype.setCubeMapTextureParams = function (gl, loadMipmap) {
  14123. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  14124. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  14125. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14126. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14127. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  14128. // this.resetTextureCache();
  14129. };
  14130. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  14131. if (compression === void 0) { compression = null; }
  14132. if (level === void 0) { level = 0; }
  14133. texture._bufferViewArray = data;
  14134. texture.format = format;
  14135. texture.type = type;
  14136. texture.invertY = invertY;
  14137. texture._compression = compression;
  14138. var gl = this._gl;
  14139. var textureType = this._getWebGLTextureType(type);
  14140. var internalFormat = this._getInternalFormat(format);
  14141. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  14142. var needConversion = false;
  14143. if (internalFormat === gl.RGB) {
  14144. internalFormat = gl.RGBA;
  14145. needConversion = true;
  14146. }
  14147. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14148. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  14149. if (texture.width % 4 !== 0) {
  14150. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  14151. }
  14152. // Data are known to be in +X +Y +Z -X -Y -Z
  14153. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  14154. var faceData = data[faceIndex];
  14155. if (compression) {
  14156. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  14157. }
  14158. else {
  14159. if (needConversion) {
  14160. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  14161. }
  14162. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  14163. }
  14164. }
  14165. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  14166. if (isPot && texture.generateMipMaps && level === 0) {
  14167. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  14168. }
  14169. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14170. // this.resetTextureCache();
  14171. texture.isReady = true;
  14172. };
  14173. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  14174. if (compression === void 0) { compression = null; }
  14175. var gl = this._gl;
  14176. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  14177. texture.isCube = true;
  14178. texture.generateMipMaps = generateMipMaps;
  14179. texture.format = format;
  14180. texture.type = type;
  14181. if (!this._doNotHandleContextLost) {
  14182. texture._bufferViewArray = data;
  14183. }
  14184. var textureType = this._getWebGLTextureType(type);
  14185. var internalFormat = this._getInternalFormat(format);
  14186. if (internalFormat === gl.RGB) {
  14187. internalFormat = gl.RGBA;
  14188. }
  14189. var width = size;
  14190. var height = width;
  14191. texture.width = width;
  14192. texture.height = height;
  14193. // Double check on POT to generate Mips.
  14194. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  14195. if (!isPot) {
  14196. generateMipMaps = false;
  14197. }
  14198. // Upload data if needed. The texture won't be ready until then.
  14199. if (data) {
  14200. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  14201. }
  14202. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  14203. // Filters
  14204. if (data && generateMipMaps) {
  14205. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  14206. }
  14207. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  14208. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  14209. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  14210. }
  14211. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  14212. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  14213. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  14214. }
  14215. else {
  14216. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  14217. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  14218. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  14219. }
  14220. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14221. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14222. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  14223. return texture;
  14224. };
  14225. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator, onLoad, onError, samplingMode, invertY) {
  14226. var _this = this;
  14227. if (onLoad === void 0) { onLoad = null; }
  14228. if (onError === void 0) { onError = null; }
  14229. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  14230. if (invertY === void 0) { invertY = false; }
  14231. var gl = this._gl;
  14232. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  14233. scene._addPendingData(texture);
  14234. texture.url = url;
  14235. this._internalTexturesCache.push(texture);
  14236. var onerror = function (request, exception) {
  14237. scene._removePendingData(texture);
  14238. if (onError && request) {
  14239. onError(request.status + " " + request.statusText, exception);
  14240. }
  14241. };
  14242. var internalCallback = function (data) {
  14243. var width = texture.width;
  14244. var faceDataArrays = callback(data);
  14245. if (!faceDataArrays) {
  14246. return;
  14247. }
  14248. if (mipmmapGenerator) {
  14249. var textureType = _this._getWebGLTextureType(type);
  14250. var internalFormat = _this._getInternalFormat(format);
  14251. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  14252. var needConversion = false;
  14253. if (internalFormat === gl.RGB) {
  14254. internalFormat = gl.RGBA;
  14255. needConversion = true;
  14256. }
  14257. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14258. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  14259. var mipData = mipmmapGenerator(faceDataArrays);
  14260. for (var level = 0; level < mipData.length; level++) {
  14261. var mipSize = width >> level;
  14262. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  14263. var mipFaceData = mipData[level][faceIndex];
  14264. if (needConversion) {
  14265. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  14266. }
  14267. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  14268. }
  14269. }
  14270. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  14271. }
  14272. else {
  14273. texture.generateMipMaps = !noMipmap;
  14274. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  14275. }
  14276. texture.isReady = true;
  14277. // this.resetTextureCache();
  14278. scene._removePendingData(texture);
  14279. if (onLoad) {
  14280. onLoad();
  14281. }
  14282. };
  14283. this._loadFile(url, function (data) {
  14284. internalCallback(data);
  14285. }, undefined, scene.database, true, onerror);
  14286. return texture;
  14287. };
  14288. ;
  14289. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression) {
  14290. if (compression === void 0) { compression = null; }
  14291. var internalFormat = this._getInternalFormat(format);
  14292. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  14293. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  14294. if (!this._doNotHandleContextLost) {
  14295. texture._bufferView = data;
  14296. texture.format = format;
  14297. texture.invertY = invertY;
  14298. texture._compression = compression;
  14299. }
  14300. if (texture.width % 4 !== 0) {
  14301. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  14302. }
  14303. if (compression && data) {
  14304. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  14305. }
  14306. else {
  14307. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalFormat, texture.width, texture.height, texture.depth, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  14308. }
  14309. if (texture.generateMipMaps) {
  14310. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  14311. }
  14312. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14313. // this.resetTextureCache();
  14314. texture.isReady = true;
  14315. };
  14316. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression) {
  14317. if (compression === void 0) { compression = null; }
  14318. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  14319. texture.baseWidth = width;
  14320. texture.baseHeight = height;
  14321. texture.baseDepth = depth;
  14322. texture.width = width;
  14323. texture.height = height;
  14324. texture.depth = depth;
  14325. texture.format = format;
  14326. texture.generateMipMaps = generateMipMaps;
  14327. texture.samplingMode = samplingMode;
  14328. texture.is3D = true;
  14329. if (!this._doNotHandleContextLost) {
  14330. texture._bufferView = data;
  14331. }
  14332. this.updateRawTexture3D(texture, data, format, invertY, compression);
  14333. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  14334. // Filters
  14335. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  14336. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  14337. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14338. if (generateMipMaps) {
  14339. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  14340. }
  14341. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14342. this._internalTexturesCache.push(texture);
  14343. return texture;
  14344. };
  14345. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  14346. var gl = this._gl;
  14347. if (!gl) {
  14348. return;
  14349. }
  14350. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  14351. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  14352. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  14353. if (!noMipmap && !isCompressed) {
  14354. gl.generateMipmap(gl.TEXTURE_2D);
  14355. }
  14356. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  14357. // this.resetTextureCache();
  14358. if (scene) {
  14359. scene._removePendingData(texture);
  14360. }
  14361. texture.onLoadedObservable.notifyObservers(texture);
  14362. texture.onLoadedObservable.clear();
  14363. };
  14364. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  14365. var _this = this;
  14366. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  14367. var potWidth = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  14368. var potHeight = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  14369. var gl = this._gl;
  14370. if (!gl) {
  14371. return;
  14372. }
  14373. if (!texture._webGLTexture) {
  14374. // this.resetTextureCache();
  14375. if (scene) {
  14376. scene._removePendingData(texture);
  14377. }
  14378. return;
  14379. }
  14380. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  14381. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  14382. texture.baseWidth = width;
  14383. texture.baseHeight = height;
  14384. texture.width = potWidth;
  14385. texture.height = potHeight;
  14386. texture.isReady = true;
  14387. if (processFunction(potWidth, potHeight, function () {
  14388. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  14389. })) {
  14390. // Returning as texture needs extra async steps
  14391. return;
  14392. }
  14393. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  14394. };
  14395. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  14396. // Create new RGBA data container.
  14397. var rgbaData;
  14398. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  14399. rgbaData = new Float32Array(width * height * 4);
  14400. }
  14401. else {
  14402. rgbaData = new Uint32Array(width * height * 4);
  14403. }
  14404. // Convert each pixel.
  14405. for (var x = 0; x < width; x++) {
  14406. for (var y = 0; y < height; y++) {
  14407. var index = (y * width + x) * 3;
  14408. var newIndex = (y * width + x) * 4;
  14409. // Map Old Value to new value.
  14410. rgbaData[newIndex + 0] = rgbData[index + 0];
  14411. rgbaData[newIndex + 1] = rgbData[index + 1];
  14412. rgbaData[newIndex + 2] = rgbData[index + 2];
  14413. // Add fully opaque alpha channel.
  14414. rgbaData[newIndex + 3] = 1;
  14415. }
  14416. }
  14417. return rgbaData;
  14418. };
  14419. Engine.prototype._releaseFramebufferObjects = function (texture) {
  14420. var gl = this._gl;
  14421. if (texture._framebuffer) {
  14422. gl.deleteFramebuffer(texture._framebuffer);
  14423. texture._framebuffer = null;
  14424. }
  14425. if (texture._depthStencilBuffer) {
  14426. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  14427. texture._depthStencilBuffer = null;
  14428. }
  14429. if (texture._MSAAFramebuffer) {
  14430. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  14431. texture._MSAAFramebuffer = null;
  14432. }
  14433. if (texture._MSAARenderBuffer) {
  14434. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  14435. texture._MSAARenderBuffer = null;
  14436. }
  14437. };
  14438. Engine.prototype._releaseTexture = function (texture) {
  14439. var gl = this._gl;
  14440. this._releaseFramebufferObjects(texture);
  14441. gl.deleteTexture(texture._webGLTexture);
  14442. // Unbind channels
  14443. this.unbindAllTextures();
  14444. var index = this._internalTexturesCache.indexOf(texture);
  14445. if (index !== -1) {
  14446. this._internalTexturesCache.splice(index, 1);
  14447. }
  14448. // Integrated fixed lod samplers.
  14449. if (texture._lodTextureHigh) {
  14450. texture._lodTextureHigh.dispose();
  14451. }
  14452. if (texture._lodTextureMid) {
  14453. texture._lodTextureMid.dispose();
  14454. }
  14455. if (texture._lodTextureLow) {
  14456. texture._lodTextureLow.dispose();
  14457. }
  14458. };
  14459. Engine.prototype.setProgram = function (program) {
  14460. if (this._currentProgram !== program) {
  14461. this._gl.useProgram(program);
  14462. this._currentProgram = program;
  14463. }
  14464. };
  14465. Engine.prototype.bindSamplers = function (effect) {
  14466. this.setProgram(effect.getProgram());
  14467. var samplers = effect.getSamplers();
  14468. for (var index = 0; index < samplers.length; index++) {
  14469. var uniform = effect.getUniform(samplers[index]);
  14470. if (uniform) {
  14471. this._boundUniforms[index] = uniform;
  14472. }
  14473. }
  14474. this._currentEffect = null;
  14475. };
  14476. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  14477. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  14478. return;
  14479. }
  14480. // Remove
  14481. this._linkTrackers(internalTexture.previous, internalTexture.next);
  14482. // Bind last to it
  14483. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  14484. // Bind to dummy
  14485. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  14486. };
  14487. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  14488. if (!internalTexture) {
  14489. return -1;
  14490. }
  14491. internalTexture._initialSlot = channel;
  14492. if (this.disableTextureBindingOptimization) {
  14493. if (channel !== internalTexture._designatedSlot) {
  14494. this._textureCollisions.addCount(1, false);
  14495. }
  14496. }
  14497. else {
  14498. if (channel !== internalTexture._designatedSlot) {
  14499. if (internalTexture._designatedSlot > -1) {
  14500. return internalTexture._designatedSlot;
  14501. }
  14502. else {
  14503. // No slot for this texture, let's pick a new one (if we find a free slot)
  14504. if (this._nextFreeTextureSlots.length) {
  14505. return this._nextFreeTextureSlots[0];
  14506. }
  14507. // We need to recycle the oldest bound texture, sorry.
  14508. this._textureCollisions.addCount(1, false);
  14509. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  14510. }
  14511. }
  14512. }
  14513. return channel;
  14514. };
  14515. Engine.prototype._linkTrackers = function (previous, next) {
  14516. previous.next = next;
  14517. next.previous = previous;
  14518. };
  14519. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  14520. var currentSlot = internalTexture._designatedSlot;
  14521. if (currentSlot === -1) {
  14522. return -1;
  14523. }
  14524. internalTexture._designatedSlot = -1;
  14525. if (this.disableTextureBindingOptimization) {
  14526. return -1;
  14527. }
  14528. // Remove from bound list
  14529. this._linkTrackers(internalTexture.previous, internalTexture.next);
  14530. // Free the slot
  14531. this._boundTexturesCache[currentSlot] = null;
  14532. this._nextFreeTextureSlots.push(currentSlot);
  14533. return currentSlot;
  14534. };
  14535. Engine.prototype._activateCurrentTexture = function () {
  14536. if (this._currentTextureChannel !== this._activeChannel) {
  14537. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  14538. this._currentTextureChannel = this._activeChannel;
  14539. }
  14540. };
  14541. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate) {
  14542. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  14543. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  14544. this._activeChannel = texture._designatedSlot;
  14545. }
  14546. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  14547. var isTextureForRendering = texture && texture._initialSlot > -1;
  14548. if (currentTextureBound !== texture) {
  14549. if (currentTextureBound) {
  14550. this._removeDesignatedSlot(currentTextureBound);
  14551. }
  14552. this._activateCurrentTexture();
  14553. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  14554. this._boundTexturesCache[this._activeChannel] = texture;
  14555. if (texture) {
  14556. if (!this.disableTextureBindingOptimization) {
  14557. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  14558. if (slotIndex > -1) {
  14559. this._nextFreeTextureSlots.splice(slotIndex, 1);
  14560. }
  14561. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  14562. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  14563. }
  14564. texture._designatedSlot = this._activeChannel;
  14565. }
  14566. }
  14567. else if (forTextureDataUpdate) {
  14568. this._activateCurrentTexture();
  14569. }
  14570. if (isTextureForRendering && !forTextureDataUpdate) {
  14571. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  14572. }
  14573. };
  14574. Engine.prototype._bindTexture = function (channel, texture) {
  14575. if (channel < 0) {
  14576. return;
  14577. }
  14578. if (texture) {
  14579. channel = this._getCorrectTextureChannel(channel, texture);
  14580. }
  14581. this._activeChannel = channel;
  14582. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  14583. };
  14584. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  14585. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  14586. };
  14587. Engine.prototype.unbindAllTextures = function () {
  14588. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  14589. this._activeChannel = channel;
  14590. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14591. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14592. if (this.webGLVersion > 1) {
  14593. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14594. }
  14595. }
  14596. };
  14597. Engine.prototype.setTexture = function (channel, uniform, texture) {
  14598. if (channel < 0) {
  14599. return;
  14600. }
  14601. if (uniform) {
  14602. this._boundUniforms[channel] = uniform;
  14603. }
  14604. this._setTexture(channel, texture);
  14605. };
  14606. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  14607. var uniform = this._boundUniforms[sourceSlot];
  14608. if (uniform._currentState === destination) {
  14609. return;
  14610. }
  14611. this._gl.uniform1i(uniform, destination);
  14612. uniform._currentState = destination;
  14613. };
  14614. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray) {
  14615. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  14616. // Not ready?
  14617. if (!texture) {
  14618. if (this._boundTexturesCache[channel] != null) {
  14619. this._activeChannel = channel;
  14620. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14621. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14622. if (this.webGLVersion > 1) {
  14623. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14624. }
  14625. }
  14626. return false;
  14627. }
  14628. // Video
  14629. if (texture.video) {
  14630. this._activeChannel = channel;
  14631. texture.update();
  14632. }
  14633. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  14634. texture.delayLoad();
  14635. return false;
  14636. }
  14637. var internalTexture;
  14638. if (texture.isReady()) {
  14639. internalTexture = texture.getInternalTexture();
  14640. }
  14641. else if (texture.isCube) {
  14642. internalTexture = this.emptyCubeTexture;
  14643. }
  14644. else if (texture.is3D) {
  14645. internalTexture = this.emptyTexture3D;
  14646. }
  14647. else {
  14648. internalTexture = this.emptyTexture;
  14649. }
  14650. if (!isPartOfTextureArray) {
  14651. channel = this._getCorrectTextureChannel(channel, internalTexture);
  14652. }
  14653. if (this._boundTexturesCache[channel] === internalTexture) {
  14654. this._moveBoundTextureOnTop(internalTexture);
  14655. if (!isPartOfTextureArray) {
  14656. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  14657. }
  14658. return false;
  14659. }
  14660. this._activeChannel = channel;
  14661. if (internalTexture && internalTexture.is3D) {
  14662. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  14663. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  14664. internalTexture._cachedWrapU = texture.wrapU;
  14665. switch (texture.wrapU) {
  14666. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14667. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  14668. break;
  14669. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14670. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  14671. break;
  14672. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14673. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  14674. break;
  14675. }
  14676. }
  14677. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  14678. internalTexture._cachedWrapV = texture.wrapV;
  14679. switch (texture.wrapV) {
  14680. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14681. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  14682. break;
  14683. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14684. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  14685. break;
  14686. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14687. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  14688. break;
  14689. }
  14690. }
  14691. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  14692. internalTexture._cachedWrapR = texture.wrapR;
  14693. switch (texture.wrapR) {
  14694. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14695. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.REPEAT);
  14696. break;
  14697. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14698. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.CLAMP_TO_EDGE);
  14699. break;
  14700. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14701. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.MIRRORED_REPEAT);
  14702. break;
  14703. }
  14704. }
  14705. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  14706. }
  14707. else if (internalTexture && internalTexture.isCube) {
  14708. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  14709. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  14710. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  14711. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  14712. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  14713. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  14714. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  14715. }
  14716. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  14717. }
  14718. else {
  14719. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  14720. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  14721. internalTexture._cachedWrapU = texture.wrapU;
  14722. switch (texture.wrapU) {
  14723. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14724. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  14725. break;
  14726. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14727. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  14728. break;
  14729. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14730. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  14731. break;
  14732. }
  14733. }
  14734. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  14735. internalTexture._cachedWrapV = texture.wrapV;
  14736. switch (texture.wrapV) {
  14737. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14738. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  14739. break;
  14740. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14741. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  14742. break;
  14743. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14744. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  14745. break;
  14746. }
  14747. }
  14748. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  14749. }
  14750. return true;
  14751. };
  14752. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  14753. if (channel < 0 || !uniform) {
  14754. return;
  14755. }
  14756. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  14757. this._textureUnits = new Int32Array(textures.length);
  14758. }
  14759. for (var i = 0; i < textures.length; i++) {
  14760. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  14761. }
  14762. this._gl.uniform1iv(uniform, this._textureUnits);
  14763. for (var index = 0; index < textures.length; index++) {
  14764. this._setTexture(this._textureUnits[index], textures[index], true);
  14765. }
  14766. };
  14767. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  14768. var internalTexture = texture.getInternalTexture();
  14769. if (!internalTexture) {
  14770. return;
  14771. }
  14772. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  14773. var value = texture.anisotropicFilteringLevel;
  14774. if (internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST
  14775. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR
  14776. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR) {
  14777. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  14778. }
  14779. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  14780. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  14781. internalTexture._cachedAnisotropicFilteringLevel = value;
  14782. }
  14783. };
  14784. Engine.prototype.readPixels = function (x, y, width, height) {
  14785. var data = new Uint8Array(height * width * 4);
  14786. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  14787. return data;
  14788. };
  14789. /**
  14790. * Add an externaly attached data from its key.
  14791. * This method call will fail and return false, if such key already exists.
  14792. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  14793. * @param key the unique key that identifies the data
  14794. * @param data the data object to associate to the key for this Engine instance
  14795. * @return true if no such key were already present and the data was added successfully, false otherwise
  14796. */
  14797. Engine.prototype.addExternalData = function (key, data) {
  14798. if (!this._externalData) {
  14799. this._externalData = new BABYLON.StringDictionary();
  14800. }
  14801. return this._externalData.add(key, data);
  14802. };
  14803. /**
  14804. * Get an externaly attached data from its key
  14805. * @param key the unique key that identifies the data
  14806. * @return the associated data, if present (can be null), or undefined if not present
  14807. */
  14808. Engine.prototype.getExternalData = function (key) {
  14809. if (!this._externalData) {
  14810. this._externalData = new BABYLON.StringDictionary();
  14811. }
  14812. return this._externalData.get(key);
  14813. };
  14814. /**
  14815. * Get an externaly attached data from its key, create it using a factory if it's not already present
  14816. * @param key the unique key that identifies the data
  14817. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  14818. * @return the associated data, can be null if the factory returned null.
  14819. */
  14820. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  14821. if (!this._externalData) {
  14822. this._externalData = new BABYLON.StringDictionary();
  14823. }
  14824. return this._externalData.getOrAddWithFactory(key, factory);
  14825. };
  14826. /**
  14827. * Remove an externaly attached data from the Engine instance
  14828. * @param key the unique key that identifies the data
  14829. * @return true if the data was successfully removed, false if it doesn't exist
  14830. */
  14831. Engine.prototype.removeExternalData = function (key) {
  14832. if (!this._externalData) {
  14833. this._externalData = new BABYLON.StringDictionary();
  14834. }
  14835. return this._externalData.remove(key);
  14836. };
  14837. Engine.prototype.unbindAllAttributes = function () {
  14838. if (this._mustWipeVertexAttributes) {
  14839. this._mustWipeVertexAttributes = false;
  14840. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  14841. this._gl.disableVertexAttribArray(i);
  14842. this._vertexAttribArraysEnabled[i] = false;
  14843. this._currentBufferPointers[i].active = false;
  14844. }
  14845. return;
  14846. }
  14847. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  14848. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  14849. continue;
  14850. }
  14851. this._gl.disableVertexAttribArray(i);
  14852. this._vertexAttribArraysEnabled[i] = false;
  14853. this._currentBufferPointers[i].active = false;
  14854. }
  14855. };
  14856. Engine.prototype.releaseEffects = function () {
  14857. for (var name in this._compiledEffects) {
  14858. this._deleteProgram(this._compiledEffects[name]._program);
  14859. }
  14860. this._compiledEffects = {};
  14861. };
  14862. // Dispose
  14863. Engine.prototype.dispose = function () {
  14864. this.hideLoadingUI();
  14865. this.stopRenderLoop();
  14866. // Release postProcesses
  14867. while (this.postProcesses.length) {
  14868. this.postProcesses[0].dispose();
  14869. }
  14870. // Empty texture
  14871. if (this._emptyTexture) {
  14872. this._releaseTexture(this._emptyTexture);
  14873. this._emptyTexture = null;
  14874. }
  14875. if (this._emptyCubeTexture) {
  14876. this._releaseTexture(this._emptyCubeTexture);
  14877. this._emptyCubeTexture = null;
  14878. }
  14879. // Rescale PP
  14880. if (this._rescalePostProcess) {
  14881. this._rescalePostProcess.dispose();
  14882. }
  14883. // Release scenes
  14884. while (this.scenes.length) {
  14885. this.scenes[0].dispose();
  14886. }
  14887. // Release audio engine
  14888. if (Engine.audioEngine) {
  14889. Engine.audioEngine.dispose();
  14890. }
  14891. // Release effects
  14892. this.releaseEffects();
  14893. // Unbind
  14894. this.unbindAllAttributes();
  14895. if (this._dummyFramebuffer) {
  14896. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  14897. }
  14898. //WebVR
  14899. this.disableVR();
  14900. // Events
  14901. if (BABYLON.Tools.IsWindowObjectExist()) {
  14902. window.removeEventListener("blur", this._onBlur);
  14903. window.removeEventListener("focus", this._onFocus);
  14904. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  14905. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  14906. if (this._renderingCanvas) {
  14907. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  14908. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  14909. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasPointerOut);
  14910. if (!this._doNotHandleContextLost) {
  14911. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  14912. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  14913. }
  14914. }
  14915. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  14916. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  14917. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  14918. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  14919. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  14920. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  14921. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  14922. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  14923. if (this._onVrDisplayConnect) {
  14924. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  14925. if (this._onVrDisplayDisconnect) {
  14926. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  14927. }
  14928. if (this._onVrDisplayPresentChange) {
  14929. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  14930. }
  14931. this._onVrDisplayConnect = null;
  14932. this._onVrDisplayDisconnect = null;
  14933. }
  14934. }
  14935. // Remove from Instances
  14936. var index = Engine.Instances.indexOf(this);
  14937. if (index >= 0) {
  14938. Engine.Instances.splice(index, 1);
  14939. }
  14940. this._workingCanvas = null;
  14941. this._workingContext = null;
  14942. this._currentBufferPointers = [];
  14943. this._renderingCanvas = null;
  14944. this._currentProgram = null;
  14945. this._bindedRenderFunction = null;
  14946. this.onResizeObservable.clear();
  14947. this.onCanvasBlurObservable.clear();
  14948. this.onCanvasFocusObservable.clear();
  14949. this.onCanvasPointerOutObservable.clear();
  14950. this.onBeginFrameObservable.clear();
  14951. this.onEndFrameObservable.clear();
  14952. BABYLON.Effect.ResetCache();
  14953. // Abort active requests
  14954. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  14955. var request = _a[_i];
  14956. request.abort();
  14957. }
  14958. };
  14959. // Loading screen
  14960. Engine.prototype.displayLoadingUI = function () {
  14961. if (!BABYLON.Tools.IsWindowObjectExist()) {
  14962. return;
  14963. }
  14964. var loadingScreen = this.loadingScreen;
  14965. if (loadingScreen) {
  14966. loadingScreen.displayLoadingUI();
  14967. }
  14968. };
  14969. Engine.prototype.hideLoadingUI = function () {
  14970. if (!BABYLON.Tools.IsWindowObjectExist()) {
  14971. return;
  14972. }
  14973. var loadingScreen = this.loadingScreen;
  14974. if (loadingScreen) {
  14975. loadingScreen.hideLoadingUI();
  14976. }
  14977. };
  14978. Object.defineProperty(Engine.prototype, "loadingScreen", {
  14979. get: function () {
  14980. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  14981. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  14982. return this._loadingScreen;
  14983. },
  14984. set: function (loadingScreen) {
  14985. this._loadingScreen = loadingScreen;
  14986. },
  14987. enumerable: true,
  14988. configurable: true
  14989. });
  14990. Object.defineProperty(Engine.prototype, "loadingUIText", {
  14991. set: function (text) {
  14992. this.loadingScreen.loadingUIText = text;
  14993. },
  14994. enumerable: true,
  14995. configurable: true
  14996. });
  14997. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  14998. set: function (color) {
  14999. this.loadingScreen.loadingUIBackgroundColor = color;
  15000. },
  15001. enumerable: true,
  15002. configurable: true
  15003. });
  15004. Engine.prototype.attachContextLostEvent = function (callback) {
  15005. if (this._renderingCanvas) {
  15006. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  15007. }
  15008. };
  15009. Engine.prototype.attachContextRestoredEvent = function (callback) {
  15010. if (this._renderingCanvas) {
  15011. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  15012. }
  15013. };
  15014. Engine.prototype.getVertexShaderSource = function (program) {
  15015. var shaders = this._gl.getAttachedShaders(program);
  15016. if (!shaders) {
  15017. return null;
  15018. }
  15019. return this._gl.getShaderSource(shaders[0]);
  15020. };
  15021. Engine.prototype.getFragmentShaderSource = function (program) {
  15022. var shaders = this._gl.getAttachedShaders(program);
  15023. if (!shaders) {
  15024. return null;
  15025. }
  15026. return this._gl.getShaderSource(shaders[1]);
  15027. };
  15028. Engine.prototype.getError = function () {
  15029. return this._gl.getError();
  15030. };
  15031. // FPS
  15032. Engine.prototype.getFps = function () {
  15033. return this._fps;
  15034. };
  15035. Engine.prototype.getDeltaTime = function () {
  15036. return this._deltaTime;
  15037. };
  15038. Engine.prototype._measureFps = function () {
  15039. this._performanceMonitor.sampleFrame();
  15040. this._fps = this._performanceMonitor.averageFPS;
  15041. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  15042. };
  15043. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex) {
  15044. if (faceIndex === void 0) { faceIndex = -1; }
  15045. var gl = this._gl;
  15046. if (!this._dummyFramebuffer) {
  15047. var dummy = gl.createFramebuffer();
  15048. if (!dummy) {
  15049. throw new Error("Unable to create dummy framebuffer");
  15050. }
  15051. this._dummyFramebuffer = dummy;
  15052. }
  15053. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  15054. if (faceIndex > -1) {
  15055. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  15056. }
  15057. else {
  15058. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15059. }
  15060. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  15061. var buffer;
  15062. switch (readType) {
  15063. case gl.UNSIGNED_BYTE:
  15064. buffer = new Uint8Array(4 * width * height);
  15065. readType = gl.UNSIGNED_BYTE;
  15066. break;
  15067. default:
  15068. buffer = new Float32Array(4 * width * height);
  15069. readType = gl.FLOAT;
  15070. break;
  15071. }
  15072. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  15073. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  15074. return buffer;
  15075. };
  15076. Engine.prototype._canRenderToFloatFramebuffer = function () {
  15077. if (this._webGLVersion > 1) {
  15078. return this._caps.colorBufferFloat;
  15079. }
  15080. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  15081. };
  15082. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  15083. if (this._webGLVersion > 1) {
  15084. return this._caps.colorBufferFloat;
  15085. }
  15086. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  15087. };
  15088. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  15089. Engine.prototype._canRenderToFramebuffer = function (type) {
  15090. var gl = this._gl;
  15091. //clear existing errors
  15092. while (gl.getError() !== gl.NO_ERROR) { }
  15093. var successful = true;
  15094. var texture = gl.createTexture();
  15095. gl.bindTexture(gl.TEXTURE_2D, texture);
  15096. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  15097. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15098. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15099. var fb = gl.createFramebuffer();
  15100. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  15101. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  15102. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  15103. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  15104. successful = successful && (gl.getError() === gl.NO_ERROR);
  15105. //try render by clearing frame buffer's color buffer
  15106. if (successful) {
  15107. gl.clear(gl.COLOR_BUFFER_BIT);
  15108. successful = successful && (gl.getError() === gl.NO_ERROR);
  15109. }
  15110. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  15111. if (successful) {
  15112. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  15113. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  15114. var readFormat = gl.RGBA;
  15115. var readType = gl.UNSIGNED_BYTE;
  15116. var buffer = new Uint8Array(4);
  15117. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  15118. successful = successful && (gl.getError() === gl.NO_ERROR);
  15119. }
  15120. //clean up
  15121. gl.deleteTexture(texture);
  15122. gl.deleteFramebuffer(fb);
  15123. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  15124. //clear accumulated errors
  15125. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  15126. return successful;
  15127. };
  15128. Engine.prototype._getWebGLTextureType = function (type) {
  15129. if (type === Engine.TEXTURETYPE_FLOAT) {
  15130. return this._gl.FLOAT;
  15131. }
  15132. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  15133. // Add Half Float Constant.
  15134. return this._gl.HALF_FLOAT_OES;
  15135. }
  15136. return this._gl.UNSIGNED_BYTE;
  15137. };
  15138. ;
  15139. Engine.prototype._getInternalFormat = function (format) {
  15140. var internalFormat = this._gl.RGBA;
  15141. switch (format) {
  15142. case Engine.TEXTUREFORMAT_ALPHA:
  15143. internalFormat = this._gl.ALPHA;
  15144. break;
  15145. case Engine.TEXTUREFORMAT_LUMINANCE:
  15146. internalFormat = this._gl.LUMINANCE;
  15147. break;
  15148. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  15149. internalFormat = this._gl.LUMINANCE_ALPHA;
  15150. break;
  15151. case Engine.TEXTUREFORMAT_RGB:
  15152. case Engine.TEXTUREFORMAT_RGB32F:
  15153. internalFormat = this._gl.RGB;
  15154. break;
  15155. case Engine.TEXTUREFORMAT_RGBA:
  15156. case Engine.TEXTUREFORMAT_RGBA32F:
  15157. internalFormat = this._gl.RGBA;
  15158. break;
  15159. case Engine.TEXTUREFORMAT_R32F:
  15160. internalFormat = this._gl.RED;
  15161. break;
  15162. case Engine.TEXTUREFORMAT_RG32F:
  15163. internalFormat = this._gl.RG;
  15164. break;
  15165. }
  15166. return internalFormat;
  15167. };
  15168. /** @ignore */
  15169. Engine.prototype._getRGBABufferInternalSizedFormat = function (type, format) {
  15170. if (this._webGLVersion === 1) {
  15171. if (format) {
  15172. switch (format) {
  15173. case Engine.TEXTUREFORMAT_LUMINANCE:
  15174. return this._gl.LUMINANCE;
  15175. }
  15176. }
  15177. return this._gl.RGBA;
  15178. }
  15179. if (type === Engine.TEXTURETYPE_FLOAT) {
  15180. if (format) {
  15181. switch (format) {
  15182. case Engine.TEXTUREFORMAT_R32F:
  15183. return this._gl.R32F;
  15184. case Engine.TEXTUREFORMAT_RG32F:
  15185. return this._gl.RG32F;
  15186. case Engine.TEXTUREFORMAT_RGB32F:
  15187. return this._gl.RGB32F;
  15188. }
  15189. }
  15190. return this._gl.RGBA32F;
  15191. }
  15192. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  15193. return this._gl.RGBA16F;
  15194. }
  15195. if (format) {
  15196. switch (format) {
  15197. case Engine.TEXTUREFORMAT_LUMINANCE:
  15198. return this._gl.LUMINANCE;
  15199. }
  15200. }
  15201. return this._gl.RGBA;
  15202. };
  15203. ;
  15204. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  15205. if (type === Engine.TEXTURETYPE_FLOAT) {
  15206. return this._gl.RGBA32F;
  15207. }
  15208. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  15209. return this._gl.RGBA16F;
  15210. }
  15211. return this._gl.RGBA8;
  15212. };
  15213. ;
  15214. Engine.prototype.createQuery = function () {
  15215. return this._gl.createQuery();
  15216. };
  15217. Engine.prototype.deleteQuery = function (query) {
  15218. this._gl.deleteQuery(query);
  15219. return this;
  15220. };
  15221. Engine.prototype.isQueryResultAvailable = function (query) {
  15222. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  15223. };
  15224. Engine.prototype.getQueryResult = function (query) {
  15225. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  15226. };
  15227. Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  15228. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  15229. this._gl.beginQuery(glAlgorithm, query);
  15230. return this;
  15231. };
  15232. Engine.prototype.endOcclusionQuery = function (algorithmType) {
  15233. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  15234. this._gl.endQuery(glAlgorithm);
  15235. return this;
  15236. };
  15237. /* Time queries */
  15238. Engine.prototype._createTimeQuery = function () {
  15239. var timerQuery = this._caps.timerQuery;
  15240. if (timerQuery.createQueryEXT) {
  15241. return timerQuery.createQueryEXT();
  15242. }
  15243. return this.createQuery();
  15244. };
  15245. Engine.prototype._deleteTimeQuery = function (query) {
  15246. var timerQuery = this._caps.timerQuery;
  15247. if (timerQuery.deleteQueryEXT) {
  15248. timerQuery.deleteQueryEXT(query);
  15249. return;
  15250. }
  15251. this.deleteQuery(query);
  15252. };
  15253. Engine.prototype._getTimeQueryResult = function (query) {
  15254. var timerQuery = this._caps.timerQuery;
  15255. if (timerQuery.getQueryObjectEXT) {
  15256. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  15257. }
  15258. return this.getQueryResult(query);
  15259. };
  15260. Engine.prototype._getTimeQueryAvailability = function (query) {
  15261. var timerQuery = this._caps.timerQuery;
  15262. if (timerQuery.getQueryObjectEXT) {
  15263. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  15264. }
  15265. return this.isQueryResultAvailable(query);
  15266. };
  15267. Engine.prototype.startTimeQuery = function () {
  15268. var timerQuery = this._caps.timerQuery;
  15269. if (!timerQuery) {
  15270. return null;
  15271. }
  15272. var token = new BABYLON._TimeToken();
  15273. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  15274. if (this._caps.canUseTimestampForTimerQuery) {
  15275. token._startTimeQuery = this._createTimeQuery();
  15276. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  15277. }
  15278. else {
  15279. if (this._currentNonTimestampToken) {
  15280. return this._currentNonTimestampToken;
  15281. }
  15282. token._timeElapsedQuery = this._createTimeQuery();
  15283. if (timerQuery.beginQueryEXT) {
  15284. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  15285. }
  15286. else {
  15287. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  15288. }
  15289. this._currentNonTimestampToken = token;
  15290. }
  15291. return token;
  15292. };
  15293. Engine.prototype.endTimeQuery = function (token) {
  15294. var timerQuery = this._caps.timerQuery;
  15295. if (!timerQuery || !token) {
  15296. return -1;
  15297. }
  15298. if (this._caps.canUseTimestampForTimerQuery) {
  15299. if (!token._startTimeQuery) {
  15300. return -1;
  15301. }
  15302. if (!token._endTimeQuery) {
  15303. token._endTimeQuery = this._createTimeQuery();
  15304. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  15305. }
  15306. }
  15307. else if (!token._timeElapsedQueryEnded) {
  15308. if (!token._timeElapsedQuery) {
  15309. return -1;
  15310. }
  15311. if (timerQuery.endQueryEXT) {
  15312. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  15313. }
  15314. else {
  15315. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  15316. }
  15317. token._timeElapsedQueryEnded = true;
  15318. }
  15319. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  15320. var available = false;
  15321. if (token._endTimeQuery) {
  15322. available = this._getTimeQueryAvailability(token._endTimeQuery);
  15323. }
  15324. else if (token._timeElapsedQuery) {
  15325. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  15326. }
  15327. if (available && !disjoint) {
  15328. var result = 0;
  15329. if (this._caps.canUseTimestampForTimerQuery) {
  15330. if (!token._startTimeQuery || !token._endTimeQuery) {
  15331. return -1;
  15332. }
  15333. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  15334. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  15335. result = timeEnd - timeStart;
  15336. this._deleteTimeQuery(token._startTimeQuery);
  15337. this._deleteTimeQuery(token._endTimeQuery);
  15338. token._startTimeQuery = null;
  15339. token._endTimeQuery = null;
  15340. }
  15341. else {
  15342. if (!token._timeElapsedQuery) {
  15343. return -1;
  15344. }
  15345. result = this._getTimeQueryResult(token._timeElapsedQuery);
  15346. this._deleteTimeQuery(token._timeElapsedQuery);
  15347. token._timeElapsedQuery = null;
  15348. token._timeElapsedQueryEnded = false;
  15349. this._currentNonTimestampToken = null;
  15350. }
  15351. return result;
  15352. }
  15353. return -1;
  15354. };
  15355. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  15356. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  15357. };
  15358. // Transform feedback
  15359. Engine.prototype.createTransformFeedback = function () {
  15360. return this._gl.createTransformFeedback();
  15361. };
  15362. Engine.prototype.deleteTransformFeedback = function (value) {
  15363. this._gl.deleteTransformFeedback(value);
  15364. };
  15365. Engine.prototype.bindTransformFeedback = function (value) {
  15366. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  15367. };
  15368. Engine.prototype.beginTransformFeedback = function (usePoints) {
  15369. if (usePoints === void 0) { usePoints = true; }
  15370. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  15371. };
  15372. Engine.prototype.endTransformFeedback = function () {
  15373. this._gl.endTransformFeedback();
  15374. };
  15375. Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  15376. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  15377. };
  15378. Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  15379. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  15380. };
  15381. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  15382. var _this = this;
  15383. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  15384. this._activeRequests.push(request);
  15385. request.onCompleteObservable.add(function (request) {
  15386. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  15387. });
  15388. return request;
  15389. };
  15390. /** @ignore */
  15391. Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {
  15392. var _this = this;
  15393. return new Promise(function (resolve, reject) {
  15394. _this._loadFile(url, function (data) {
  15395. resolve(data);
  15396. }, undefined, database, useArrayBuffer, function (request, exception) {
  15397. reject(exception);
  15398. });
  15399. });
  15400. };
  15401. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  15402. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  15403. var onload = function (data) {
  15404. loadedFiles[index] = data;
  15405. loadedFiles._internalCount++;
  15406. if (loadedFiles._internalCount === 6) {
  15407. onfinish(loadedFiles);
  15408. }
  15409. };
  15410. var onerror = function (request, exception) {
  15411. if (onErrorCallBack && request) {
  15412. onErrorCallBack(request.status + " " + request.statusText, exception);
  15413. }
  15414. };
  15415. this._loadFile(url, onload, undefined, undefined, true, onerror);
  15416. };
  15417. Engine.prototype._cascadeLoadFiles = function (scene, onfinish, files, onError) {
  15418. if (onError === void 0) { onError = null; }
  15419. var loadedFiles = [];
  15420. loadedFiles._internalCount = 0;
  15421. for (var index = 0; index < 6; index++) {
  15422. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  15423. }
  15424. };
  15425. // Statics
  15426. Engine.isSupported = function () {
  15427. try {
  15428. var tempcanvas = document.createElement("canvas");
  15429. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  15430. return gl != null && !!window.WebGLRenderingContext;
  15431. }
  15432. catch (e) {
  15433. return false;
  15434. }
  15435. };
  15436. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  15437. Engine.ExceptionList = [
  15438. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  15439. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  15440. { key: "Firefox/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  15441. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  15442. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  15443. { key: "iPad", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] }
  15444. ];
  15445. Engine.Instances = new Array();
  15446. // Const statics
  15447. Engine._ALPHA_DISABLE = 0;
  15448. Engine._ALPHA_ADD = 1;
  15449. Engine._ALPHA_COMBINE = 2;
  15450. Engine._ALPHA_SUBTRACT = 3;
  15451. Engine._ALPHA_MULTIPLY = 4;
  15452. Engine._ALPHA_MAXIMIZED = 5;
  15453. Engine._ALPHA_ONEONE = 6;
  15454. Engine._ALPHA_PREMULTIPLIED = 7;
  15455. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  15456. Engine._ALPHA_INTERPOLATE = 9;
  15457. Engine._ALPHA_SCREENMODE = 10;
  15458. Engine._DELAYLOADSTATE_NONE = 0;
  15459. Engine._DELAYLOADSTATE_LOADED = 1;
  15460. Engine._DELAYLOADSTATE_LOADING = 2;
  15461. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  15462. Engine._TEXTUREFORMAT_ALPHA = 0;
  15463. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  15464. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  15465. Engine._TEXTUREFORMAT_RGB = 4;
  15466. Engine._TEXTUREFORMAT_RGBA = 5;
  15467. Engine._TEXTUREFORMAT_R32F = 6;
  15468. Engine._TEXTUREFORMAT_RG32F = 7;
  15469. Engine._TEXTUREFORMAT_RGB32F = 8;
  15470. Engine._TEXTUREFORMAT_RGBA32F = 9;
  15471. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  15472. Engine._TEXTURETYPE_FLOAT = 1;
  15473. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  15474. // Depht or Stencil test Constants.
  15475. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  15476. 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.
  15477. 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.
  15478. 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.
  15479. 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.
  15480. 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.
  15481. 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.
  15482. 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.
  15483. // Stencil Actions Constants.
  15484. Engine._KEEP = 0x1E00;
  15485. Engine._REPLACE = 0x1E01;
  15486. Engine._INCR = 0x1E02;
  15487. Engine._DECR = 0x1E03;
  15488. Engine._INVERT = 0x150A;
  15489. Engine._INCR_WRAP = 0x8507;
  15490. Engine._DECR_WRAP = 0x8508;
  15491. // Texture rescaling mode
  15492. Engine._SCALEMODE_FLOOR = 1;
  15493. Engine._SCALEMODE_NEAREST = 2;
  15494. Engine._SCALEMODE_CEILING = 3;
  15495. // Updatable statics so stick with vars here
  15496. Engine.CollisionsEpsilon = 0.001;
  15497. Engine.CodeRepository = "src/";
  15498. Engine.ShadersRepository = "src/Shaders/";
  15499. return Engine;
  15500. }());
  15501. BABYLON.Engine = Engine;
  15502. })(BABYLON || (BABYLON = {}));
  15503. //# sourceMappingURL=babylon.engine.js.map
  15504. var BABYLON;
  15505. (function (BABYLON) {
  15506. /**
  15507. * Node is the basic class for all scene objects (Mesh, Light Camera).
  15508. */
  15509. var Node = /** @class */ (function () {
  15510. /**
  15511. * Creates a new Node
  15512. * @param {string} name - the name and id to be given to this node
  15513. * @param {BABYLON.Scene} the scene this node will be added to
  15514. */
  15515. function Node(name, scene) {
  15516. if (scene === void 0) { scene = null; }
  15517. /**
  15518. * Gets or sets a string used to store user defined state for the node
  15519. */
  15520. this.state = "";
  15521. /**
  15522. * Gets or sets an object used to store user defined information for the node
  15523. */
  15524. this.metadata = null;
  15525. /**
  15526. * Gets or sets a boolean used to define if the node must be serialized
  15527. */
  15528. this.doNotSerialize = false;
  15529. /** @ignore */
  15530. this._isDisposed = false;
  15531. /**
  15532. * Gets a list of {BABYLON.Animation} associated with the node
  15533. */
  15534. this.animations = new Array();
  15535. this._ranges = {};
  15536. this._isEnabled = true;
  15537. this._isReady = true;
  15538. /** @ignore */
  15539. this._currentRenderId = -1;
  15540. this._parentRenderId = -1;
  15541. this._animationPropertiesOverride = null;
  15542. /**
  15543. * An event triggered when the mesh is disposed
  15544. * @type {BABYLON.Observable}
  15545. */
  15546. this.onDisposeObservable = new BABYLON.Observable();
  15547. // Behaviors
  15548. this._behaviors = new Array();
  15549. this.name = name;
  15550. this.id = name;
  15551. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  15552. this.uniqueId = this._scene.getUniqueId();
  15553. this._initCache();
  15554. }
  15555. /**
  15556. * Gets a boolean indicating if the node has been disposed
  15557. * @returns true if the node was disposed
  15558. */
  15559. Node.prototype.isDisposed = function () {
  15560. return this._isDisposed;
  15561. };
  15562. Object.defineProperty(Node.prototype, "parent", {
  15563. get: function () {
  15564. return this._parentNode;
  15565. },
  15566. /**
  15567. * Gets or sets the parent of the node
  15568. */
  15569. set: function (parent) {
  15570. if (this._parentNode === parent) {
  15571. return;
  15572. }
  15573. // Remove self from list of children of parent
  15574. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  15575. var index = this._parentNode._children.indexOf(this);
  15576. if (index !== -1) {
  15577. this._parentNode._children.splice(index, 1);
  15578. }
  15579. }
  15580. // Store new parent
  15581. this._parentNode = parent;
  15582. // Add as child to new parent
  15583. if (this._parentNode) {
  15584. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  15585. this._parentNode._children = new Array();
  15586. }
  15587. this._parentNode._children.push(this);
  15588. }
  15589. },
  15590. enumerable: true,
  15591. configurable: true
  15592. });
  15593. Object.defineProperty(Node.prototype, "animationPropertiesOverride", {
  15594. /**
  15595. * Gets or sets the animation properties override
  15596. */
  15597. get: function () {
  15598. return this._animationPropertiesOverride;
  15599. },
  15600. set: function (value) {
  15601. this._animationPropertiesOverride = value;
  15602. },
  15603. enumerable: true,
  15604. configurable: true
  15605. });
  15606. /**
  15607. * Gets a string idenfifying the name of the class
  15608. * @returns "Node" string
  15609. */
  15610. Node.prototype.getClassName = function () {
  15611. return "Node";
  15612. };
  15613. Object.defineProperty(Node.prototype, "onDispose", {
  15614. /**
  15615. * Sets a callback that will be raised when the node will be disposed
  15616. */
  15617. set: function (callback) {
  15618. if (this._onDisposeObserver) {
  15619. this.onDisposeObservable.remove(this._onDisposeObserver);
  15620. }
  15621. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  15622. },
  15623. enumerable: true,
  15624. configurable: true
  15625. });
  15626. /**
  15627. * Gets the scene of the node
  15628. * @returns a {BABYLON.Scene}
  15629. */
  15630. Node.prototype.getScene = function () {
  15631. return this._scene;
  15632. };
  15633. /**
  15634. * Gets the engine of the node
  15635. * @returns a {BABYLON.Engine}
  15636. */
  15637. Node.prototype.getEngine = function () {
  15638. return this._scene.getEngine();
  15639. };
  15640. /**
  15641. * Attach a behavior to the node
  15642. * @see http://doc.babylonjs.com/features/behaviour
  15643. * @param behavior defines the behavior to attach
  15644. * @returns the current Node
  15645. */
  15646. Node.prototype.addBehavior = function (behavior) {
  15647. var _this = this;
  15648. var index = this._behaviors.indexOf(behavior);
  15649. if (index !== -1) {
  15650. return this;
  15651. }
  15652. behavior.init();
  15653. if (this._scene.isLoading) {
  15654. // We defer the attach when the scene will be loaded
  15655. var observer = this._scene.onDataLoadedObservable.add(function () {
  15656. behavior.attach(_this);
  15657. setTimeout(function () {
  15658. // Need to use a timeout to avoid removing an observer while iterating the list of observers
  15659. _this._scene.onDataLoadedObservable.remove(observer);
  15660. }, 0);
  15661. });
  15662. }
  15663. else {
  15664. behavior.attach(this);
  15665. }
  15666. this._behaviors.push(behavior);
  15667. return this;
  15668. };
  15669. /**
  15670. * Remove an attached behavior
  15671. * @see http://doc.babylonjs.com/features/behaviour
  15672. * @param behavior defines the behavior to attach
  15673. * @returns the current Node
  15674. */
  15675. Node.prototype.removeBehavior = function (behavior) {
  15676. var index = this._behaviors.indexOf(behavior);
  15677. if (index === -1) {
  15678. return this;
  15679. }
  15680. this._behaviors[index].detach();
  15681. this._behaviors.splice(index, 1);
  15682. return this;
  15683. };
  15684. Object.defineProperty(Node.prototype, "behaviors", {
  15685. /**
  15686. * Gets the list of attached behaviors
  15687. * @see http://doc.babylonjs.com/features/behaviour
  15688. */
  15689. get: function () {
  15690. return this._behaviors;
  15691. },
  15692. enumerable: true,
  15693. configurable: true
  15694. });
  15695. /**
  15696. * Gets an attached behavior by name
  15697. * @param name defines the name of the behavior to look for
  15698. * @see http://doc.babylonjs.com/features/behaviour
  15699. * @returns null if behavior was not found else the requested behavior
  15700. */
  15701. Node.prototype.getBehaviorByName = function (name) {
  15702. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  15703. var behavior = _a[_i];
  15704. if (behavior.name === name) {
  15705. return behavior;
  15706. }
  15707. }
  15708. return null;
  15709. };
  15710. /**
  15711. * Returns the world matrix of the node
  15712. * @returns a matrix containing the node's world matrix
  15713. */
  15714. Node.prototype.getWorldMatrix = function () {
  15715. return BABYLON.Matrix.Identity();
  15716. };
  15717. // override it in derived class if you add new variables to the cache
  15718. // and call the parent class method
  15719. /** @ignore */
  15720. Node.prototype._initCache = function () {
  15721. this._cache = {};
  15722. this._cache.parent = undefined;
  15723. };
  15724. /** @ignore */
  15725. Node.prototype.updateCache = function (force) {
  15726. if (!force && this.isSynchronized())
  15727. return;
  15728. this._cache.parent = this.parent;
  15729. this._updateCache();
  15730. };
  15731. // override it in derived class if you add new variables to the cache
  15732. // and call the parent class method if !ignoreParentClass
  15733. /** @ignore */
  15734. Node.prototype._updateCache = function (ignoreParentClass) {
  15735. };
  15736. // override it in derived class if you add new variables to the cache
  15737. /** @ignore */
  15738. Node.prototype._isSynchronized = function () {
  15739. return true;
  15740. };
  15741. /** @ignore */
  15742. Node.prototype._markSyncedWithParent = function () {
  15743. if (this.parent) {
  15744. this._parentRenderId = this.parent._currentRenderId;
  15745. }
  15746. };
  15747. /** @ignore */
  15748. Node.prototype.isSynchronizedWithParent = function () {
  15749. if (!this.parent) {
  15750. return true;
  15751. }
  15752. if (this._parentRenderId !== this.parent._currentRenderId) {
  15753. return false;
  15754. }
  15755. return this.parent.isSynchronized();
  15756. };
  15757. /** @ignore */
  15758. Node.prototype.isSynchronized = function (updateCache) {
  15759. var check = this.hasNewParent();
  15760. check = check || !this.isSynchronizedWithParent();
  15761. check = check || !this._isSynchronized();
  15762. if (updateCache)
  15763. this.updateCache(true);
  15764. return !check;
  15765. };
  15766. /** @ignore */
  15767. Node.prototype.hasNewParent = function (update) {
  15768. if (this._cache.parent === this.parent)
  15769. return false;
  15770. if (update)
  15771. this._cache.parent = this.parent;
  15772. return true;
  15773. };
  15774. /**
  15775. * Is this node ready to be used/rendered
  15776. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  15777. * @return true if the node is ready
  15778. */
  15779. Node.prototype.isReady = function (completeCheck) {
  15780. if (completeCheck === void 0) { completeCheck = false; }
  15781. return this._isReady;
  15782. };
  15783. /**
  15784. * Is this node enabled?
  15785. * 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
  15786. * @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
  15787. * @return whether this node (and its parent) is enabled
  15788. * @see setEnabled
  15789. */
  15790. Node.prototype.isEnabled = function (checkAncestors) {
  15791. if (checkAncestors === void 0) { checkAncestors = true; }
  15792. if (checkAncestors === false) {
  15793. return this._isEnabled;
  15794. }
  15795. if (this._isEnabled === false) {
  15796. return false;
  15797. }
  15798. if (this.parent !== undefined && this.parent !== null) {
  15799. return this.parent.isEnabled(checkAncestors);
  15800. }
  15801. return true;
  15802. };
  15803. /**
  15804. * Set the enabled state of this node
  15805. * @param value defines the new enabled state
  15806. * @see isEnabled
  15807. */
  15808. Node.prototype.setEnabled = function (value) {
  15809. this._isEnabled = value;
  15810. };
  15811. /**
  15812. * Is this node a descendant of the given node?
  15813. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined
  15814. * @param ancestor defines the parent node to inspect
  15815. * @see parent
  15816. * @returns a boolean indicating if this node is a descendant of the given node
  15817. */
  15818. Node.prototype.isDescendantOf = function (ancestor) {
  15819. if (this.parent) {
  15820. if (this.parent === ancestor) {
  15821. return true;
  15822. }
  15823. return this.parent.isDescendantOf(ancestor);
  15824. }
  15825. return false;
  15826. };
  15827. /** @ignore */
  15828. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  15829. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  15830. if (!this._children) {
  15831. return;
  15832. }
  15833. for (var index = 0; index < this._children.length; index++) {
  15834. var item = this._children[index];
  15835. if (!predicate || predicate(item)) {
  15836. results.push(item);
  15837. }
  15838. if (!directDescendantsOnly) {
  15839. item._getDescendants(results, false, predicate);
  15840. }
  15841. }
  15842. };
  15843. /**
  15844. * Will return all nodes that have this node as ascendant
  15845. * @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
  15846. * @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
  15847. * @return all children nodes of all types
  15848. */
  15849. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  15850. var results = new Array();
  15851. this._getDescendants(results, directDescendantsOnly, predicate);
  15852. return results;
  15853. };
  15854. /**
  15855. * Get all child-meshes of this node
  15856. * @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
  15857. * @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
  15858. * @returns an array of {BABYLON.AbstractMesh}
  15859. */
  15860. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  15861. var results = [];
  15862. this._getDescendants(results, directDescendantsOnly, function (node) {
  15863. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  15864. });
  15865. return results;
  15866. };
  15867. /**
  15868. * Get all child-transformNodes of this node
  15869. * @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
  15870. * @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
  15871. * @returns an array of {BABYLON.TransformNode}
  15872. */
  15873. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  15874. var results = [];
  15875. this._getDescendants(results, directDescendantsOnly, function (node) {
  15876. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  15877. });
  15878. return results;
  15879. };
  15880. /**
  15881. * Get all direct children of this node
  15882. * @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
  15883. * @returns an array of {BABYLON.Node}
  15884. */
  15885. Node.prototype.getChildren = function (predicate) {
  15886. return this.getDescendants(true, predicate);
  15887. };
  15888. /** @ignore */
  15889. Node.prototype._setReady = function (state) {
  15890. if (state === this._isReady) {
  15891. return;
  15892. }
  15893. if (!state) {
  15894. this._isReady = false;
  15895. return;
  15896. }
  15897. this._isReady = true;
  15898. if (this.onReady) {
  15899. this.onReady(this);
  15900. }
  15901. };
  15902. /**
  15903. * Get an animation by name
  15904. * @param name defines the name of the animation to look for
  15905. * @returns null if not found else the requested animation
  15906. */
  15907. Node.prototype.getAnimationByName = function (name) {
  15908. for (var i = 0; i < this.animations.length; i++) {
  15909. var animation = this.animations[i];
  15910. if (animation.name === name) {
  15911. return animation;
  15912. }
  15913. }
  15914. return null;
  15915. };
  15916. /**
  15917. * Creates an animation range for this node
  15918. * @param name defines the name of the range
  15919. * @param from defines the starting key
  15920. * @param to defines the end key
  15921. */
  15922. Node.prototype.createAnimationRange = function (name, from, to) {
  15923. // check name not already in use
  15924. if (!this._ranges[name]) {
  15925. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  15926. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  15927. if (this.animations[i]) {
  15928. this.animations[i].createRange(name, from, to);
  15929. }
  15930. }
  15931. }
  15932. };
  15933. /**
  15934. * Delete a specific animation range
  15935. * @param name defines the name of the range to delete
  15936. * @param deleteFrames defines if animation frames from the range must be deleted as well
  15937. */
  15938. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  15939. if (deleteFrames === void 0) { deleteFrames = true; }
  15940. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  15941. if (this.animations[i]) {
  15942. this.animations[i].deleteRange(name, deleteFrames);
  15943. }
  15944. }
  15945. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  15946. };
  15947. /**
  15948. * Get an animation range by name
  15949. * @param name defines the name of the animation range to look for
  15950. * @returns null if not found else the requested animation range
  15951. */
  15952. Node.prototype.getAnimationRange = function (name) {
  15953. return this._ranges[name];
  15954. };
  15955. /**
  15956. * Will start the animation sequence
  15957. * @param name defines the range frames for animation sequence
  15958. * @param loop defines if the animation should loop (false by default)
  15959. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  15960. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  15961. * @returns the object created for this animation. If range does not exist, it will return null
  15962. */
  15963. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  15964. var range = this.getAnimationRange(name);
  15965. if (!range) {
  15966. return null;
  15967. }
  15968. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  15969. };
  15970. /**
  15971. * Serialize animation ranges into a JSON compatible object
  15972. * @returns serialization object
  15973. */
  15974. Node.prototype.serializeAnimationRanges = function () {
  15975. var serializationRanges = [];
  15976. for (var name in this._ranges) {
  15977. var localRange = this._ranges[name];
  15978. if (!localRange) {
  15979. continue;
  15980. }
  15981. var range = {};
  15982. range.name = name;
  15983. range.from = localRange.from;
  15984. range.to = localRange.to;
  15985. serializationRanges.push(range);
  15986. }
  15987. return serializationRanges;
  15988. };
  15989. /**
  15990. * Computes the world matrix of the node
  15991. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  15992. * @returns the world matrix
  15993. */
  15994. Node.prototype.computeWorldMatrix = function (force) {
  15995. return BABYLON.Matrix.Identity();
  15996. };
  15997. /**
  15998. * Releases resources associated with this node.
  15999. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  16000. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  16001. */
  16002. Node.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  16003. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  16004. if (!doNotRecurse) {
  16005. var nodes = this.getDescendants(true);
  16006. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  16007. var node = nodes_1[_i];
  16008. node.dispose(doNotRecurse, disposeMaterialAndTextures);
  16009. }
  16010. }
  16011. else {
  16012. var transformNodes = this.getChildTransformNodes(true);
  16013. for (var _a = 0, transformNodes_1 = transformNodes; _a < transformNodes_1.length; _a++) {
  16014. var transformNode = transformNodes_1[_a];
  16015. transformNode.parent = null;
  16016. transformNode.computeWorldMatrix(true);
  16017. }
  16018. }
  16019. this.parent = null;
  16020. // Callback
  16021. this.onDisposeObservable.notifyObservers(this);
  16022. this.onDisposeObservable.clear();
  16023. // Behaviors
  16024. for (var _b = 0, _c = this._behaviors; _b < _c.length; _b++) {
  16025. var behavior = _c[_b];
  16026. behavior.detach();
  16027. }
  16028. this._behaviors = [];
  16029. this._isDisposed = true;
  16030. };
  16031. /**
  16032. * Parse animation range data from a serialization object and store them into a given node
  16033. * @param node defines where to store the animation ranges
  16034. * @param parsedNode defines the serialization object to read data from
  16035. * @param scene defines the hosting scene
  16036. */
  16037. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  16038. if (parsedNode.ranges) {
  16039. for (var index = 0; index < parsedNode.ranges.length; index++) {
  16040. var data = parsedNode.ranges[index];
  16041. node.createAnimationRange(data.name, data.from, data.to);
  16042. }
  16043. }
  16044. };
  16045. __decorate([
  16046. BABYLON.serialize()
  16047. ], Node.prototype, "name", void 0);
  16048. __decorate([
  16049. BABYLON.serialize()
  16050. ], Node.prototype, "id", void 0);
  16051. __decorate([
  16052. BABYLON.serialize()
  16053. ], Node.prototype, "uniqueId", void 0);
  16054. __decorate([
  16055. BABYLON.serialize()
  16056. ], Node.prototype, "state", void 0);
  16057. __decorate([
  16058. BABYLON.serialize()
  16059. ], Node.prototype, "metadata", void 0);
  16060. return Node;
  16061. }());
  16062. BABYLON.Node = Node;
  16063. })(BABYLON || (BABYLON = {}));
  16064. //# sourceMappingURL=babylon.node.js.map
  16065. var BABYLON;
  16066. (function (BABYLON) {
  16067. var BoundingSphere = /** @class */ (function () {
  16068. function BoundingSphere(minimum, maximum) {
  16069. this.minimum = minimum;
  16070. this.maximum = maximum;
  16071. this._tempRadiusVector = BABYLON.Vector3.Zero();
  16072. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  16073. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  16074. this.radius = distance * 0.5;
  16075. this.centerWorld = BABYLON.Vector3.Zero();
  16076. this._update(BABYLON.Matrix.Identity());
  16077. }
  16078. // Methods
  16079. BoundingSphere.prototype._update = function (world) {
  16080. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  16081. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  16082. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  16083. };
  16084. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  16085. for (var i = 0; i < 6; i++) {
  16086. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  16087. return false;
  16088. }
  16089. return true;
  16090. };
  16091. BoundingSphere.prototype.intersectsPoint = function (point) {
  16092. var x = this.centerWorld.x - point.x;
  16093. var y = this.centerWorld.y - point.y;
  16094. var z = this.centerWorld.z - point.z;
  16095. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  16096. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  16097. return false;
  16098. return true;
  16099. };
  16100. // Statics
  16101. BoundingSphere.Intersects = function (sphere0, sphere1) {
  16102. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  16103. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  16104. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  16105. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  16106. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  16107. return false;
  16108. return true;
  16109. };
  16110. return BoundingSphere;
  16111. }());
  16112. BABYLON.BoundingSphere = BoundingSphere;
  16113. })(BABYLON || (BABYLON = {}));
  16114. //# sourceMappingURL=babylon.boundingSphere.js.map
  16115. var BABYLON;
  16116. (function (BABYLON) {
  16117. var BoundingBox = /** @class */ (function () {
  16118. function BoundingBox(minimum, maximum) {
  16119. this.minimum = minimum;
  16120. this.maximum = maximum;
  16121. this.vectors = new Array();
  16122. this.vectorsWorld = new Array();
  16123. // Bounding vectors
  16124. this.vectors.push(this.minimum.clone());
  16125. this.vectors.push(this.maximum.clone());
  16126. this.vectors.push(this.minimum.clone());
  16127. this.vectors[2].x = this.maximum.x;
  16128. this.vectors.push(this.minimum.clone());
  16129. this.vectors[3].y = this.maximum.y;
  16130. this.vectors.push(this.minimum.clone());
  16131. this.vectors[4].z = this.maximum.z;
  16132. this.vectors.push(this.maximum.clone());
  16133. this.vectors[5].z = this.minimum.z;
  16134. this.vectors.push(this.maximum.clone());
  16135. this.vectors[6].x = this.minimum.x;
  16136. this.vectors.push(this.maximum.clone());
  16137. this.vectors[7].y = this.minimum.y;
  16138. // OBB
  16139. this.center = this.maximum.add(this.minimum).scale(0.5);
  16140. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  16141. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  16142. // World
  16143. for (var index = 0; index < this.vectors.length; index++) {
  16144. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  16145. }
  16146. this.minimumWorld = BABYLON.Vector3.Zero();
  16147. this.maximumWorld = BABYLON.Vector3.Zero();
  16148. this.centerWorld = BABYLON.Vector3.Zero();
  16149. this.extendSizeWorld = BABYLON.Vector3.Zero();
  16150. this._update(BABYLON.Matrix.Identity());
  16151. }
  16152. // Methods
  16153. BoundingBox.prototype.getWorldMatrix = function () {
  16154. return this._worldMatrix;
  16155. };
  16156. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  16157. this._worldMatrix.copyFrom(matrix);
  16158. return this;
  16159. };
  16160. BoundingBox.prototype._update = function (world) {
  16161. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  16162. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  16163. for (var index = 0; index < this.vectors.length; index++) {
  16164. var v = this.vectorsWorld[index];
  16165. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  16166. if (v.x < this.minimumWorld.x)
  16167. this.minimumWorld.x = v.x;
  16168. if (v.y < this.minimumWorld.y)
  16169. this.minimumWorld.y = v.y;
  16170. if (v.z < this.minimumWorld.z)
  16171. this.minimumWorld.z = v.z;
  16172. if (v.x > this.maximumWorld.x)
  16173. this.maximumWorld.x = v.x;
  16174. if (v.y > this.maximumWorld.y)
  16175. this.maximumWorld.y = v.y;
  16176. if (v.z > this.maximumWorld.z)
  16177. this.maximumWorld.z = v.z;
  16178. }
  16179. // Extend
  16180. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  16181. this.extendSizeWorld.scaleInPlace(0.5);
  16182. // OBB
  16183. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  16184. this.centerWorld.scaleInPlace(0.5);
  16185. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  16186. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  16187. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  16188. this._worldMatrix = world;
  16189. };
  16190. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  16191. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  16192. };
  16193. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  16194. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  16195. };
  16196. BoundingBox.prototype.intersectsPoint = function (point) {
  16197. var delta = -BABYLON.Epsilon;
  16198. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  16199. return false;
  16200. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  16201. return false;
  16202. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  16203. return false;
  16204. return true;
  16205. };
  16206. BoundingBox.prototype.intersectsSphere = function (sphere) {
  16207. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  16208. };
  16209. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  16210. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  16211. return false;
  16212. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  16213. return false;
  16214. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  16215. return false;
  16216. return true;
  16217. };
  16218. // Statics
  16219. BoundingBox.Intersects = function (box0, box1) {
  16220. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  16221. return false;
  16222. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  16223. return false;
  16224. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  16225. return false;
  16226. return true;
  16227. };
  16228. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  16229. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  16230. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  16231. return (num <= (sphereRadius * sphereRadius));
  16232. };
  16233. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  16234. for (var p = 0; p < 6; p++) {
  16235. for (var i = 0; i < 8; i++) {
  16236. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  16237. return false;
  16238. }
  16239. }
  16240. }
  16241. return true;
  16242. };
  16243. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  16244. for (var p = 0; p < 6; p++) {
  16245. var inCount = 8;
  16246. for (var i = 0; i < 8; i++) {
  16247. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  16248. --inCount;
  16249. }
  16250. else {
  16251. break;
  16252. }
  16253. }
  16254. if (inCount === 0)
  16255. return false;
  16256. }
  16257. return true;
  16258. };
  16259. return BoundingBox;
  16260. }());
  16261. BABYLON.BoundingBox = BoundingBox;
  16262. })(BABYLON || (BABYLON = {}));
  16263. //# sourceMappingURL=babylon.boundingBox.js.map
  16264. var BABYLON;
  16265. (function (BABYLON) {
  16266. var computeBoxExtents = function (axis, box) {
  16267. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  16268. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  16269. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  16270. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  16271. var r = r0 + r1 + r2;
  16272. return {
  16273. min: p - r,
  16274. max: p + r
  16275. };
  16276. };
  16277. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  16278. var axisOverlap = function (axis, box0, box1) {
  16279. var result0 = computeBoxExtents(axis, box0);
  16280. var result1 = computeBoxExtents(axis, box1);
  16281. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  16282. };
  16283. var BoundingInfo = /** @class */ (function () {
  16284. function BoundingInfo(minimum, maximum) {
  16285. this.minimum = minimum;
  16286. this.maximum = maximum;
  16287. this._isLocked = false;
  16288. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  16289. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  16290. }
  16291. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  16292. get: function () {
  16293. return this._isLocked;
  16294. },
  16295. set: function (value) {
  16296. this._isLocked = value;
  16297. },
  16298. enumerable: true,
  16299. configurable: true
  16300. });
  16301. // Methods
  16302. BoundingInfo.prototype.update = function (world) {
  16303. if (this._isLocked) {
  16304. return;
  16305. }
  16306. this.boundingBox._update(world);
  16307. this.boundingSphere._update(world);
  16308. };
  16309. /**
  16310. * Recreate the bounding info to be centered around a specific point given a specific extend.
  16311. * @param center New center of the bounding info
  16312. * @param extend New extend of the bounding info
  16313. */
  16314. BoundingInfo.prototype.centerOn = function (center, extend) {
  16315. this.minimum = center.subtract(extend);
  16316. this.maximum = center.add(extend);
  16317. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  16318. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  16319. return this;
  16320. };
  16321. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  16322. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  16323. return false;
  16324. return this.boundingBox.isInFrustum(frustumPlanes);
  16325. };
  16326. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  16327. /**
  16328. * Gets the world distance between the min and max points of the bounding box
  16329. */
  16330. get: function () {
  16331. var boundingBox = this.boundingBox;
  16332. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  16333. return size.length();
  16334. },
  16335. enumerable: true,
  16336. configurable: true
  16337. });
  16338. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  16339. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  16340. };
  16341. BoundingInfo.prototype._checkCollision = function (collider) {
  16342. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  16343. };
  16344. BoundingInfo.prototype.intersectsPoint = function (point) {
  16345. if (!this.boundingSphere.centerWorld) {
  16346. return false;
  16347. }
  16348. if (!this.boundingSphere.intersectsPoint(point)) {
  16349. return false;
  16350. }
  16351. if (!this.boundingBox.intersectsPoint(point)) {
  16352. return false;
  16353. }
  16354. return true;
  16355. };
  16356. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  16357. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  16358. return false;
  16359. }
  16360. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  16361. return false;
  16362. }
  16363. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  16364. return false;
  16365. }
  16366. if (!precise) {
  16367. return true;
  16368. }
  16369. var box0 = this.boundingBox;
  16370. var box1 = boundingInfo.boundingBox;
  16371. if (!axisOverlap(box0.directions[0], box0, box1))
  16372. return false;
  16373. if (!axisOverlap(box0.directions[1], box0, box1))
  16374. return false;
  16375. if (!axisOverlap(box0.directions[2], box0, box1))
  16376. return false;
  16377. if (!axisOverlap(box1.directions[0], box0, box1))
  16378. return false;
  16379. if (!axisOverlap(box1.directions[1], box0, box1))
  16380. return false;
  16381. if (!axisOverlap(box1.directions[2], box0, box1))
  16382. return false;
  16383. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  16384. return false;
  16385. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  16386. return false;
  16387. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  16388. return false;
  16389. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  16390. return false;
  16391. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  16392. return false;
  16393. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  16394. return false;
  16395. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  16396. return false;
  16397. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  16398. return false;
  16399. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  16400. return false;
  16401. return true;
  16402. };
  16403. return BoundingInfo;
  16404. }());
  16405. BABYLON.BoundingInfo = BoundingInfo;
  16406. })(BABYLON || (BABYLON = {}));
  16407. //# sourceMappingURL=babylon.boundingInfo.js.map
  16408. var BABYLON;
  16409. (function (BABYLON) {
  16410. var TransformNode = /** @class */ (function (_super) {
  16411. __extends(TransformNode, _super);
  16412. function TransformNode(name, scene, isPure) {
  16413. if (scene === void 0) { scene = null; }
  16414. if (isPure === void 0) { isPure = true; }
  16415. var _this = _super.call(this, name, scene) || this;
  16416. // Properties
  16417. _this._rotation = BABYLON.Vector3.Zero();
  16418. _this._scaling = BABYLON.Vector3.One();
  16419. _this._isDirty = false;
  16420. _this.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_NONE;
  16421. _this.scalingDeterminant = 1;
  16422. _this.infiniteDistance = false;
  16423. _this.position = BABYLON.Vector3.Zero();
  16424. _this._localWorld = BABYLON.Matrix.Zero();
  16425. _this._worldMatrix = BABYLON.Matrix.Zero();
  16426. _this._worldMatrixDeterminant = 0;
  16427. _this._absolutePosition = BABYLON.Vector3.Zero();
  16428. _this._pivotMatrix = BABYLON.Matrix.Identity();
  16429. _this._postMultiplyPivotMatrix = false;
  16430. _this._isWorldMatrixFrozen = false;
  16431. /**
  16432. * An event triggered after the world matrix is updated
  16433. * @type {BABYLON.Observable}
  16434. */
  16435. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  16436. _this._nonUniformScaling = false;
  16437. if (isPure) {
  16438. _this.getScene().addTransformNode(_this);
  16439. }
  16440. return _this;
  16441. }
  16442. /**
  16443. * Gets a string idenfifying the name of the class
  16444. * @returns "TransformNode" string
  16445. */
  16446. TransformNode.prototype.getClassName = function () {
  16447. return "TransformNode";
  16448. };
  16449. Object.defineProperty(TransformNode.prototype, "rotation", {
  16450. /**
  16451. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  16452. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  16453. * Default : (0.0, 0.0, 0.0)
  16454. */
  16455. get: function () {
  16456. return this._rotation;
  16457. },
  16458. set: function (newRotation) {
  16459. this._rotation = newRotation;
  16460. },
  16461. enumerable: true,
  16462. configurable: true
  16463. });
  16464. Object.defineProperty(TransformNode.prototype, "scaling", {
  16465. /**
  16466. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  16467. * Default : (1.0, 1.0, 1.0)
  16468. */
  16469. get: function () {
  16470. return this._scaling;
  16471. },
  16472. /**
  16473. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  16474. * Default : (1.0, 1.0, 1.0)
  16475. */
  16476. set: function (newScaling) {
  16477. this._scaling = newScaling;
  16478. },
  16479. enumerable: true,
  16480. configurable: true
  16481. });
  16482. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  16483. /**
  16484. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  16485. * It's null by default.
  16486. * 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)
  16487. */
  16488. get: function () {
  16489. return this._rotationQuaternion;
  16490. },
  16491. set: function (quaternion) {
  16492. this._rotationQuaternion = quaternion;
  16493. //reset the rotation vector.
  16494. if (quaternion && this.rotation.length()) {
  16495. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  16496. }
  16497. },
  16498. enumerable: true,
  16499. configurable: true
  16500. });
  16501. /**
  16502. * Returns the latest update of the World matrix
  16503. * Returns a Matrix.
  16504. */
  16505. TransformNode.prototype.getWorldMatrix = function () {
  16506. if (this._currentRenderId !== this.getScene().getRenderId()) {
  16507. this.computeWorldMatrix();
  16508. }
  16509. return this._worldMatrix;
  16510. };
  16511. /**
  16512. * Returns the latest update of the World matrix determinant.
  16513. */
  16514. TransformNode.prototype._getWorldMatrixDeterminant = function () {
  16515. return this._worldMatrixDeterminant;
  16516. };
  16517. Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
  16518. /**
  16519. * Returns directly the latest state of the mesh World matrix.
  16520. * A Matrix is returned.
  16521. */
  16522. get: function () {
  16523. return this._worldMatrix;
  16524. },
  16525. enumerable: true,
  16526. configurable: true
  16527. });
  16528. /**
  16529. * Copies the paramater passed Matrix into the mesh Pose matrix.
  16530. * Returns the AbstractMesh.
  16531. */
  16532. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  16533. this._poseMatrix.copyFrom(matrix);
  16534. return this;
  16535. };
  16536. /**
  16537. * Returns the mesh Pose matrix.
  16538. * Returned object : Matrix
  16539. */
  16540. TransformNode.prototype.getPoseMatrix = function () {
  16541. return this._poseMatrix;
  16542. };
  16543. TransformNode.prototype._isSynchronized = function () {
  16544. if (this._isDirty) {
  16545. return false;
  16546. }
  16547. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE)
  16548. return false;
  16549. if (this._cache.pivotMatrixUpdated) {
  16550. return false;
  16551. }
  16552. if (this.infiniteDistance) {
  16553. return false;
  16554. }
  16555. if (!this._cache.position.equals(this.position))
  16556. return false;
  16557. if (this.rotationQuaternion) {
  16558. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  16559. return false;
  16560. }
  16561. if (!this._cache.rotation.equals(this.rotation))
  16562. return false;
  16563. if (!this._cache.scaling.equals(this.scaling))
  16564. return false;
  16565. return true;
  16566. };
  16567. TransformNode.prototype._initCache = function () {
  16568. _super.prototype._initCache.call(this);
  16569. this._cache.localMatrixUpdated = false;
  16570. this._cache.position = BABYLON.Vector3.Zero();
  16571. this._cache.scaling = BABYLON.Vector3.Zero();
  16572. this._cache.rotation = BABYLON.Vector3.Zero();
  16573. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  16574. this._cache.billboardMode = -1;
  16575. };
  16576. TransformNode.prototype.markAsDirty = function (property) {
  16577. if (property === "rotation") {
  16578. this.rotationQuaternion = null;
  16579. }
  16580. this._currentRenderId = Number.MAX_VALUE;
  16581. this._isDirty = true;
  16582. return this;
  16583. };
  16584. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  16585. /**
  16586. * Returns the current mesh absolute position.
  16587. * Retuns a Vector3.
  16588. */
  16589. get: function () {
  16590. return this._absolutePosition;
  16591. },
  16592. enumerable: true,
  16593. configurable: true
  16594. });
  16595. /**
  16596. * Sets a new matrix to apply before all other transformation
  16597. * @param matrix defines the transform matrix
  16598. * @returns the current TransformNode
  16599. */
  16600. TransformNode.prototype.setPreTransformMatrix = function (matrix) {
  16601. return this.setPivotMatrix(matrix, false);
  16602. };
  16603. /**
  16604. * Sets a new pivot matrix to the current node
  16605. * @param matrix defines the new pivot matrix to use
  16606. * @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
  16607. * @returns the current TransformNode
  16608. */
  16609. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  16610. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
  16611. this._pivotMatrix = matrix.clone();
  16612. this._cache.pivotMatrixUpdated = true;
  16613. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  16614. if (this._postMultiplyPivotMatrix) {
  16615. if (!this._pivotMatrixInverse) {
  16616. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  16617. }
  16618. else {
  16619. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  16620. }
  16621. }
  16622. return this;
  16623. };
  16624. /**
  16625. * Returns the mesh pivot matrix.
  16626. * Default : Identity.
  16627. * A Matrix is returned.
  16628. */
  16629. TransformNode.prototype.getPivotMatrix = function () {
  16630. return this._pivotMatrix;
  16631. };
  16632. /**
  16633. * Prevents the World matrix to be computed any longer.
  16634. * Returns the AbstractMesh.
  16635. */
  16636. TransformNode.prototype.freezeWorldMatrix = function () {
  16637. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  16638. this.computeWorldMatrix(true);
  16639. this._isWorldMatrixFrozen = true;
  16640. return this;
  16641. };
  16642. /**
  16643. * Allows back the World matrix computation.
  16644. * Returns the AbstractMesh.
  16645. */
  16646. TransformNode.prototype.unfreezeWorldMatrix = function () {
  16647. this._isWorldMatrixFrozen = false;
  16648. this.computeWorldMatrix(true);
  16649. return this;
  16650. };
  16651. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  16652. /**
  16653. * True if the World matrix has been frozen.
  16654. * Returns a boolean.
  16655. */
  16656. get: function () {
  16657. return this._isWorldMatrixFrozen;
  16658. },
  16659. enumerable: true,
  16660. configurable: true
  16661. });
  16662. /**
  16663. * Retuns the mesh absolute position in the World.
  16664. * Returns a Vector3.
  16665. */
  16666. TransformNode.prototype.getAbsolutePosition = function () {
  16667. this.computeWorldMatrix();
  16668. return this._absolutePosition;
  16669. };
  16670. /**
  16671. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  16672. * Returns the AbstractMesh.
  16673. */
  16674. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  16675. if (!absolutePosition) {
  16676. return this;
  16677. }
  16678. var absolutePositionX;
  16679. var absolutePositionY;
  16680. var absolutePositionZ;
  16681. if (absolutePosition.x === undefined) {
  16682. if (arguments.length < 3) {
  16683. return this;
  16684. }
  16685. absolutePositionX = arguments[0];
  16686. absolutePositionY = arguments[1];
  16687. absolutePositionZ = arguments[2];
  16688. }
  16689. else {
  16690. absolutePositionX = absolutePosition.x;
  16691. absolutePositionY = absolutePosition.y;
  16692. absolutePositionZ = absolutePosition.z;
  16693. }
  16694. if (this.parent) {
  16695. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  16696. invertParentWorldMatrix.invert();
  16697. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  16698. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  16699. }
  16700. else {
  16701. this.position.x = absolutePositionX;
  16702. this.position.y = absolutePositionY;
  16703. this.position.z = absolutePositionZ;
  16704. }
  16705. return this;
  16706. };
  16707. /**
  16708. * Sets the mesh position in its local space.
  16709. * Returns the AbstractMesh.
  16710. */
  16711. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  16712. this.computeWorldMatrix();
  16713. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  16714. return this;
  16715. };
  16716. /**
  16717. * Returns the mesh position in the local space from the current World matrix values.
  16718. * Returns a new Vector3.
  16719. */
  16720. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  16721. this.computeWorldMatrix();
  16722. var invLocalWorldMatrix = this._localWorld.clone();
  16723. invLocalWorldMatrix.invert();
  16724. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  16725. };
  16726. /**
  16727. * Translates the mesh along the passed Vector3 in its local space.
  16728. * Returns the AbstractMesh.
  16729. */
  16730. TransformNode.prototype.locallyTranslate = function (vector3) {
  16731. this.computeWorldMatrix(true);
  16732. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  16733. return this;
  16734. };
  16735. /**
  16736. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  16737. * @param targetPoint the position (must be in same space as current mesh) to look at
  16738. * @param yawCor optional yaw (y-axis) correction in radians
  16739. * @param pitchCor optional pitch (x-axis) correction in radians
  16740. * @param rollCor optional roll (z-axis) correction in radians
  16741. * @param space the choosen space of the target
  16742. * @returns the TransformNode.
  16743. */
  16744. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  16745. if (yawCor === void 0) { yawCor = 0; }
  16746. if (pitchCor === void 0) { pitchCor = 0; }
  16747. if (rollCor === void 0) { rollCor = 0; }
  16748. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  16749. var dv = BABYLON.AbstractMesh._lookAtVectorCache;
  16750. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  16751. targetPoint.subtractToRef(pos, dv);
  16752. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  16753. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  16754. var pitch = Math.atan2(dv.y, len);
  16755. if (this.rotationQuaternion) {
  16756. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  16757. }
  16758. else {
  16759. this.rotation.x = pitch + pitchCor;
  16760. this.rotation.y = yaw + yawCor;
  16761. this.rotation.z = rollCor;
  16762. }
  16763. return this;
  16764. };
  16765. /**
  16766. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  16767. * This Vector3 is expressed in the World space.
  16768. */
  16769. TransformNode.prototype.getDirection = function (localAxis) {
  16770. var result = BABYLON.Vector3.Zero();
  16771. this.getDirectionToRef(localAxis, result);
  16772. return result;
  16773. };
  16774. /**
  16775. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  16776. * localAxis is expressed in the mesh local space.
  16777. * result is computed in the Wordl space from the mesh World matrix.
  16778. * Returns the AbstractMesh.
  16779. */
  16780. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  16781. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  16782. return this;
  16783. };
  16784. /**
  16785. * Sets a new pivot point to the current node
  16786. * @param point defines the new pivot point to use
  16787. * @param space defines if the point is in world or local space (local by default)
  16788. * @returns the current TransformNode
  16789. */
  16790. TransformNode.prototype.setPivotPoint = function (point, space) {
  16791. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  16792. if (this.getScene().getRenderId() == 0) {
  16793. this.computeWorldMatrix(true);
  16794. }
  16795. var wm = this.getWorldMatrix();
  16796. if (space == BABYLON.Space.WORLD) {
  16797. var tmat = BABYLON.Tmp.Matrix[0];
  16798. wm.invertToRef(tmat);
  16799. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  16800. }
  16801. return this.setPivotMatrix(BABYLON.Matrix.Translation(-point.x, -point.y, -point.z), true);
  16802. };
  16803. /**
  16804. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  16805. */
  16806. TransformNode.prototype.getPivotPoint = function () {
  16807. var point = BABYLON.Vector3.Zero();
  16808. this.getPivotPointToRef(point);
  16809. return point;
  16810. };
  16811. /**
  16812. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  16813. * Returns the AbstractMesh.
  16814. */
  16815. TransformNode.prototype.getPivotPointToRef = function (result) {
  16816. result.x = -this._pivotMatrix.m[12];
  16817. result.y = -this._pivotMatrix.m[13];
  16818. result.z = -this._pivotMatrix.m[14];
  16819. return this;
  16820. };
  16821. /**
  16822. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  16823. */
  16824. TransformNode.prototype.getAbsolutePivotPoint = function () {
  16825. var point = BABYLON.Vector3.Zero();
  16826. this.getAbsolutePivotPointToRef(point);
  16827. return point;
  16828. };
  16829. /**
  16830. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  16831. * Returns the AbstractMesh.
  16832. */
  16833. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  16834. result.x = this._pivotMatrix.m[12];
  16835. result.y = this._pivotMatrix.m[13];
  16836. result.z = this._pivotMatrix.m[14];
  16837. this.getPivotPointToRef(result);
  16838. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  16839. return this;
  16840. };
  16841. /**
  16842. * Defines the passed node as the parent of the current node.
  16843. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  16844. * Returns the TransformNode.
  16845. */
  16846. TransformNode.prototype.setParent = function (node) {
  16847. if (node === null) {
  16848. var rotation = BABYLON.Tmp.Quaternion[0];
  16849. var position = BABYLON.Tmp.Vector3[0];
  16850. var scale = BABYLON.Tmp.Vector3[1];
  16851. if (this.parent && this.parent.computeWorldMatrix) {
  16852. this.parent.computeWorldMatrix(true);
  16853. }
  16854. this.computeWorldMatrix(true);
  16855. this.getWorldMatrix().decompose(scale, rotation, position);
  16856. if (this.rotationQuaternion) {
  16857. this.rotationQuaternion.copyFrom(rotation);
  16858. }
  16859. else {
  16860. rotation.toEulerAnglesToRef(this.rotation);
  16861. }
  16862. this.scaling.x = scale.x;
  16863. this.scaling.y = scale.y;
  16864. this.scaling.z = scale.z;
  16865. this.position.x = position.x;
  16866. this.position.y = position.y;
  16867. this.position.z = position.z;
  16868. }
  16869. else {
  16870. var rotation = BABYLON.Tmp.Quaternion[0];
  16871. var position = BABYLON.Tmp.Vector3[0];
  16872. var scale = BABYLON.Tmp.Vector3[1];
  16873. var diffMatrix = BABYLON.Tmp.Matrix[0];
  16874. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  16875. this.computeWorldMatrix(true);
  16876. node.computeWorldMatrix(true);
  16877. node.getWorldMatrix().invertToRef(invParentMatrix);
  16878. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  16879. diffMatrix.decompose(scale, rotation, position);
  16880. if (this.rotationQuaternion) {
  16881. this.rotationQuaternion.copyFrom(rotation);
  16882. }
  16883. else {
  16884. rotation.toEulerAnglesToRef(this.rotation);
  16885. }
  16886. this.position.x = position.x;
  16887. this.position.y = position.y;
  16888. this.position.z = position.z;
  16889. this.scaling.x = scale.x;
  16890. this.scaling.y = scale.y;
  16891. this.scaling.z = scale.z;
  16892. }
  16893. this.parent = node;
  16894. return this;
  16895. };
  16896. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  16897. get: function () {
  16898. return this._nonUniformScaling;
  16899. },
  16900. enumerable: true,
  16901. configurable: true
  16902. });
  16903. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  16904. if (this._nonUniformScaling === value) {
  16905. return false;
  16906. }
  16907. this._nonUniformScaling = true;
  16908. return true;
  16909. };
  16910. /**
  16911. * Attach the current TransformNode to another TransformNode associated with a bone
  16912. * @param bone Bone affecting the TransformNode
  16913. * @param affectedTransformNode TransformNode associated with the bone
  16914. */
  16915. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  16916. this._transformToBoneReferal = affectedTransformNode;
  16917. this.parent = bone;
  16918. if (bone.getWorldMatrix().determinant() < 0) {
  16919. this.scalingDeterminant *= -1;
  16920. }
  16921. return this;
  16922. };
  16923. TransformNode.prototype.detachFromBone = function () {
  16924. if (!this.parent) {
  16925. return this;
  16926. }
  16927. if (this.parent.getWorldMatrix().determinant() < 0) {
  16928. this.scalingDeterminant *= -1;
  16929. }
  16930. this._transformToBoneReferal = null;
  16931. this.parent = null;
  16932. return this;
  16933. };
  16934. /**
  16935. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  16936. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  16937. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  16938. * The passed axis is also normalized.
  16939. * Returns the AbstractMesh.
  16940. */
  16941. TransformNode.prototype.rotate = function (axis, amount, space) {
  16942. axis.normalize();
  16943. if (!this.rotationQuaternion) {
  16944. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  16945. this.rotation = BABYLON.Vector3.Zero();
  16946. }
  16947. var rotationQuaternion;
  16948. if (!space || space === BABYLON.Space.LOCAL) {
  16949. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, BABYLON.AbstractMesh._rotationAxisCache);
  16950. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  16951. }
  16952. else {
  16953. if (this.parent) {
  16954. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  16955. invertParentWorldMatrix.invert();
  16956. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  16957. }
  16958. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, BABYLON.AbstractMesh._rotationAxisCache);
  16959. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  16960. }
  16961. return this;
  16962. };
  16963. /**
  16964. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  16965. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  16966. * The passed axis is also normalized.
  16967. * Returns the AbstractMesh.
  16968. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  16969. */
  16970. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  16971. axis.normalize();
  16972. if (!this.rotationQuaternion) {
  16973. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  16974. this.rotation.copyFromFloats(0, 0, 0);
  16975. }
  16976. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  16977. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  16978. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  16979. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  16980. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  16981. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  16982. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  16983. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  16984. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  16985. return this;
  16986. };
  16987. /**
  16988. * Translates the mesh along the axis vector for the passed distance in the given space.
  16989. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  16990. * Returns the AbstractMesh.
  16991. */
  16992. TransformNode.prototype.translate = function (axis, distance, space) {
  16993. var displacementVector = axis.scale(distance);
  16994. if (!space || space === BABYLON.Space.LOCAL) {
  16995. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  16996. this.setPositionWithLocalVector(tempV3);
  16997. }
  16998. else {
  16999. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  17000. }
  17001. return this;
  17002. };
  17003. /**
  17004. * Adds a rotation step to the mesh current rotation.
  17005. * x, y, z are Euler angles expressed in radians.
  17006. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  17007. * This means this rotation is made in the mesh local space only.
  17008. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  17009. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  17010. * ```javascript
  17011. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  17012. * ```
  17013. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  17014. * 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.
  17015. * Returns the AbstractMesh.
  17016. */
  17017. TransformNode.prototype.addRotation = function (x, y, z) {
  17018. var rotationQuaternion;
  17019. if (this.rotationQuaternion) {
  17020. rotationQuaternion = this.rotationQuaternion;
  17021. }
  17022. else {
  17023. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  17024. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  17025. }
  17026. var accumulation = BABYLON.Tmp.Quaternion[0];
  17027. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  17028. rotationQuaternion.multiplyInPlace(accumulation);
  17029. if (!this.rotationQuaternion) {
  17030. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  17031. }
  17032. return this;
  17033. };
  17034. /**
  17035. * Computes the mesh World matrix and returns it.
  17036. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  17037. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  17038. * If the parameter `force`is set to `true`, the actual computation is done.
  17039. * Returns the mesh World Matrix.
  17040. */
  17041. TransformNode.prototype.computeWorldMatrix = function (force) {
  17042. if (this._isWorldMatrixFrozen) {
  17043. return this._worldMatrix;
  17044. }
  17045. if (!force && this.isSynchronized(true)) {
  17046. return this._worldMatrix;
  17047. }
  17048. this._cache.position.copyFrom(this.position);
  17049. this._cache.scaling.copyFrom(this.scaling);
  17050. this._cache.pivotMatrixUpdated = false;
  17051. this._cache.billboardMode = this.billboardMode;
  17052. this._currentRenderId = this.getScene().getRenderId();
  17053. this._isDirty = false;
  17054. // Scaling
  17055. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  17056. // Rotation
  17057. //rotate, if quaternion is set and rotation was used
  17058. if (this.rotationQuaternion) {
  17059. var len = this.rotation.length();
  17060. if (len) {
  17061. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  17062. this.rotation.copyFromFloats(0, 0, 0);
  17063. }
  17064. }
  17065. if (this.rotationQuaternion) {
  17066. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  17067. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  17068. }
  17069. else {
  17070. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  17071. this._cache.rotation.copyFrom(this.rotation);
  17072. }
  17073. // Translation
  17074. var camera = this.getScene().activeCamera;
  17075. if (this.infiniteDistance && !this.parent && camera) {
  17076. var cameraWorldMatrix = camera.getWorldMatrix();
  17077. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  17078. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  17079. }
  17080. else {
  17081. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  17082. }
  17083. // Composing transformations
  17084. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  17085. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  17086. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  17087. if (this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE && camera) {
  17088. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_ALL) !== BABYLON.AbstractMesh.BILLBOARDMODE_ALL) {
  17089. // Need to decompose each rotation here
  17090. var currentPosition = BABYLON.Tmp.Vector3[3];
  17091. if (this.parent && this.parent.getWorldMatrix) {
  17092. if (this._transformToBoneReferal) {
  17093. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  17094. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  17095. }
  17096. else {
  17097. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  17098. }
  17099. }
  17100. else {
  17101. currentPosition.copyFrom(this.position);
  17102. }
  17103. currentPosition.subtractInPlace(camera.globalPosition);
  17104. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  17105. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_X) === BABYLON.AbstractMesh.BILLBOARDMODE_X) {
  17106. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  17107. }
  17108. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Y) === BABYLON.AbstractMesh.BILLBOARDMODE_Y) {
  17109. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  17110. }
  17111. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Z) === BABYLON.AbstractMesh.BILLBOARDMODE_Z) {
  17112. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  17113. }
  17114. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  17115. }
  17116. else {
  17117. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  17118. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  17119. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  17120. }
  17121. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  17122. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  17123. }
  17124. // Local world
  17125. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  17126. // Parent
  17127. if (this.parent && this.parent.getWorldMatrix) {
  17128. if (this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE) {
  17129. if (this._transformToBoneReferal) {
  17130. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  17131. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  17132. }
  17133. else {
  17134. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  17135. }
  17136. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  17137. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  17138. this._worldMatrix.copyFrom(this._localWorld);
  17139. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  17140. }
  17141. else {
  17142. if (this._transformToBoneReferal) {
  17143. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  17144. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  17145. }
  17146. else {
  17147. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  17148. }
  17149. }
  17150. this._markSyncedWithParent();
  17151. }
  17152. else {
  17153. this._worldMatrix.copyFrom(this._localWorld);
  17154. }
  17155. // Post multiply inverse of pivotMatrix
  17156. if (this._postMultiplyPivotMatrix) {
  17157. this._worldMatrix.multiplyToRef(this._pivotMatrixInverse, this._worldMatrix);
  17158. }
  17159. // Normal matrix
  17160. if (this.scaling.isNonUniform) {
  17161. this._updateNonUniformScalingState(true);
  17162. }
  17163. else if (this.parent && this.parent._nonUniformScaling) {
  17164. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  17165. }
  17166. else {
  17167. this._updateNonUniformScalingState(false);
  17168. }
  17169. this._afterComputeWorldMatrix();
  17170. // Absolute position
  17171. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  17172. // Callbacks
  17173. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  17174. if (!this._poseMatrix) {
  17175. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  17176. }
  17177. // Cache the determinant
  17178. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  17179. return this._worldMatrix;
  17180. };
  17181. TransformNode.prototype._afterComputeWorldMatrix = function () {
  17182. };
  17183. /**
  17184. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  17185. * @param func: callback function to add
  17186. *
  17187. * Returns the TransformNode.
  17188. */
  17189. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  17190. this.onAfterWorldMatrixUpdateObservable.add(func);
  17191. return this;
  17192. };
  17193. /**
  17194. * Removes a registered callback function.
  17195. * Returns the TransformNode.
  17196. */
  17197. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  17198. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  17199. return this;
  17200. };
  17201. /**
  17202. * Clone the current transform node
  17203. * Returns the new transform node
  17204. * @param name Name of the new clone
  17205. * @param newParent New parent for the clone
  17206. * @param doNotCloneChildren Do not clone children hierarchy
  17207. */
  17208. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  17209. var _this = this;
  17210. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  17211. result.name = name;
  17212. result.id = name;
  17213. if (newParent) {
  17214. result.parent = newParent;
  17215. }
  17216. if (!doNotCloneChildren) {
  17217. // Children
  17218. var directDescendants = this.getDescendants(true);
  17219. for (var index = 0; index < directDescendants.length; index++) {
  17220. var child = directDescendants[index];
  17221. if (child.clone) {
  17222. child.clone(name + "." + child.name, result);
  17223. }
  17224. }
  17225. }
  17226. return result;
  17227. };
  17228. TransformNode.prototype.serialize = function (currentSerializationObject) {
  17229. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  17230. serializationObject.type = this.getClassName();
  17231. // Parent
  17232. if (this.parent) {
  17233. serializationObject.parentId = this.parent.id;
  17234. }
  17235. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  17236. serializationObject.tags = BABYLON.Tags.GetTags(this);
  17237. }
  17238. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  17239. serializationObject.isEnabled = this.isEnabled();
  17240. // Parent
  17241. if (this.parent) {
  17242. serializationObject.parentId = this.parent.id;
  17243. }
  17244. return serializationObject;
  17245. };
  17246. // Statics
  17247. /**
  17248. * Returns a new TransformNode object parsed from the source provided.
  17249. * The parameter `parsedMesh` is the source.
  17250. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  17251. */
  17252. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  17253. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  17254. if (BABYLON.Tags) {
  17255. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  17256. }
  17257. if (parsedTransformNode.localMatrix) {
  17258. transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  17259. }
  17260. else if (parsedTransformNode.pivotMatrix) {
  17261. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  17262. }
  17263. transformNode.setEnabled(parsedTransformNode.isEnabled);
  17264. // Parent
  17265. if (parsedTransformNode.parentId) {
  17266. transformNode._waitingParentId = parsedTransformNode.parentId;
  17267. }
  17268. return transformNode;
  17269. };
  17270. /**
  17271. * Releases resources associated with this transform node.
  17272. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  17273. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  17274. */
  17275. TransformNode.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  17276. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  17277. // Animations
  17278. this.getScene().stopAnimation(this);
  17279. // Remove from scene
  17280. this.getScene().removeTransformNode(this);
  17281. this.onAfterWorldMatrixUpdateObservable.clear();
  17282. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  17283. };
  17284. // Statics
  17285. TransformNode.BILLBOARDMODE_NONE = 0;
  17286. TransformNode.BILLBOARDMODE_X = 1;
  17287. TransformNode.BILLBOARDMODE_Y = 2;
  17288. TransformNode.BILLBOARDMODE_Z = 4;
  17289. TransformNode.BILLBOARDMODE_ALL = 7;
  17290. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  17291. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  17292. __decorate([
  17293. BABYLON.serializeAsVector3()
  17294. ], TransformNode.prototype, "_rotation", void 0);
  17295. __decorate([
  17296. BABYLON.serializeAsQuaternion()
  17297. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  17298. __decorate([
  17299. BABYLON.serializeAsVector3()
  17300. ], TransformNode.prototype, "_scaling", void 0);
  17301. __decorate([
  17302. BABYLON.serialize()
  17303. ], TransformNode.prototype, "billboardMode", void 0);
  17304. __decorate([
  17305. BABYLON.serialize()
  17306. ], TransformNode.prototype, "scalingDeterminant", void 0);
  17307. __decorate([
  17308. BABYLON.serialize()
  17309. ], TransformNode.prototype, "infiniteDistance", void 0);
  17310. __decorate([
  17311. BABYLON.serializeAsVector3()
  17312. ], TransformNode.prototype, "position", void 0);
  17313. return TransformNode;
  17314. }(BABYLON.Node));
  17315. BABYLON.TransformNode = TransformNode;
  17316. })(BABYLON || (BABYLON = {}));
  17317. //# sourceMappingURL=babylon.transformNode.js.map
  17318. var BABYLON;
  17319. (function (BABYLON) {
  17320. var AbstractMesh = /** @class */ (function (_super) {
  17321. __extends(AbstractMesh, _super);
  17322. // Constructor
  17323. function AbstractMesh(name, scene) {
  17324. if (scene === void 0) { scene = null; }
  17325. var _this = _super.call(this, name, scene, false) || this;
  17326. _this._facetNb = 0; // facet number
  17327. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  17328. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  17329. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  17330. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  17331. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  17332. _this._subDiv = {
  17333. max: 1,
  17334. X: 1,
  17335. Y: 1,
  17336. Z: 1
  17337. };
  17338. _this._facetDepthSort = false; // is the facet depth sort to be computed
  17339. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  17340. // Events
  17341. /**
  17342. * An event triggered when this mesh collides with another one
  17343. * @type {BABYLON.Observable}
  17344. */
  17345. _this.onCollideObservable = new BABYLON.Observable();
  17346. /**
  17347. * An event triggered when the collision's position changes
  17348. * @type {BABYLON.Observable}
  17349. */
  17350. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  17351. /**
  17352. * An event triggered when material is changed
  17353. * @type {BABYLON.Observable}
  17354. */
  17355. _this.onMaterialChangedObservable = new BABYLON.Observable();
  17356. // Properties
  17357. _this.definedFacingForward = true; // orientation for POV movement & rotation
  17358. /**
  17359. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  17360. * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  17361. * or
  17362. * 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.
  17363. * for more info check WebGl documentations
  17364. */
  17365. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  17366. /**
  17367. * 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:
  17368. * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  17369. * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  17370. * 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.
  17371. */
  17372. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  17373. /**
  17374. * 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.
  17375. * The default value is -1 which means don't break the query and wait till the result.
  17376. */
  17377. _this.occlusionRetryCount = -1;
  17378. _this._occlusionInternalRetryCounter = 0;
  17379. _this._isOccluded = false;
  17380. _this._isOcclusionQueryInProgress = false;
  17381. _this._visibility = 1.0;
  17382. _this.alphaIndex = Number.MAX_VALUE;
  17383. _this.isVisible = true;
  17384. _this.isPickable = true;
  17385. _this.showBoundingBox = false;
  17386. _this.showSubMeshesBoundingBox = false;
  17387. _this.isBlocker = false;
  17388. _this.enablePointerMoveEvents = false;
  17389. _this.renderingGroupId = 0;
  17390. _this._receiveShadows = false;
  17391. _this.renderOutline = false;
  17392. _this.outlineColor = BABYLON.Color3.Red();
  17393. _this.outlineWidth = 0.02;
  17394. _this.renderOverlay = false;
  17395. _this.overlayColor = BABYLON.Color3.Red();
  17396. _this.overlayAlpha = 0.5;
  17397. _this._hasVertexAlpha = false;
  17398. _this._useVertexColors = true;
  17399. _this._computeBonesUsingShaders = true;
  17400. _this._numBoneInfluencers = 4;
  17401. _this._applyFog = true;
  17402. _this.useOctreeForRenderingSelection = true;
  17403. _this.useOctreeForPicking = true;
  17404. _this.useOctreeForCollisions = true;
  17405. _this._layerMask = 0x0FFFFFFF;
  17406. /**
  17407. * True if the mesh must be rendered in any case.
  17408. */
  17409. _this.alwaysSelectAsActiveMesh = false;
  17410. /**
  17411. * This scene's action manager
  17412. * @type {BABYLON.ActionManager}
  17413. */
  17414. _this.actionManager = null;
  17415. // Physics
  17416. _this.physicsImpostor = null;
  17417. // Collisions
  17418. _this._checkCollisions = false;
  17419. _this._collisionMask = -1;
  17420. _this._collisionGroup = -1;
  17421. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  17422. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  17423. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  17424. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  17425. // Edges
  17426. _this.edgesWidth = 1;
  17427. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  17428. // Cache
  17429. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  17430. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  17431. _this._renderId = 0;
  17432. _this._intersectionsInProgress = new Array();
  17433. _this._unIndexed = false;
  17434. _this._lightSources = new Array();
  17435. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  17436. if (collidedMesh === void 0) { collidedMesh = null; }
  17437. //TODO move this to the collision coordinator!
  17438. if (_this.getScene().workerCollisions)
  17439. newPosition.multiplyInPlace(_this._collider._radius);
  17440. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  17441. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  17442. _this.position.addInPlace(_this._diffPositionForCollisions);
  17443. }
  17444. if (collidedMesh) {
  17445. _this.onCollideObservable.notifyObservers(collidedMesh);
  17446. }
  17447. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  17448. };
  17449. _this.getScene().addMesh(_this);
  17450. _this._resyncLightSources();
  17451. return _this;
  17452. }
  17453. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  17454. get: function () {
  17455. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  17456. },
  17457. enumerable: true,
  17458. configurable: true
  17459. });
  17460. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  17461. get: function () {
  17462. return BABYLON.TransformNode.BILLBOARDMODE_X;
  17463. },
  17464. enumerable: true,
  17465. configurable: true
  17466. });
  17467. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  17468. get: function () {
  17469. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  17470. },
  17471. enumerable: true,
  17472. configurable: true
  17473. });
  17474. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  17475. get: function () {
  17476. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  17477. },
  17478. enumerable: true,
  17479. configurable: true
  17480. });
  17481. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  17482. get: function () {
  17483. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  17484. },
  17485. enumerable: true,
  17486. configurable: true
  17487. });
  17488. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  17489. /**
  17490. * Read-only : the number of facets in the mesh
  17491. */
  17492. get: function () {
  17493. return this._facetNb;
  17494. },
  17495. enumerable: true,
  17496. configurable: true
  17497. });
  17498. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  17499. /**
  17500. * The number (integer) of subdivisions per axis in the partioning space
  17501. */
  17502. get: function () {
  17503. return this._partitioningSubdivisions;
  17504. },
  17505. set: function (nb) {
  17506. this._partitioningSubdivisions = nb;
  17507. },
  17508. enumerable: true,
  17509. configurable: true
  17510. });
  17511. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  17512. /**
  17513. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  17514. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
  17515. */
  17516. get: function () {
  17517. return this._partitioningBBoxRatio;
  17518. },
  17519. set: function (ratio) {
  17520. this._partitioningBBoxRatio = ratio;
  17521. },
  17522. enumerable: true,
  17523. configurable: true
  17524. });
  17525. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  17526. /**
  17527. * Boolean : must the facet be depth sorted on next call to `updateFacetData()` ?
  17528. * Works only for updatable meshes.
  17529. * Doesn't work with multi-materials.
  17530. */
  17531. get: function () {
  17532. return this._facetDepthSort;
  17533. },
  17534. set: function (sort) {
  17535. this._facetDepthSort = sort;
  17536. },
  17537. enumerable: true,
  17538. configurable: true
  17539. });
  17540. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  17541. /**
  17542. * The location (Vector3) where the facet depth sort must be computed from.
  17543. * By default, the active camera position.
  17544. * Used only when facet depth sort is enabled.
  17545. */
  17546. get: function () {
  17547. return this._facetDepthSortFrom;
  17548. },
  17549. set: function (location) {
  17550. this._facetDepthSortFrom = location;
  17551. },
  17552. enumerable: true,
  17553. configurable: true
  17554. });
  17555. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  17556. /**
  17557. * Read-only boolean : is the feature facetData enabled ?
  17558. */
  17559. get: function () {
  17560. return this._facetDataEnabled;
  17561. },
  17562. enumerable: true,
  17563. configurable: true
  17564. });
  17565. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  17566. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  17567. return false;
  17568. }
  17569. this._markSubMeshesAsMiscDirty();
  17570. return true;
  17571. };
  17572. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  17573. set: function (callback) {
  17574. if (this._onCollideObserver) {
  17575. this.onCollideObservable.remove(this._onCollideObserver);
  17576. }
  17577. this._onCollideObserver = this.onCollideObservable.add(callback);
  17578. },
  17579. enumerable: true,
  17580. configurable: true
  17581. });
  17582. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  17583. set: function (callback) {
  17584. if (this._onCollisionPositionChangeObserver) {
  17585. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  17586. }
  17587. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  17588. },
  17589. enumerable: true,
  17590. configurable: true
  17591. });
  17592. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  17593. /**
  17594. * 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.
  17595. */
  17596. get: function () {
  17597. return this._isOccluded;
  17598. },
  17599. set: function (value) {
  17600. this._isOccluded = value;
  17601. },
  17602. enumerable: true,
  17603. configurable: true
  17604. });
  17605. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  17606. /**
  17607. * Flag to check the progress status of the query
  17608. */
  17609. get: function () {
  17610. return this._isOcclusionQueryInProgress;
  17611. },
  17612. enumerable: true,
  17613. configurable: true
  17614. });
  17615. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  17616. /**
  17617. * Gets or sets mesh visibility between 0 and 1 (defult is 1)
  17618. */
  17619. get: function () {
  17620. return this._visibility;
  17621. },
  17622. /**
  17623. * Gets or sets mesh visibility between 0 and 1 (defult is 1)
  17624. */
  17625. set: function (value) {
  17626. if (this._visibility === value) {
  17627. return;
  17628. }
  17629. this._visibility = value;
  17630. this._markSubMeshesAsMiscDirty();
  17631. },
  17632. enumerable: true,
  17633. configurable: true
  17634. });
  17635. Object.defineProperty(AbstractMesh.prototype, "material", {
  17636. get: function () {
  17637. return this._material;
  17638. },
  17639. set: function (value) {
  17640. if (this._material === value) {
  17641. return;
  17642. }
  17643. this._material = value;
  17644. if (this.onMaterialChangedObservable.hasObservers) {
  17645. this.onMaterialChangedObservable.notifyObservers(this);
  17646. }
  17647. if (!this.subMeshes) {
  17648. return;
  17649. }
  17650. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  17651. var subMesh = _a[_i];
  17652. subMesh.setEffect(null);
  17653. }
  17654. },
  17655. enumerable: true,
  17656. configurable: true
  17657. });
  17658. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  17659. get: function () {
  17660. return this._receiveShadows;
  17661. },
  17662. set: function (value) {
  17663. if (this._receiveShadows === value) {
  17664. return;
  17665. }
  17666. this._receiveShadows = value;
  17667. this._markSubMeshesAsLightDirty();
  17668. },
  17669. enumerable: true,
  17670. configurable: true
  17671. });
  17672. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  17673. get: function () {
  17674. return this._hasVertexAlpha;
  17675. },
  17676. set: function (value) {
  17677. if (this._hasVertexAlpha === value) {
  17678. return;
  17679. }
  17680. this._hasVertexAlpha = value;
  17681. this._markSubMeshesAsAttributesDirty();
  17682. this._markSubMeshesAsMiscDirty();
  17683. },
  17684. enumerable: true,
  17685. configurable: true
  17686. });
  17687. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  17688. get: function () {
  17689. return this._useVertexColors;
  17690. },
  17691. set: function (value) {
  17692. if (this._useVertexColors === value) {
  17693. return;
  17694. }
  17695. this._useVertexColors = value;
  17696. this._markSubMeshesAsAttributesDirty();
  17697. },
  17698. enumerable: true,
  17699. configurable: true
  17700. });
  17701. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  17702. get: function () {
  17703. return this._computeBonesUsingShaders;
  17704. },
  17705. set: function (value) {
  17706. if (this._computeBonesUsingShaders === value) {
  17707. return;
  17708. }
  17709. this._computeBonesUsingShaders = value;
  17710. this._markSubMeshesAsAttributesDirty();
  17711. },
  17712. enumerable: true,
  17713. configurable: true
  17714. });
  17715. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  17716. get: function () {
  17717. return this._numBoneInfluencers;
  17718. },
  17719. set: function (value) {
  17720. if (this._numBoneInfluencers === value) {
  17721. return;
  17722. }
  17723. this._numBoneInfluencers = value;
  17724. this._markSubMeshesAsAttributesDirty();
  17725. },
  17726. enumerable: true,
  17727. configurable: true
  17728. });
  17729. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  17730. get: function () {
  17731. return this._applyFog;
  17732. },
  17733. set: function (value) {
  17734. if (this._applyFog === value) {
  17735. return;
  17736. }
  17737. this._applyFog = value;
  17738. this._markSubMeshesAsMiscDirty();
  17739. },
  17740. enumerable: true,
  17741. configurable: true
  17742. });
  17743. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  17744. get: function () {
  17745. return this._layerMask;
  17746. },
  17747. set: function (value) {
  17748. if (value === this._layerMask) {
  17749. return;
  17750. }
  17751. this._layerMask = value;
  17752. this._resyncLightSources();
  17753. },
  17754. enumerable: true,
  17755. configurable: true
  17756. });
  17757. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  17758. get: function () {
  17759. return this._collisionMask;
  17760. },
  17761. set: function (mask) {
  17762. this._collisionMask = !isNaN(mask) ? mask : -1;
  17763. },
  17764. enumerable: true,
  17765. configurable: true
  17766. });
  17767. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  17768. get: function () {
  17769. return this._collisionGroup;
  17770. },
  17771. set: function (mask) {
  17772. this._collisionGroup = !isNaN(mask) ? mask : -1;
  17773. },
  17774. enumerable: true,
  17775. configurable: true
  17776. });
  17777. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  17778. get: function () {
  17779. return null;
  17780. },
  17781. enumerable: true,
  17782. configurable: true
  17783. });
  17784. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  17785. get: function () {
  17786. return this._skeleton;
  17787. },
  17788. set: function (value) {
  17789. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  17790. this._skeleton._unregisterMeshWithPoseMatrix(this);
  17791. }
  17792. if (value && value.needInitialSkinMatrix) {
  17793. value._registerMeshWithPoseMatrix(this);
  17794. }
  17795. this._skeleton = value;
  17796. if (!this._skeleton) {
  17797. this._bonesTransformMatrices = null;
  17798. }
  17799. this._markSubMeshesAsAttributesDirty();
  17800. },
  17801. enumerable: true,
  17802. configurable: true
  17803. });
  17804. /**
  17805. * Returns the string "AbstractMesh"
  17806. */
  17807. AbstractMesh.prototype.getClassName = function () {
  17808. return "AbstractMesh";
  17809. };
  17810. /**
  17811. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  17812. */
  17813. AbstractMesh.prototype.toString = function (fullDetails) {
  17814. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  17815. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  17816. if (this._skeleton) {
  17817. ret += ", skeleton: " + this._skeleton.name;
  17818. }
  17819. if (fullDetails) {
  17820. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  17821. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  17822. }
  17823. return ret;
  17824. };
  17825. AbstractMesh.prototype._rebuild = function () {
  17826. if (this._occlusionQuery) {
  17827. this._occlusionQuery = null;
  17828. }
  17829. if (this._edgesRenderer) {
  17830. this._edgesRenderer._rebuild();
  17831. }
  17832. if (!this.subMeshes) {
  17833. return;
  17834. }
  17835. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  17836. var subMesh = _a[_i];
  17837. subMesh._rebuild();
  17838. }
  17839. };
  17840. AbstractMesh.prototype._resyncLightSources = function () {
  17841. this._lightSources.length = 0;
  17842. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  17843. var light = _a[_i];
  17844. if (!light.isEnabled()) {
  17845. continue;
  17846. }
  17847. if (light.canAffectMesh(this)) {
  17848. this._lightSources.push(light);
  17849. }
  17850. }
  17851. this._markSubMeshesAsLightDirty();
  17852. };
  17853. AbstractMesh.prototype._resyncLighSource = function (light) {
  17854. var isIn = light.isEnabled() && light.canAffectMesh(this);
  17855. var index = this._lightSources.indexOf(light);
  17856. if (index === -1) {
  17857. if (!isIn) {
  17858. return;
  17859. }
  17860. this._lightSources.push(light);
  17861. }
  17862. else {
  17863. if (isIn) {
  17864. return;
  17865. }
  17866. this._lightSources.splice(index, 1);
  17867. }
  17868. this._markSubMeshesAsLightDirty();
  17869. };
  17870. AbstractMesh.prototype._removeLightSource = function (light) {
  17871. var index = this._lightSources.indexOf(light);
  17872. if (index === -1) {
  17873. return;
  17874. }
  17875. this._lightSources.splice(index, 1);
  17876. this._markSubMeshesAsLightDirty();
  17877. };
  17878. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  17879. if (!this.subMeshes) {
  17880. return;
  17881. }
  17882. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  17883. var subMesh = _a[_i];
  17884. if (subMesh._materialDefines) {
  17885. func(subMesh._materialDefines);
  17886. }
  17887. }
  17888. };
  17889. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  17890. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  17891. };
  17892. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  17893. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  17894. };
  17895. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  17896. if (!this.subMeshes) {
  17897. return;
  17898. }
  17899. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  17900. var subMesh = _a[_i];
  17901. var material = subMesh.getMaterial();
  17902. if (material) {
  17903. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  17904. }
  17905. }
  17906. };
  17907. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  17908. /**
  17909. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  17910. * Default : (1.0, 1.0, 1.0)
  17911. */
  17912. get: function () {
  17913. return this._scaling;
  17914. },
  17915. /**
  17916. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  17917. * Default : (1.0, 1.0, 1.0)
  17918. */
  17919. set: function (newScaling) {
  17920. this._scaling = newScaling;
  17921. if (this.physicsImpostor) {
  17922. this.physicsImpostor.forceUpdate();
  17923. }
  17924. },
  17925. enumerable: true,
  17926. configurable: true
  17927. });
  17928. // Methods
  17929. /**
  17930. * Disables the mesh edger rendering mode.
  17931. * Returns the AbstractMesh.
  17932. */
  17933. AbstractMesh.prototype.disableEdgesRendering = function () {
  17934. if (this._edgesRenderer) {
  17935. this._edgesRenderer.dispose();
  17936. this._edgesRenderer = null;
  17937. }
  17938. return this;
  17939. };
  17940. /**
  17941. * Enables the edge rendering mode on the mesh.
  17942. * This mode makes the mesh edges visible.
  17943. * Returns the AbstractMesh.
  17944. */
  17945. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  17946. if (epsilon === void 0) { epsilon = 0.95; }
  17947. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  17948. this.disableEdgesRendering();
  17949. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  17950. return this;
  17951. };
  17952. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  17953. /**
  17954. * Returns true if the mesh is blocked. Used by the class Mesh.
  17955. * Returns the boolean `false` by default.
  17956. */
  17957. get: function () {
  17958. return false;
  17959. },
  17960. enumerable: true,
  17961. configurable: true
  17962. });
  17963. /**
  17964. * Returns the mesh itself by default, used by the class Mesh.
  17965. * Returned type : AbstractMesh
  17966. */
  17967. AbstractMesh.prototype.getLOD = function (camera) {
  17968. return this;
  17969. };
  17970. /**
  17971. * Returns 0 by default, used by the class Mesh.
  17972. * Returns an integer.
  17973. */
  17974. AbstractMesh.prototype.getTotalVertices = function () {
  17975. return 0;
  17976. };
  17977. /**
  17978. * Returns null by default, used by the class Mesh.
  17979. * Returned type : integer array
  17980. */
  17981. AbstractMesh.prototype.getIndices = function () {
  17982. return null;
  17983. };
  17984. /**
  17985. * Returns the array of the requested vertex data kind. Used by the class Mesh. Returns null here.
  17986. * Returned type : float array or Float32Array
  17987. */
  17988. AbstractMesh.prototype.getVerticesData = function (kind) {
  17989. return null;
  17990. };
  17991. /**
  17992. * Sets the vertex data of the mesh geometry for the requested `kind`.
  17993. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  17994. * The `data` are either a numeric array either a Float32Array.
  17995. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  17996. * 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).
  17997. * Note that a new underlying VertexBuffer object is created each call.
  17998. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  17999. *
  18000. * Possible `kind` values :
  18001. * - BABYLON.VertexBuffer.PositionKind
  18002. * - BABYLON.VertexBuffer.UVKind
  18003. * - BABYLON.VertexBuffer.UV2Kind
  18004. * - BABYLON.VertexBuffer.UV3Kind
  18005. * - BABYLON.VertexBuffer.UV4Kind
  18006. * - BABYLON.VertexBuffer.UV5Kind
  18007. * - BABYLON.VertexBuffer.UV6Kind
  18008. * - BABYLON.VertexBuffer.ColorKind
  18009. * - BABYLON.VertexBuffer.MatricesIndicesKind
  18010. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  18011. * - BABYLON.VertexBuffer.MatricesWeightsKind
  18012. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  18013. *
  18014. * Returns the Mesh.
  18015. */
  18016. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  18017. return this;
  18018. };
  18019. /**
  18020. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  18021. * If the mesh has no geometry, it is simply returned as it is.
  18022. * The `data` are either a numeric array either a Float32Array.
  18023. * No new underlying VertexBuffer object is created.
  18024. * 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.
  18025. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  18026. *
  18027. * Possible `kind` values :
  18028. * - BABYLON.VertexBuffer.PositionKind
  18029. * - BABYLON.VertexBuffer.UVKind
  18030. * - BABYLON.VertexBuffer.UV2Kind
  18031. * - BABYLON.VertexBuffer.UV3Kind
  18032. * - BABYLON.VertexBuffer.UV4Kind
  18033. * - BABYLON.VertexBuffer.UV5Kind
  18034. * - BABYLON.VertexBuffer.UV6Kind
  18035. * - BABYLON.VertexBuffer.ColorKind
  18036. * - BABYLON.VertexBuffer.MatricesIndicesKind
  18037. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  18038. * - BABYLON.VertexBuffer.MatricesWeightsKind
  18039. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  18040. *
  18041. * Returns the Mesh.
  18042. */
  18043. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  18044. return this;
  18045. };
  18046. /**
  18047. * Sets the mesh indices.
  18048. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  18049. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  18050. * This method creates a new index buffer each call.
  18051. * Returns the Mesh.
  18052. */
  18053. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  18054. return this;
  18055. };
  18056. /** Returns false by default, used by the class Mesh.
  18057. * Returns a boolean
  18058. */
  18059. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  18060. return false;
  18061. };
  18062. /**
  18063. * Returns the mesh BoundingInfo object or creates a new one and returns it if undefined.
  18064. * Returns a BoundingInfo
  18065. */
  18066. AbstractMesh.prototype.getBoundingInfo = function () {
  18067. if (this._masterMesh) {
  18068. return this._masterMesh.getBoundingInfo();
  18069. }
  18070. if (!this._boundingInfo) {
  18071. // this._boundingInfo is being created here
  18072. this._updateBoundingInfo();
  18073. }
  18074. // cannot be null.
  18075. return this._boundingInfo;
  18076. };
  18077. /**
  18078. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units).
  18079. * @param includeDescendants Take the hierarchy's bounding box instead of the mesh's bounding box.
  18080. */
  18081. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  18082. if (includeDescendants === void 0) { includeDescendants = true; }
  18083. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  18084. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  18085. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  18086. if (maxDimension === 0) {
  18087. return this;
  18088. }
  18089. var scale = 1 / maxDimension;
  18090. this.scaling.scaleInPlace(scale);
  18091. return this;
  18092. };
  18093. /**
  18094. * Sets a mesh new object BoundingInfo.
  18095. * Returns the AbstractMesh.
  18096. */
  18097. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  18098. this._boundingInfo = boundingInfo;
  18099. return this;
  18100. };
  18101. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  18102. get: function () {
  18103. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  18104. },
  18105. enumerable: true,
  18106. configurable: true
  18107. });
  18108. AbstractMesh.prototype._preActivate = function () {
  18109. };
  18110. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  18111. };
  18112. AbstractMesh.prototype._activate = function (renderId) {
  18113. this._renderId = renderId;
  18114. };
  18115. /**
  18116. * Returns the latest update of the World matrix
  18117. * Returns a Matrix.
  18118. */
  18119. AbstractMesh.prototype.getWorldMatrix = function () {
  18120. if (this._masterMesh) {
  18121. return this._masterMesh.getWorldMatrix();
  18122. }
  18123. return _super.prototype.getWorldMatrix.call(this);
  18124. };
  18125. /**
  18126. * Returns the latest update of the World matrix determinant.
  18127. */
  18128. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  18129. if (this._masterMesh) {
  18130. return this._masterMesh._getWorldMatrixDeterminant();
  18131. }
  18132. return _super.prototype._getWorldMatrixDeterminant.call(this);
  18133. };
  18134. // ================================== Point of View Movement =================================
  18135. /**
  18136. * Perform relative position change from the point of view of behind the front of the mesh.
  18137. * This is performed taking into account the meshes current rotation, so you do not have to care.
  18138. * Supports definition of mesh facing forward or backward.
  18139. * @param {number} amountRight
  18140. * @param {number} amountUp
  18141. * @param {number} amountForward
  18142. *
  18143. * Returns the AbstractMesh.
  18144. */
  18145. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  18146. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  18147. return this;
  18148. };
  18149. /**
  18150. * Calculate relative position change from the point of view of behind the front of the mesh.
  18151. * This is performed taking into account the meshes current rotation, so you do not have to care.
  18152. * Supports definition of mesh facing forward or backward.
  18153. * @param {number} amountRight
  18154. * @param {number} amountUp
  18155. * @param {number} amountForward
  18156. *
  18157. * Returns a new Vector3.
  18158. */
  18159. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  18160. var rotMatrix = new BABYLON.Matrix();
  18161. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  18162. rotQuaternion.toRotationMatrix(rotMatrix);
  18163. var translationDelta = BABYLON.Vector3.Zero();
  18164. var defForwardMult = this.definedFacingForward ? -1 : 1;
  18165. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  18166. return translationDelta;
  18167. };
  18168. // ================================== Point of View Rotation =================================
  18169. /**
  18170. * Perform relative rotation change from the point of view of behind the front of the mesh.
  18171. * Supports definition of mesh facing forward or backward.
  18172. * @param {number} flipBack
  18173. * @param {number} twirlClockwise
  18174. * @param {number} tiltRight
  18175. *
  18176. * Returns the AbstractMesh.
  18177. */
  18178. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  18179. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  18180. return this;
  18181. };
  18182. /**
  18183. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  18184. * Supports definition of mesh facing forward or backward.
  18185. * @param {number} flipBack
  18186. * @param {number} twirlClockwise
  18187. * @param {number} tiltRight
  18188. *
  18189. * Returns a new Vector3.
  18190. */
  18191. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  18192. var defForwardMult = this.definedFacingForward ? 1 : -1;
  18193. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  18194. };
  18195. /**
  18196. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  18197. * @param includeDescendants Include bounding info from descendants as well (true by default).
  18198. */
  18199. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants) {
  18200. if (includeDescendants === void 0) { includeDescendants = true; }
  18201. this.computeWorldMatrix(true);
  18202. var min;
  18203. var max;
  18204. var boundingInfo = this.getBoundingInfo();
  18205. if (!this.subMeshes) {
  18206. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  18207. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  18208. }
  18209. else {
  18210. min = boundingInfo.boundingBox.minimumWorld;
  18211. max = boundingInfo.boundingBox.maximumWorld;
  18212. }
  18213. if (includeDescendants) {
  18214. var descendants = this.getDescendants(false);
  18215. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  18216. var descendant = descendants_1[_i];
  18217. var childMesh = descendant;
  18218. childMesh.computeWorldMatrix(true);
  18219. //make sure we have the needed params to get mix and max
  18220. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  18221. continue;
  18222. }
  18223. var childBoundingInfo = childMesh.getBoundingInfo();
  18224. var boundingBox = childBoundingInfo.boundingBox;
  18225. var minBox = boundingBox.minimumWorld;
  18226. var maxBox = boundingBox.maximumWorld;
  18227. BABYLON.Tools.CheckExtends(minBox, min, max);
  18228. BABYLON.Tools.CheckExtends(maxBox, min, max);
  18229. }
  18230. }
  18231. return {
  18232. min: min,
  18233. max: max
  18234. };
  18235. };
  18236. /**
  18237. * Updates the mesh BoundingInfo object and all its children BoundingInfo objects also.
  18238. * Returns the AbstractMesh.
  18239. */
  18240. AbstractMesh.prototype._updateBoundingInfo = function () {
  18241. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  18242. this._boundingInfo.update(this.worldMatrixFromCache);
  18243. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  18244. return this;
  18245. };
  18246. /**
  18247. * Update a mesh's children BoundingInfo objects only.
  18248. * Returns the AbstractMesh.
  18249. */
  18250. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  18251. if (!this.subMeshes) {
  18252. return this;
  18253. }
  18254. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  18255. var subMesh = this.subMeshes[subIndex];
  18256. if (!subMesh.IsGlobal) {
  18257. subMesh.updateBoundingInfo(matrix);
  18258. }
  18259. }
  18260. return this;
  18261. };
  18262. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  18263. // Bounding info
  18264. this._updateBoundingInfo();
  18265. };
  18266. /**
  18267. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  18268. * A mesh is in the frustum if its bounding box intersects the frustum.
  18269. * Boolean returned.
  18270. */
  18271. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  18272. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  18273. };
  18274. /**
  18275. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  18276. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  18277. * Boolean returned.
  18278. */
  18279. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18280. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  18281. ;
  18282. };
  18283. /**
  18284. * True if the mesh intersects another mesh or a SolidParticle object.
  18285. * 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)
  18286. * includeDescendants can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  18287. * Returns a boolean.
  18288. */
  18289. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  18290. if (precise === void 0) { precise = false; }
  18291. if (!this._boundingInfo || !mesh._boundingInfo) {
  18292. return false;
  18293. }
  18294. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  18295. return true;
  18296. }
  18297. if (includeDescendants) {
  18298. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  18299. var child = _a[_i];
  18300. if (child.intersectsMesh(mesh, precise, true)) {
  18301. return true;
  18302. }
  18303. }
  18304. }
  18305. return false;
  18306. };
  18307. /**
  18308. * Returns true if the passed point (Vector3) is inside the mesh bounding box.
  18309. * Returns a boolean.
  18310. */
  18311. AbstractMesh.prototype.intersectsPoint = function (point) {
  18312. if (!this._boundingInfo) {
  18313. return false;
  18314. }
  18315. return this._boundingInfo.intersectsPoint(point);
  18316. };
  18317. AbstractMesh.prototype.getPhysicsImpostor = function () {
  18318. return this.physicsImpostor;
  18319. };
  18320. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  18321. if (camera === void 0) { camera = null; }
  18322. if (!camera) {
  18323. camera = this.getScene().activeCamera;
  18324. }
  18325. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  18326. };
  18327. /**
  18328. * Returns the distance from the mesh to the active camera.
  18329. * Returns a float.
  18330. */
  18331. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  18332. if (camera === void 0) { camera = null; }
  18333. if (!camera) {
  18334. camera = this.getScene().activeCamera;
  18335. }
  18336. return this.absolutePosition.subtract(camera.position).length();
  18337. };
  18338. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  18339. if (!this.physicsImpostor) {
  18340. return this;
  18341. }
  18342. this.physicsImpostor.applyImpulse(force, contactPoint);
  18343. return this;
  18344. };
  18345. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  18346. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  18347. return this;
  18348. }
  18349. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  18350. mainPivot: pivot1,
  18351. connectedPivot: pivot2,
  18352. nativeParams: options
  18353. });
  18354. return this;
  18355. };
  18356. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  18357. // Collisions
  18358. /**
  18359. * Property checkCollisions : Boolean, whether the camera should check the collisions against the mesh.
  18360. * Default `false`.
  18361. */
  18362. get: function () {
  18363. return this._checkCollisions;
  18364. },
  18365. set: function (collisionEnabled) {
  18366. this._checkCollisions = collisionEnabled;
  18367. if (this.getScene().workerCollisions) {
  18368. this.getScene().collisionCoordinator.onMeshUpdated(this);
  18369. }
  18370. },
  18371. enumerable: true,
  18372. configurable: true
  18373. });
  18374. Object.defineProperty(AbstractMesh.prototype, "collider", {
  18375. /**
  18376. * Gets Collider object used to compute collisions (not physics)
  18377. */
  18378. get: function () {
  18379. return this._collider;
  18380. },
  18381. enumerable: true,
  18382. configurable: true
  18383. });
  18384. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  18385. var globalPosition = this.getAbsolutePosition();
  18386. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  18387. if (!this._collider) {
  18388. this._collider = new BABYLON.Collider();
  18389. }
  18390. this._collider._radius = this.ellipsoid;
  18391. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  18392. return this;
  18393. };
  18394. // Submeshes octree
  18395. /**
  18396. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  18397. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree.
  18398. * Returns an Octree of submeshes.
  18399. */
  18400. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  18401. if (maxCapacity === void 0) { maxCapacity = 64; }
  18402. if (maxDepth === void 0) { maxDepth = 2; }
  18403. if (!this._submeshesOctree) {
  18404. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  18405. }
  18406. this.computeWorldMatrix(true);
  18407. var boundingInfo = this.getBoundingInfo();
  18408. // Update octree
  18409. var bbox = boundingInfo.boundingBox;
  18410. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  18411. return this._submeshesOctree;
  18412. };
  18413. // Collisions
  18414. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  18415. this._generatePointsArray();
  18416. if (!this._positions) {
  18417. return this;
  18418. }
  18419. // Transformation
  18420. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  18421. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  18422. subMesh._lastColliderWorldVertices = [];
  18423. subMesh._trianglePlanes = [];
  18424. var start = subMesh.verticesStart;
  18425. var end = (subMesh.verticesStart + subMesh.verticesCount);
  18426. for (var i = start; i < end; i++) {
  18427. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  18428. }
  18429. }
  18430. // Collide
  18431. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  18432. if (collider.collisionFound) {
  18433. collider.collidedMesh = this;
  18434. }
  18435. return this;
  18436. };
  18437. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  18438. var subMeshes;
  18439. var len;
  18440. // Octrees
  18441. if (this._submeshesOctree && this.useOctreeForCollisions) {
  18442. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  18443. var intersections = this._submeshesOctree.intersects(collider._basePointWorld, radius);
  18444. len = intersections.length;
  18445. subMeshes = intersections.data;
  18446. }
  18447. else {
  18448. subMeshes = this.subMeshes;
  18449. len = subMeshes.length;
  18450. }
  18451. for (var index = 0; index < len; index++) {
  18452. var subMesh = subMeshes[index];
  18453. // Bounding test
  18454. if (len > 1 && !subMesh._checkCollision(collider))
  18455. continue;
  18456. this._collideForSubMesh(subMesh, transformMatrix, collider);
  18457. }
  18458. return this;
  18459. };
  18460. AbstractMesh.prototype._checkCollision = function (collider) {
  18461. // Bounding box test
  18462. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  18463. return this;
  18464. // Transformation matrix
  18465. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  18466. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  18467. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  18468. return this;
  18469. };
  18470. // Picking
  18471. AbstractMesh.prototype._generatePointsArray = function () {
  18472. return false;
  18473. };
  18474. /**
  18475. * Checks if the passed Ray intersects with the mesh.
  18476. * Returns an object PickingInfo.
  18477. */
  18478. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  18479. var pickingInfo = new BABYLON.PickingInfo();
  18480. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  18481. return pickingInfo;
  18482. }
  18483. if (!this._generatePointsArray()) {
  18484. return pickingInfo;
  18485. }
  18486. var intersectInfo = null;
  18487. // Octrees
  18488. var subMeshes;
  18489. var len;
  18490. if (this._submeshesOctree && this.useOctreeForPicking) {
  18491. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  18492. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  18493. len = intersections.length;
  18494. subMeshes = intersections.data;
  18495. }
  18496. else {
  18497. subMeshes = this.subMeshes;
  18498. len = subMeshes.length;
  18499. }
  18500. for (var index = 0; index < len; index++) {
  18501. var subMesh = subMeshes[index];
  18502. // Bounding test
  18503. if (len > 1 && !subMesh.canIntersects(ray))
  18504. continue;
  18505. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  18506. if (currentIntersectInfo) {
  18507. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  18508. intersectInfo = currentIntersectInfo;
  18509. intersectInfo.subMeshId = index;
  18510. if (fastCheck) {
  18511. break;
  18512. }
  18513. }
  18514. }
  18515. }
  18516. if (intersectInfo) {
  18517. // Get picked point
  18518. var world = this.getWorldMatrix();
  18519. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  18520. var direction = ray.direction.clone();
  18521. direction = direction.scale(intersectInfo.distance);
  18522. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  18523. var pickedPoint = worldOrigin.add(worldDirection);
  18524. // Return result
  18525. pickingInfo.hit = true;
  18526. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  18527. pickingInfo.pickedPoint = pickedPoint;
  18528. pickingInfo.pickedMesh = this;
  18529. pickingInfo.bu = intersectInfo.bu || 0;
  18530. pickingInfo.bv = intersectInfo.bv || 0;
  18531. pickingInfo.faceId = intersectInfo.faceId;
  18532. pickingInfo.subMeshId = intersectInfo.subMeshId;
  18533. return pickingInfo;
  18534. }
  18535. return pickingInfo;
  18536. };
  18537. /**
  18538. * Clones the mesh, used by the class Mesh.
  18539. * Just returns `null` for an AbstractMesh.
  18540. */
  18541. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  18542. return null;
  18543. };
  18544. /**
  18545. * Disposes all the mesh submeshes.
  18546. * Returns the AbstractMesh.
  18547. */
  18548. AbstractMesh.prototype.releaseSubMeshes = function () {
  18549. if (this.subMeshes) {
  18550. while (this.subMeshes.length) {
  18551. this.subMeshes[0].dispose();
  18552. }
  18553. }
  18554. else {
  18555. this.subMeshes = new Array();
  18556. }
  18557. return this;
  18558. };
  18559. /**
  18560. * Releases resources associated with this abstract mesh.
  18561. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  18562. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  18563. */
  18564. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  18565. var _this = this;
  18566. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  18567. var index;
  18568. // Smart Array Retainers.
  18569. this.getScene().freeActiveMeshes();
  18570. this.getScene().freeRenderingGroups();
  18571. // Action manager
  18572. if (this.actionManager !== undefined && this.actionManager !== null) {
  18573. this.actionManager.dispose();
  18574. this.actionManager = null;
  18575. }
  18576. // Skeleton
  18577. this.skeleton = null;
  18578. // Physics
  18579. if (this.physicsImpostor) {
  18580. this.physicsImpostor.dispose();
  18581. }
  18582. // Intersections in progress
  18583. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  18584. var other = this._intersectionsInProgress[index];
  18585. var pos = other._intersectionsInProgress.indexOf(this);
  18586. other._intersectionsInProgress.splice(pos, 1);
  18587. }
  18588. this._intersectionsInProgress = [];
  18589. // Lights
  18590. var lights = this.getScene().lights;
  18591. lights.forEach(function (light) {
  18592. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  18593. if (meshIndex !== -1) {
  18594. light.includedOnlyMeshes.splice(meshIndex, 1);
  18595. }
  18596. meshIndex = light.excludedMeshes.indexOf(_this);
  18597. if (meshIndex !== -1) {
  18598. light.excludedMeshes.splice(meshIndex, 1);
  18599. }
  18600. // Shadow generators
  18601. var generator = light.getShadowGenerator();
  18602. if (generator) {
  18603. var shadowMap = generator.getShadowMap();
  18604. if (shadowMap && shadowMap.renderList) {
  18605. meshIndex = shadowMap.renderList.indexOf(_this);
  18606. if (meshIndex !== -1) {
  18607. shadowMap.renderList.splice(meshIndex, 1);
  18608. }
  18609. }
  18610. }
  18611. });
  18612. // Edges
  18613. if (this._edgesRenderer) {
  18614. this._edgesRenderer.dispose();
  18615. this._edgesRenderer = null;
  18616. }
  18617. // SubMeshes
  18618. if (this.getClassName() !== "InstancedMesh") {
  18619. this.releaseSubMeshes();
  18620. }
  18621. // Octree
  18622. var sceneOctree = this.getScene().selectionOctree;
  18623. if (sceneOctree !== undefined && sceneOctree !== null) {
  18624. var index = sceneOctree.dynamicContent.indexOf(this);
  18625. if (index !== -1) {
  18626. sceneOctree.dynamicContent.splice(index, 1);
  18627. }
  18628. }
  18629. // Query
  18630. var engine = this.getScene().getEngine();
  18631. if (this._occlusionQuery) {
  18632. this._isOcclusionQueryInProgress = false;
  18633. engine.deleteQuery(this._occlusionQuery);
  18634. this._occlusionQuery = null;
  18635. }
  18636. // Engine
  18637. engine.wipeCaches();
  18638. // Remove from scene
  18639. this.getScene().removeMesh(this);
  18640. if (disposeMaterialAndTextures) {
  18641. if (this.material) {
  18642. this.material.dispose(false, true);
  18643. }
  18644. }
  18645. if (!doNotRecurse) {
  18646. // Particles
  18647. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  18648. if (this.getScene().particleSystems[index].emitter === this) {
  18649. this.getScene().particleSystems[index].dispose();
  18650. index--;
  18651. }
  18652. }
  18653. }
  18654. // facet data
  18655. if (this._facetDataEnabled) {
  18656. this.disableFacetData();
  18657. }
  18658. this.onAfterWorldMatrixUpdateObservable.clear();
  18659. this.onCollideObservable.clear();
  18660. this.onCollisionPositionChangeObservable.clear();
  18661. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  18662. };
  18663. /**
  18664. * Adds the passed mesh as a child to the current mesh.
  18665. * Returns the AbstractMesh.
  18666. */
  18667. AbstractMesh.prototype.addChild = function (mesh) {
  18668. mesh.setParent(this);
  18669. return this;
  18670. };
  18671. /**
  18672. * Removes the passed mesh from the current mesh children list.
  18673. * Returns the AbstractMesh.
  18674. */
  18675. AbstractMesh.prototype.removeChild = function (mesh) {
  18676. mesh.setParent(null);
  18677. return this;
  18678. };
  18679. // Facet data
  18680. /**
  18681. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning.
  18682. * Returns the AbstractMesh.
  18683. */
  18684. AbstractMesh.prototype._initFacetData = function () {
  18685. if (!this._facetNormals) {
  18686. this._facetNormals = new Array();
  18687. }
  18688. if (!this._facetPositions) {
  18689. this._facetPositions = new Array();
  18690. }
  18691. if (!this._facetPartitioning) {
  18692. this._facetPartitioning = new Array();
  18693. }
  18694. this._facetNb = (this.getIndices().length / 3) | 0;
  18695. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  18696. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  18697. for (var f = 0; f < this._facetNb; f++) {
  18698. this._facetNormals[f] = BABYLON.Vector3.Zero();
  18699. this._facetPositions[f] = BABYLON.Vector3.Zero();
  18700. }
  18701. this._facetDataEnabled = true;
  18702. return this;
  18703. };
  18704. /**
  18705. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  18706. * This method can be called within the render loop.
  18707. * 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.
  18708. * Returns the AbstractMesh.
  18709. */
  18710. AbstractMesh.prototype.updateFacetData = function () {
  18711. if (!this._facetDataEnabled) {
  18712. this._initFacetData();
  18713. }
  18714. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18715. var indices = this.getIndices();
  18716. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  18717. var bInfo = this.getBoundingInfo();
  18718. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  18719. // init arrays, matrix and sort function on first call
  18720. this._facetDepthSortEnabled = true;
  18721. if (indices instanceof Uint16Array) {
  18722. this._depthSortedIndices = new Uint16Array(indices);
  18723. }
  18724. else if (indices instanceof Uint32Array) {
  18725. this._depthSortedIndices = new Uint32Array(indices);
  18726. }
  18727. else {
  18728. var needs32bits = false;
  18729. for (var i = 0; i < indices.length; i++) {
  18730. if (indices[i] > 65535) {
  18731. needs32bits = true;
  18732. break;
  18733. }
  18734. }
  18735. if (needs32bits) {
  18736. this._depthSortedIndices = new Uint32Array(indices);
  18737. }
  18738. else {
  18739. this._depthSortedIndices = new Uint16Array(indices);
  18740. }
  18741. }
  18742. this._facetDepthSortFunction = function (f1, f2) {
  18743. return (f2.sqDistance - f1.sqDistance);
  18744. };
  18745. if (!this._facetDepthSortFrom) {
  18746. var camera = this.getScene().activeCamera;
  18747. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  18748. }
  18749. this._depthSortedFacets = [];
  18750. for (var f = 0; f < this._facetNb; f++) {
  18751. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  18752. this._depthSortedFacets.push(depthSortedFacet);
  18753. }
  18754. this._invertedMatrix = BABYLON.Matrix.Identity();
  18755. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  18756. }
  18757. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  18758. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  18759. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  18760. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  18761. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  18762. this._subDiv.max = this._partitioningSubdivisions;
  18763. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  18764. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  18765. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  18766. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  18767. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  18768. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  18769. // set the parameters for ComputeNormals()
  18770. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  18771. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  18772. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  18773. this._facetParameters.bInfo = bInfo;
  18774. this._facetParameters.bbSize = this._bbSize;
  18775. this._facetParameters.subDiv = this._subDiv;
  18776. this._facetParameters.ratio = this.partitioningBBoxRatio;
  18777. this._facetParameters.depthSort = this._facetDepthSort;
  18778. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  18779. this.computeWorldMatrix(true);
  18780. this._worldMatrix.invertToRef(this._invertedMatrix);
  18781. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  18782. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  18783. }
  18784. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  18785. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  18786. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  18787. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  18788. var l = (this._depthSortedIndices.length / 3) | 0;
  18789. for (var f = 0; f < l; f++) {
  18790. var sind = this._depthSortedFacets[f].ind;
  18791. this._depthSortedIndices[f * 3] = indices[sind];
  18792. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  18793. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  18794. }
  18795. this.updateIndices(this._depthSortedIndices);
  18796. }
  18797. return this;
  18798. };
  18799. /**
  18800. * Returns the facetLocalNormals array.
  18801. * The normals are expressed in the mesh local space.
  18802. */
  18803. AbstractMesh.prototype.getFacetLocalNormals = function () {
  18804. if (!this._facetNormals) {
  18805. this.updateFacetData();
  18806. }
  18807. return this._facetNormals;
  18808. };
  18809. /**
  18810. * Returns the facetLocalPositions array.
  18811. * The facet positions are expressed in the mesh local space.
  18812. */
  18813. AbstractMesh.prototype.getFacetLocalPositions = function () {
  18814. if (!this._facetPositions) {
  18815. this.updateFacetData();
  18816. }
  18817. return this._facetPositions;
  18818. };
  18819. /**
  18820. * Returns the facetLocalPartioning array.
  18821. */
  18822. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  18823. if (!this._facetPartitioning) {
  18824. this.updateFacetData();
  18825. }
  18826. return this._facetPartitioning;
  18827. };
  18828. /**
  18829. * Returns the i-th facet position in the world system.
  18830. * This method allocates a new Vector3 per call.
  18831. */
  18832. AbstractMesh.prototype.getFacetPosition = function (i) {
  18833. var pos = BABYLON.Vector3.Zero();
  18834. this.getFacetPositionToRef(i, pos);
  18835. return pos;
  18836. };
  18837. /**
  18838. * Sets the reference Vector3 with the i-th facet position in the world system.
  18839. * Returns the AbstractMesh.
  18840. */
  18841. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  18842. var localPos = (this.getFacetLocalPositions())[i];
  18843. var world = this.getWorldMatrix();
  18844. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  18845. return this;
  18846. };
  18847. /**
  18848. * Returns the i-th facet normal in the world system.
  18849. * This method allocates a new Vector3 per call.
  18850. */
  18851. AbstractMesh.prototype.getFacetNormal = function (i) {
  18852. var norm = BABYLON.Vector3.Zero();
  18853. this.getFacetNormalToRef(i, norm);
  18854. return norm;
  18855. };
  18856. /**
  18857. * Sets the reference Vector3 with the i-th facet normal in the world system.
  18858. * Returns the AbstractMesh.
  18859. */
  18860. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  18861. var localNorm = (this.getFacetLocalNormals())[i];
  18862. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  18863. return this;
  18864. };
  18865. /**
  18866. * 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).
  18867. */
  18868. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  18869. var bInfo = this.getBoundingInfo();
  18870. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  18871. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  18872. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  18873. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  18874. return null;
  18875. }
  18876. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  18877. };
  18878. /**
  18879. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  18880. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  18881. * 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.
  18882. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  18883. * 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.
  18884. */
  18885. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  18886. if (checkFace === void 0) { checkFace = false; }
  18887. if (facing === void 0) { facing = true; }
  18888. var world = this.getWorldMatrix();
  18889. var invMat = BABYLON.Tmp.Matrix[5];
  18890. world.invertToRef(invMat);
  18891. var invVect = BABYLON.Tmp.Vector3[8];
  18892. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  18893. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  18894. if (projected) {
  18895. // tranform the local computed projected vector to world coordinates
  18896. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  18897. }
  18898. return closest;
  18899. };
  18900. /**
  18901. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  18902. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
  18903. * 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.
  18904. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  18905. * 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.
  18906. */
  18907. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  18908. if (checkFace === void 0) { checkFace = false; }
  18909. if (facing === void 0) { facing = true; }
  18910. var closest = null;
  18911. var tmpx = 0.0;
  18912. var tmpy = 0.0;
  18913. var tmpz = 0.0;
  18914. var d = 0.0; // tmp dot facet normal * facet position
  18915. var t0 = 0.0;
  18916. var projx = 0.0;
  18917. var projy = 0.0;
  18918. var projz = 0.0;
  18919. // Get all the facets in the same partitioning block than (x, y, z)
  18920. var facetPositions = this.getFacetLocalPositions();
  18921. var facetNormals = this.getFacetLocalNormals();
  18922. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  18923. if (!facetsInBlock) {
  18924. return null;
  18925. }
  18926. // Get the closest facet to (x, y, z)
  18927. var shortest = Number.MAX_VALUE; // init distance vars
  18928. var tmpDistance = shortest;
  18929. var fib; // current facet in the block
  18930. var norm; // current facet normal
  18931. var p0; // current facet barycenter position
  18932. // loop on all the facets in the current partitioning block
  18933. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  18934. fib = facetsInBlock[idx];
  18935. norm = facetNormals[fib];
  18936. p0 = facetPositions[fib];
  18937. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  18938. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  18939. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  18940. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  18941. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  18942. projx = x + norm.x * t0;
  18943. projy = y + norm.y * t0;
  18944. projz = z + norm.z * t0;
  18945. tmpx = projx - x;
  18946. tmpy = projy - y;
  18947. tmpz = projz - z;
  18948. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  18949. if (tmpDistance < shortest) {
  18950. shortest = tmpDistance;
  18951. closest = fib;
  18952. if (projected) {
  18953. projected.x = projx;
  18954. projected.y = projy;
  18955. projected.z = projz;
  18956. }
  18957. }
  18958. }
  18959. }
  18960. return closest;
  18961. };
  18962. /**
  18963. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  18964. */
  18965. AbstractMesh.prototype.getFacetDataParameters = function () {
  18966. return this._facetParameters;
  18967. };
  18968. /**
  18969. * Disables the feature FacetData and frees the related memory.
  18970. * Returns the AbstractMesh.
  18971. */
  18972. AbstractMesh.prototype.disableFacetData = function () {
  18973. if (this._facetDataEnabled) {
  18974. this._facetDataEnabled = false;
  18975. this._facetPositions = new Array();
  18976. this._facetNormals = new Array();
  18977. this._facetPartitioning = new Array();
  18978. this._facetParameters = null;
  18979. this._depthSortedIndices = new Uint32Array(0);
  18980. }
  18981. return this;
  18982. };
  18983. /**
  18984. * Updates the AbstractMesh indices array. Actually, used by the Mesh object.
  18985. * Returns the mesh.
  18986. */
  18987. AbstractMesh.prototype.updateIndices = function (indices) {
  18988. return this;
  18989. };
  18990. /**
  18991. * The mesh Geometry. Actually used by the Mesh object.
  18992. * Returns a blank geometry object.
  18993. */
  18994. /**
  18995. * Creates new normals data for the mesh.
  18996. * @param updatable.
  18997. */
  18998. AbstractMesh.prototype.createNormals = function (updatable) {
  18999. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19000. var indices = this.getIndices();
  19001. var normals;
  19002. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  19003. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  19004. }
  19005. else {
  19006. normals = [];
  19007. }
  19008. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  19009. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  19010. };
  19011. /**
  19012. * Align the mesh with a normal.
  19013. * Returns the mesh.
  19014. */
  19015. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  19016. if (!upDirection) {
  19017. upDirection = BABYLON.Axis.Y;
  19018. }
  19019. var axisX = BABYLON.Tmp.Vector3[0];
  19020. var axisZ = BABYLON.Tmp.Vector3[1];
  19021. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  19022. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  19023. if (this.rotationQuaternion) {
  19024. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  19025. }
  19026. else {
  19027. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  19028. }
  19029. return this;
  19030. };
  19031. AbstractMesh.prototype.checkOcclusionQuery = function () {
  19032. var engine = this.getEngine();
  19033. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  19034. this._isOccluded = false;
  19035. return;
  19036. }
  19037. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  19038. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  19039. if (isOcclusionQueryAvailable) {
  19040. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  19041. this._isOcclusionQueryInProgress = false;
  19042. this._occlusionInternalRetryCounter = 0;
  19043. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  19044. }
  19045. else {
  19046. this._occlusionInternalRetryCounter++;
  19047. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  19048. this._isOcclusionQueryInProgress = false;
  19049. this._occlusionInternalRetryCounter = 0;
  19050. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  19051. // if strict continue the last state of the object.
  19052. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  19053. }
  19054. else {
  19055. return;
  19056. }
  19057. }
  19058. }
  19059. var scene = this.getScene();
  19060. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  19061. if (!this._occlusionQuery) {
  19062. this._occlusionQuery = engine.createQuery();
  19063. }
  19064. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  19065. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  19066. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  19067. this._isOcclusionQueryInProgress = true;
  19068. };
  19069. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  19070. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  19071. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  19072. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  19073. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  19074. return AbstractMesh;
  19075. }(BABYLON.TransformNode));
  19076. BABYLON.AbstractMesh = AbstractMesh;
  19077. })(BABYLON || (BABYLON = {}));
  19078. //# sourceMappingURL=babylon.abstractMesh.js.map
  19079. var BABYLON;
  19080. (function (BABYLON) {
  19081. /**
  19082. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  19083. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  19084. * 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.
  19085. */
  19086. var Light = /** @class */ (function (_super) {
  19087. __extends(Light, _super);
  19088. /**
  19089. * Creates a Light object in the scene.
  19090. * Documentation : http://doc.babylonjs.com/tutorials/lights
  19091. * @param name The firendly name of the light
  19092. * @param scene The scene the light belongs too
  19093. */
  19094. function Light(name, scene) {
  19095. var _this = _super.call(this, name, scene) || this;
  19096. /**
  19097. * Diffuse gives the basic color to an object.
  19098. */
  19099. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  19100. /**
  19101. * Specular produces a highlight color on an object.
  19102. * Note: This is note affecting PBR materials.
  19103. */
  19104. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  19105. /**
  19106. * Strength of the light.
  19107. * Note: By default it is define in the framework own unit.
  19108. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  19109. */
  19110. _this.intensity = 1.0;
  19111. /**
  19112. * Defines how far from the source the light is impacting in scene units.
  19113. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  19114. */
  19115. _this.range = Number.MAX_VALUE;
  19116. /**
  19117. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  19118. * of light.
  19119. */
  19120. _this._photometricScale = 1.0;
  19121. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  19122. _this._radius = 0.00001;
  19123. /**
  19124. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  19125. * exceeding the number allowed of the materials.
  19126. */
  19127. _this.renderPriority = 0;
  19128. /**
  19129. * Defines wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  19130. * the current shadow generator.
  19131. */
  19132. _this.shadowEnabled = true;
  19133. _this._excludeWithLayerMask = 0;
  19134. _this._includeOnlyWithLayerMask = 0;
  19135. _this._lightmapMode = 0;
  19136. /**
  19137. * @ignore Internal use only.
  19138. */
  19139. _this._excludedMeshesIds = new Array();
  19140. /**
  19141. * @ignore Internal use only.
  19142. */
  19143. _this._includedOnlyMeshesIds = new Array();
  19144. _this.getScene().addLight(_this);
  19145. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  19146. _this._buildUniformLayout();
  19147. _this.includedOnlyMeshes = new Array();
  19148. _this.excludedMeshes = new Array();
  19149. _this._resyncMeshes();
  19150. return _this;
  19151. }
  19152. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  19153. /**
  19154. * If every light affecting the material is in this lightmapMode,
  19155. * material.lightmapTexture adds or multiplies
  19156. * (depends on material.useLightmapAsShadowmap)
  19157. * after every other light calculations.
  19158. */
  19159. get: function () {
  19160. return Light._LIGHTMAP_DEFAULT;
  19161. },
  19162. enumerable: true,
  19163. configurable: true
  19164. });
  19165. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  19166. /**
  19167. * material.lightmapTexture as only diffuse lighting from this light
  19168. * adds only specular lighting from this light
  19169. * adds dynamic shadows
  19170. */
  19171. get: function () {
  19172. return Light._LIGHTMAP_SPECULAR;
  19173. },
  19174. enumerable: true,
  19175. configurable: true
  19176. });
  19177. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  19178. /**
  19179. * material.lightmapTexture as only lighting
  19180. * no light calculation from this light
  19181. * only adds dynamic shadows from this light
  19182. */
  19183. get: function () {
  19184. return Light._LIGHTMAP_SHADOWSONLY;
  19185. },
  19186. enumerable: true,
  19187. configurable: true
  19188. });
  19189. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  19190. /**
  19191. * Each light type uses the default quantity according to its type:
  19192. * point/spot lights use luminous intensity
  19193. * directional lights use illuminance
  19194. */
  19195. get: function () {
  19196. return Light._INTENSITYMODE_AUTOMATIC;
  19197. },
  19198. enumerable: true,
  19199. configurable: true
  19200. });
  19201. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  19202. /**
  19203. * lumen (lm)
  19204. */
  19205. get: function () {
  19206. return Light._INTENSITYMODE_LUMINOUSPOWER;
  19207. },
  19208. enumerable: true,
  19209. configurable: true
  19210. });
  19211. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  19212. /**
  19213. * candela (lm/sr)
  19214. */
  19215. get: function () {
  19216. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  19217. },
  19218. enumerable: true,
  19219. configurable: true
  19220. });
  19221. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  19222. /**
  19223. * lux (lm/m^2)
  19224. */
  19225. get: function () {
  19226. return Light._INTENSITYMODE_ILLUMINANCE;
  19227. },
  19228. enumerable: true,
  19229. configurable: true
  19230. });
  19231. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  19232. /**
  19233. * nit (cd/m^2)
  19234. */
  19235. get: function () {
  19236. return Light._INTENSITYMODE_LUMINANCE;
  19237. },
  19238. enumerable: true,
  19239. configurable: true
  19240. });
  19241. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  19242. /**
  19243. * Light type const id of the point light.
  19244. */
  19245. get: function () {
  19246. return Light._LIGHTTYPEID_POINTLIGHT;
  19247. },
  19248. enumerable: true,
  19249. configurable: true
  19250. });
  19251. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  19252. /**
  19253. * Light type const id of the directional light.
  19254. */
  19255. get: function () {
  19256. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  19257. },
  19258. enumerable: true,
  19259. configurable: true
  19260. });
  19261. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  19262. /**
  19263. * Light type const id of the spot light.
  19264. */
  19265. get: function () {
  19266. return Light._LIGHTTYPEID_SPOTLIGHT;
  19267. },
  19268. enumerable: true,
  19269. configurable: true
  19270. });
  19271. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  19272. /**
  19273. * Light type const id of the hemispheric light.
  19274. */
  19275. get: function () {
  19276. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  19277. },
  19278. enumerable: true,
  19279. configurable: true
  19280. });
  19281. Object.defineProperty(Light.prototype, "intensityMode", {
  19282. /**
  19283. * Gets the photometric scale used to interpret the intensity.
  19284. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  19285. */
  19286. get: function () {
  19287. return this._intensityMode;
  19288. },
  19289. /**
  19290. * Sets the photometric scale used to interpret the intensity.
  19291. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  19292. */
  19293. set: function (value) {
  19294. this._intensityMode = value;
  19295. this._computePhotometricScale();
  19296. },
  19297. enumerable: true,
  19298. configurable: true
  19299. });
  19300. ;
  19301. ;
  19302. Object.defineProperty(Light.prototype, "radius", {
  19303. /**
  19304. * Gets the light radius used by PBR Materials to simulate soft area lights.
  19305. */
  19306. get: function () {
  19307. return this._radius;
  19308. },
  19309. /**
  19310. * sets the light radius used by PBR Materials to simulate soft area lights.
  19311. */
  19312. set: function (value) {
  19313. this._radius = value;
  19314. this._computePhotometricScale();
  19315. },
  19316. enumerable: true,
  19317. configurable: true
  19318. });
  19319. ;
  19320. ;
  19321. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  19322. /**
  19323. * Gets the only meshes impacted by this light.
  19324. */
  19325. get: function () {
  19326. return this._includedOnlyMeshes;
  19327. },
  19328. /**
  19329. * Sets the only meshes impacted by this light.
  19330. */
  19331. set: function (value) {
  19332. this._includedOnlyMeshes = value;
  19333. this._hookArrayForIncludedOnly(value);
  19334. },
  19335. enumerable: true,
  19336. configurable: true
  19337. });
  19338. Object.defineProperty(Light.prototype, "excludedMeshes", {
  19339. /**
  19340. * Gets the meshes not impacted by this light.
  19341. */
  19342. get: function () {
  19343. return this._excludedMeshes;
  19344. },
  19345. /**
  19346. * Sets the meshes not impacted by this light.
  19347. */
  19348. set: function (value) {
  19349. this._excludedMeshes = value;
  19350. this._hookArrayForExcluded(value);
  19351. },
  19352. enumerable: true,
  19353. configurable: true
  19354. });
  19355. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  19356. /**
  19357. * Gets the layer id use to find what meshes are not impacted by the light.
  19358. * Inactive if 0
  19359. */
  19360. get: function () {
  19361. return this._excludeWithLayerMask;
  19362. },
  19363. /**
  19364. * Sets the layer id use to find what meshes are not impacted by the light.
  19365. * Inactive if 0
  19366. */
  19367. set: function (value) {
  19368. this._excludeWithLayerMask = value;
  19369. this._resyncMeshes();
  19370. },
  19371. enumerable: true,
  19372. configurable: true
  19373. });
  19374. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  19375. /**
  19376. * Gets the layer id use to find what meshes are impacted by the light.
  19377. * Inactive if 0
  19378. */
  19379. get: function () {
  19380. return this._includeOnlyWithLayerMask;
  19381. },
  19382. /**
  19383. * Sets the layer id use to find what meshes are impacted by the light.
  19384. * Inactive if 0
  19385. */
  19386. set: function (value) {
  19387. this._includeOnlyWithLayerMask = value;
  19388. this._resyncMeshes();
  19389. },
  19390. enumerable: true,
  19391. configurable: true
  19392. });
  19393. Object.defineProperty(Light.prototype, "lightmapMode", {
  19394. /**
  19395. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  19396. */
  19397. get: function () {
  19398. return this._lightmapMode;
  19399. },
  19400. /**
  19401. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  19402. */
  19403. set: function (value) {
  19404. if (this._lightmapMode === value) {
  19405. return;
  19406. }
  19407. this._lightmapMode = value;
  19408. this._markMeshesAsLightDirty();
  19409. },
  19410. enumerable: true,
  19411. configurable: true
  19412. });
  19413. /**
  19414. * Returns the string "Light".
  19415. * @returns the class name
  19416. */
  19417. Light.prototype.getClassName = function () {
  19418. return "Light";
  19419. };
  19420. /**
  19421. * Converts the light information to a readable string for debug purpose.
  19422. * @param fullDetails Supports for multiple levels of logging within scene loading
  19423. * @returns the human readable light info
  19424. */
  19425. Light.prototype.toString = function (fullDetails) {
  19426. var ret = "Name: " + this.name;
  19427. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  19428. if (this.animations) {
  19429. for (var i = 0; i < this.animations.length; i++) {
  19430. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  19431. }
  19432. }
  19433. if (fullDetails) {
  19434. }
  19435. return ret;
  19436. };
  19437. /**
  19438. * Set the enabled state of this node.
  19439. * @param value - the new enabled state
  19440. * @see isEnabled
  19441. */
  19442. Light.prototype.setEnabled = function (value) {
  19443. _super.prototype.setEnabled.call(this, value);
  19444. this._resyncMeshes();
  19445. };
  19446. /**
  19447. * Returns the Light associated shadow generator if any.
  19448. * @return the associated shadow generator.
  19449. */
  19450. Light.prototype.getShadowGenerator = function () {
  19451. return this._shadowGenerator;
  19452. };
  19453. /**
  19454. * Returns a Vector3, the absolute light position in the World.
  19455. * @returns the world space position of the light
  19456. */
  19457. Light.prototype.getAbsolutePosition = function () {
  19458. return BABYLON.Vector3.Zero();
  19459. };
  19460. /**
  19461. * Specifies if the light will affect the passed mesh.
  19462. * @param mesh The mesh to test against the light
  19463. * @return true the mesh is affected otherwise, false.
  19464. */
  19465. Light.prototype.canAffectMesh = function (mesh) {
  19466. if (!mesh) {
  19467. return true;
  19468. }
  19469. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  19470. return false;
  19471. }
  19472. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  19473. return false;
  19474. }
  19475. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  19476. return false;
  19477. }
  19478. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  19479. return false;
  19480. }
  19481. return true;
  19482. };
  19483. /**
  19484. * Computes and Returns the light World matrix.
  19485. * @returns the world matrix
  19486. */
  19487. Light.prototype.getWorldMatrix = function () {
  19488. this._currentRenderId = this.getScene().getRenderId();
  19489. var worldMatrix = this._getWorldMatrix();
  19490. if (this.parent && this.parent.getWorldMatrix) {
  19491. if (!this._parentedWorldMatrix) {
  19492. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  19493. }
  19494. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  19495. this._markSyncedWithParent();
  19496. return this._parentedWorldMatrix;
  19497. }
  19498. return worldMatrix;
  19499. };
  19500. /**
  19501. * Sort function to order lights for rendering.
  19502. * @param a First Light object to compare to second.
  19503. * @param b Second Light object to compare first.
  19504. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  19505. */
  19506. Light.CompareLightsPriority = function (a, b) {
  19507. //shadow-casting lights have priority over non-shadow-casting lights
  19508. //the renderPrioirty is a secondary sort criterion
  19509. if (a.shadowEnabled !== b.shadowEnabled) {
  19510. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  19511. }
  19512. return b.renderPriority - a.renderPriority;
  19513. };
  19514. /**
  19515. * Releases resources associated with this node.
  19516. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  19517. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  19518. */
  19519. Light.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  19520. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  19521. if (this._shadowGenerator) {
  19522. this._shadowGenerator.dispose();
  19523. this._shadowGenerator = null;
  19524. }
  19525. // Animations
  19526. this.getScene().stopAnimation(this);
  19527. // Remove from meshes
  19528. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  19529. var mesh = _a[_i];
  19530. mesh._removeLightSource(this);
  19531. }
  19532. this._uniformBuffer.dispose();
  19533. // Remove from scene
  19534. this.getScene().removeLight(this);
  19535. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  19536. };
  19537. /**
  19538. * Returns the light type ID (integer).
  19539. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  19540. */
  19541. Light.prototype.getTypeID = function () {
  19542. return 0;
  19543. };
  19544. /**
  19545. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  19546. * @returns the scaled intensity in intensity mode unit
  19547. */
  19548. Light.prototype.getScaledIntensity = function () {
  19549. return this._photometricScale * this.intensity;
  19550. };
  19551. /**
  19552. * Returns a new Light object, named "name", from the current one.
  19553. * @param name The name of the cloned light
  19554. * @returns the new created light
  19555. */
  19556. Light.prototype.clone = function (name) {
  19557. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  19558. if (!constructor) {
  19559. return null;
  19560. }
  19561. return BABYLON.SerializationHelper.Clone(constructor, this);
  19562. };
  19563. /**
  19564. * Serializes the current light into a Serialization object.
  19565. * @returns the serialized object.
  19566. */
  19567. Light.prototype.serialize = function () {
  19568. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  19569. // Type
  19570. serializationObject.type = this.getTypeID();
  19571. // Parent
  19572. if (this.parent) {
  19573. serializationObject.parentId = this.parent.id;
  19574. }
  19575. // Inclusion / exclusions
  19576. if (this.excludedMeshes.length > 0) {
  19577. serializationObject.excludedMeshesIds = [];
  19578. this.excludedMeshes.forEach(function (mesh) {
  19579. serializationObject.excludedMeshesIds.push(mesh.id);
  19580. });
  19581. }
  19582. if (this.includedOnlyMeshes.length > 0) {
  19583. serializationObject.includedOnlyMeshesIds = [];
  19584. this.includedOnlyMeshes.forEach(function (mesh) {
  19585. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  19586. });
  19587. }
  19588. // Animations
  19589. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  19590. serializationObject.ranges = this.serializeAnimationRanges();
  19591. return serializationObject;
  19592. };
  19593. /**
  19594. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  19595. * This new light is named "name" and added to the passed scene.
  19596. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  19597. * @param name The friendly name of the light
  19598. * @param scene The scene the new light will belong to
  19599. * @returns the constructor function
  19600. */
  19601. Light.GetConstructorFromName = function (type, name, scene) {
  19602. switch (type) {
  19603. case 0:
  19604. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  19605. case 1:
  19606. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  19607. case 2:
  19608. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  19609. case 3:
  19610. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  19611. }
  19612. return null;
  19613. };
  19614. /**
  19615. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  19616. * @param parsedLight The JSON representation of the light
  19617. * @param scene The scene to create the parsed light in
  19618. * @returns the created light after parsing
  19619. */
  19620. Light.Parse = function (parsedLight, scene) {
  19621. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  19622. if (!constructor) {
  19623. return null;
  19624. }
  19625. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  19626. // Inclusion / exclusions
  19627. if (parsedLight.excludedMeshesIds) {
  19628. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  19629. }
  19630. if (parsedLight.includedOnlyMeshesIds) {
  19631. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  19632. }
  19633. // Parent
  19634. if (parsedLight.parentId) {
  19635. light._waitingParentId = parsedLight.parentId;
  19636. }
  19637. // Animations
  19638. if (parsedLight.animations) {
  19639. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  19640. var parsedAnimation = parsedLight.animations[animationIndex];
  19641. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  19642. }
  19643. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  19644. }
  19645. if (parsedLight.autoAnimate) {
  19646. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  19647. }
  19648. return light;
  19649. };
  19650. Light.prototype._hookArrayForExcluded = function (array) {
  19651. var _this = this;
  19652. var oldPush = array.push;
  19653. array.push = function () {
  19654. var items = [];
  19655. for (var _i = 0; _i < arguments.length; _i++) {
  19656. items[_i] = arguments[_i];
  19657. }
  19658. var result = oldPush.apply(array, items);
  19659. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  19660. var item = items_1[_a];
  19661. item._resyncLighSource(_this);
  19662. }
  19663. return result;
  19664. };
  19665. var oldSplice = array.splice;
  19666. array.splice = function (index, deleteCount) {
  19667. var deleted = oldSplice.apply(array, [index, deleteCount]);
  19668. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  19669. var item = deleted_1[_i];
  19670. item._resyncLighSource(_this);
  19671. }
  19672. return deleted;
  19673. };
  19674. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  19675. var item = array_1[_i];
  19676. item._resyncLighSource(this);
  19677. }
  19678. };
  19679. Light.prototype._hookArrayForIncludedOnly = function (array) {
  19680. var _this = this;
  19681. var oldPush = array.push;
  19682. array.push = function () {
  19683. var items = [];
  19684. for (var _i = 0; _i < arguments.length; _i++) {
  19685. items[_i] = arguments[_i];
  19686. }
  19687. var result = oldPush.apply(array, items);
  19688. _this._resyncMeshes();
  19689. return result;
  19690. };
  19691. var oldSplice = array.splice;
  19692. array.splice = function (index, deleteCount) {
  19693. var deleted = oldSplice.apply(array, [index, deleteCount]);
  19694. _this._resyncMeshes();
  19695. return deleted;
  19696. };
  19697. this._resyncMeshes();
  19698. };
  19699. Light.prototype._resyncMeshes = function () {
  19700. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  19701. var mesh = _a[_i];
  19702. mesh._resyncLighSource(this);
  19703. }
  19704. };
  19705. /**
  19706. * Forces the meshes to update their light related information in their rendering used effects
  19707. * @ignore Internal Use Only
  19708. */
  19709. Light.prototype._markMeshesAsLightDirty = function () {
  19710. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  19711. var mesh = _a[_i];
  19712. if (mesh._lightSources.indexOf(this) !== -1) {
  19713. mesh._markSubMeshesAsLightDirty();
  19714. }
  19715. }
  19716. };
  19717. /**
  19718. * Recomputes the cached photometric scale if needed.
  19719. */
  19720. Light.prototype._computePhotometricScale = function () {
  19721. this._photometricScale = this._getPhotometricScale();
  19722. this.getScene().resetCachedMaterial();
  19723. };
  19724. /**
  19725. * Returns the Photometric Scale according to the light type and intensity mode.
  19726. */
  19727. Light.prototype._getPhotometricScale = function () {
  19728. var photometricScale = 0.0;
  19729. var lightTypeID = this.getTypeID();
  19730. //get photometric mode
  19731. var photometricMode = this.intensityMode;
  19732. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  19733. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  19734. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  19735. }
  19736. else {
  19737. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  19738. }
  19739. }
  19740. //compute photometric scale
  19741. switch (lightTypeID) {
  19742. case Light.LIGHTTYPEID_POINTLIGHT:
  19743. case Light.LIGHTTYPEID_SPOTLIGHT:
  19744. switch (photometricMode) {
  19745. case Light.INTENSITYMODE_LUMINOUSPOWER:
  19746. photometricScale = 1.0 / (4.0 * Math.PI);
  19747. break;
  19748. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  19749. photometricScale = 1.0;
  19750. break;
  19751. case Light.INTENSITYMODE_LUMINANCE:
  19752. photometricScale = this.radius * this.radius;
  19753. break;
  19754. }
  19755. break;
  19756. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  19757. switch (photometricMode) {
  19758. case Light.INTENSITYMODE_ILLUMINANCE:
  19759. photometricScale = 1.0;
  19760. break;
  19761. case Light.INTENSITYMODE_LUMINANCE:
  19762. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  19763. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  19764. var apexAngleRadians = this.radius;
  19765. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  19766. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  19767. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  19768. photometricScale = solidAngle;
  19769. break;
  19770. }
  19771. break;
  19772. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  19773. // No fall off in hemisperic light.
  19774. photometricScale = 1.0;
  19775. break;
  19776. }
  19777. return photometricScale;
  19778. };
  19779. /**
  19780. * Reorder the light in the scene according to their defined priority.
  19781. * @ignore Internal Use Only
  19782. */
  19783. Light.prototype._reorderLightsInScene = function () {
  19784. var scene = this.getScene();
  19785. if (this._renderPriority != 0) {
  19786. scene.requireLightSorting = true;
  19787. }
  19788. this.getScene().sortLightsByPriority();
  19789. };
  19790. //lightmapMode Consts
  19791. Light._LIGHTMAP_DEFAULT = 0;
  19792. Light._LIGHTMAP_SPECULAR = 1;
  19793. Light._LIGHTMAP_SHADOWSONLY = 2;
  19794. // Intensity Mode Consts
  19795. Light._INTENSITYMODE_AUTOMATIC = 0;
  19796. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  19797. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  19798. Light._INTENSITYMODE_ILLUMINANCE = 3;
  19799. Light._INTENSITYMODE_LUMINANCE = 4;
  19800. // Light types ids const.
  19801. Light._LIGHTTYPEID_POINTLIGHT = 0;
  19802. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  19803. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  19804. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  19805. __decorate([
  19806. BABYLON.serializeAsColor3()
  19807. ], Light.prototype, "diffuse", void 0);
  19808. __decorate([
  19809. BABYLON.serializeAsColor3()
  19810. ], Light.prototype, "specular", void 0);
  19811. __decorate([
  19812. BABYLON.serialize()
  19813. ], Light.prototype, "intensity", void 0);
  19814. __decorate([
  19815. BABYLON.serialize()
  19816. ], Light.prototype, "range", void 0);
  19817. __decorate([
  19818. BABYLON.serialize()
  19819. ], Light.prototype, "intensityMode", null);
  19820. __decorate([
  19821. BABYLON.serialize()
  19822. ], Light.prototype, "radius", null);
  19823. __decorate([
  19824. BABYLON.serialize()
  19825. ], Light.prototype, "_renderPriority", void 0);
  19826. __decorate([
  19827. BABYLON.expandToProperty("_reorderLightsInScene")
  19828. ], Light.prototype, "renderPriority", void 0);
  19829. __decorate([
  19830. BABYLON.serialize()
  19831. ], Light.prototype, "shadowEnabled", void 0);
  19832. __decorate([
  19833. BABYLON.serialize("excludeWithLayerMask")
  19834. ], Light.prototype, "_excludeWithLayerMask", void 0);
  19835. __decorate([
  19836. BABYLON.serialize("includeOnlyWithLayerMask")
  19837. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  19838. __decorate([
  19839. BABYLON.serialize("lightmapMode")
  19840. ], Light.prototype, "_lightmapMode", void 0);
  19841. return Light;
  19842. }(BABYLON.Node));
  19843. BABYLON.Light = Light;
  19844. })(BABYLON || (BABYLON = {}));
  19845. //# sourceMappingURL=babylon.light.js.map
  19846. var BABYLON;
  19847. (function (BABYLON) {
  19848. var Camera = /** @class */ (function (_super) {
  19849. __extends(Camera, _super);
  19850. function Camera(name, position, scene) {
  19851. var _this = _super.call(this, name, scene) || this;
  19852. /**
  19853. * The vector the camera should consider as up.
  19854. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  19855. */
  19856. _this.upVector = BABYLON.Vector3.Up();
  19857. _this.orthoLeft = null;
  19858. _this.orthoRight = null;
  19859. _this.orthoBottom = null;
  19860. _this.orthoTop = null;
  19861. /**
  19862. * FOV is set in Radians. (default is 0.8)
  19863. */
  19864. _this.fov = 0.8;
  19865. _this.minZ = 1;
  19866. _this.maxZ = 10000.0;
  19867. _this.inertia = 0.9;
  19868. _this.mode = Camera.PERSPECTIVE_CAMERA;
  19869. _this.isIntermediate = false;
  19870. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  19871. /**
  19872. * Restricts the camera to viewing objects with the same layerMask.
  19873. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  19874. */
  19875. _this.layerMask = 0x0FFFFFFF;
  19876. /**
  19877. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  19878. */
  19879. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  19880. // Camera rig members
  19881. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  19882. _this._rigCameras = new Array();
  19883. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  19884. _this._skipRendering = false;
  19885. _this.customRenderTargets = new Array();
  19886. // Observables
  19887. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  19888. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  19889. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  19890. _this.onRestoreStateObservable = new BABYLON.Observable();
  19891. // Cache
  19892. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  19893. _this._projectionMatrix = new BABYLON.Matrix();
  19894. _this._doNotComputeProjectionMatrix = false;
  19895. _this._postProcesses = new Array();
  19896. _this._transformMatrix = BABYLON.Matrix.Zero();
  19897. _this._activeMeshes = new BABYLON.SmartArray(256);
  19898. _this._globalPosition = BABYLON.Vector3.Zero();
  19899. _this._refreshFrustumPlanes = true;
  19900. _this.getScene().addCamera(_this);
  19901. if (!_this.getScene().activeCamera) {
  19902. _this.getScene().activeCamera = _this;
  19903. }
  19904. _this.position = position;
  19905. return _this;
  19906. }
  19907. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  19908. get: function () {
  19909. return Camera._PERSPECTIVE_CAMERA;
  19910. },
  19911. enumerable: true,
  19912. configurable: true
  19913. });
  19914. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  19915. get: function () {
  19916. return Camera._ORTHOGRAPHIC_CAMERA;
  19917. },
  19918. enumerable: true,
  19919. configurable: true
  19920. });
  19921. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  19922. /**
  19923. * This is the default FOV mode for perspective cameras.
  19924. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  19925. *
  19926. */
  19927. get: function () {
  19928. return Camera._FOVMODE_VERTICAL_FIXED;
  19929. },
  19930. enumerable: true,
  19931. configurable: true
  19932. });
  19933. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  19934. /**
  19935. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  19936. *
  19937. */
  19938. get: function () {
  19939. return Camera._FOVMODE_HORIZONTAL_FIXED;
  19940. },
  19941. enumerable: true,
  19942. configurable: true
  19943. });
  19944. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  19945. get: function () {
  19946. return Camera._RIG_MODE_NONE;
  19947. },
  19948. enumerable: true,
  19949. configurable: true
  19950. });
  19951. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  19952. get: function () {
  19953. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  19954. },
  19955. enumerable: true,
  19956. configurable: true
  19957. });
  19958. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  19959. get: function () {
  19960. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  19961. },
  19962. enumerable: true,
  19963. configurable: true
  19964. });
  19965. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  19966. get: function () {
  19967. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  19968. },
  19969. enumerable: true,
  19970. configurable: true
  19971. });
  19972. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  19973. get: function () {
  19974. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  19975. },
  19976. enumerable: true,
  19977. configurable: true
  19978. });
  19979. Object.defineProperty(Camera, "RIG_MODE_VR", {
  19980. get: function () {
  19981. return Camera._RIG_MODE_VR;
  19982. },
  19983. enumerable: true,
  19984. configurable: true
  19985. });
  19986. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  19987. get: function () {
  19988. return Camera._RIG_MODE_WEBVR;
  19989. },
  19990. enumerable: true,
  19991. configurable: true
  19992. });
  19993. /**
  19994. * Store current camera state (fov, position, etc..)
  19995. */
  19996. Camera.prototype.storeState = function () {
  19997. this._stateStored = true;
  19998. this._storedFov = this.fov;
  19999. return this;
  20000. };
  20001. /**
  20002. * Restores the camera state values if it has been stored. You must call storeState() first
  20003. */
  20004. Camera.prototype._restoreStateValues = function () {
  20005. if (!this._stateStored) {
  20006. return false;
  20007. }
  20008. this.fov = this._storedFov;
  20009. return true;
  20010. };
  20011. /**
  20012. * Restored camera state. You must call storeState() first
  20013. */
  20014. Camera.prototype.restoreState = function () {
  20015. if (this._restoreStateValues()) {
  20016. this.onRestoreStateObservable.notifyObservers(this);
  20017. return true;
  20018. }
  20019. return false;
  20020. };
  20021. Camera.prototype.getClassName = function () {
  20022. return "Camera";
  20023. };
  20024. /**
  20025. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  20026. */
  20027. Camera.prototype.toString = function (fullDetails) {
  20028. var ret = "Name: " + this.name;
  20029. ret += ", type: " + this.getClassName();
  20030. if (this.animations) {
  20031. for (var i = 0; i < this.animations.length; i++) {
  20032. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  20033. }
  20034. }
  20035. if (fullDetails) {
  20036. }
  20037. return ret;
  20038. };
  20039. Object.defineProperty(Camera.prototype, "globalPosition", {
  20040. get: function () {
  20041. return this._globalPosition;
  20042. },
  20043. enumerable: true,
  20044. configurable: true
  20045. });
  20046. Camera.prototype.getActiveMeshes = function () {
  20047. return this._activeMeshes;
  20048. };
  20049. Camera.prototype.isActiveMesh = function (mesh) {
  20050. return (this._activeMeshes.indexOf(mesh) !== -1);
  20051. };
  20052. //Cache
  20053. Camera.prototype._initCache = function () {
  20054. _super.prototype._initCache.call(this);
  20055. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  20056. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  20057. this._cache.mode = undefined;
  20058. this._cache.minZ = undefined;
  20059. this._cache.maxZ = undefined;
  20060. this._cache.fov = undefined;
  20061. this._cache.fovMode = undefined;
  20062. this._cache.aspectRatio = undefined;
  20063. this._cache.orthoLeft = undefined;
  20064. this._cache.orthoRight = undefined;
  20065. this._cache.orthoBottom = undefined;
  20066. this._cache.orthoTop = undefined;
  20067. this._cache.renderWidth = undefined;
  20068. this._cache.renderHeight = undefined;
  20069. };
  20070. Camera.prototype._updateCache = function (ignoreParentClass) {
  20071. if (!ignoreParentClass) {
  20072. _super.prototype._updateCache.call(this);
  20073. }
  20074. this._cache.position.copyFrom(this.position);
  20075. this._cache.upVector.copyFrom(this.upVector);
  20076. };
  20077. // Synchronized
  20078. Camera.prototype._isSynchronized = function () {
  20079. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  20080. };
  20081. Camera.prototype._isSynchronizedViewMatrix = function () {
  20082. if (!_super.prototype._isSynchronized.call(this))
  20083. return false;
  20084. return this._cache.position.equals(this.position)
  20085. && this._cache.upVector.equals(this.upVector)
  20086. && this.isSynchronizedWithParent();
  20087. };
  20088. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  20089. var check = this._cache.mode === this.mode
  20090. && this._cache.minZ === this.minZ
  20091. && this._cache.maxZ === this.maxZ;
  20092. if (!check) {
  20093. return false;
  20094. }
  20095. var engine = this.getEngine();
  20096. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  20097. check = this._cache.fov === this.fov
  20098. && this._cache.fovMode === this.fovMode
  20099. && this._cache.aspectRatio === engine.getAspectRatio(this);
  20100. }
  20101. else {
  20102. check = this._cache.orthoLeft === this.orthoLeft
  20103. && this._cache.orthoRight === this.orthoRight
  20104. && this._cache.orthoBottom === this.orthoBottom
  20105. && this._cache.orthoTop === this.orthoTop
  20106. && this._cache.renderWidth === engine.getRenderWidth()
  20107. && this._cache.renderHeight === engine.getRenderHeight();
  20108. }
  20109. return check;
  20110. };
  20111. // Controls
  20112. Camera.prototype.attachControl = function (element, noPreventDefault) {
  20113. };
  20114. Camera.prototype.detachControl = function (element) {
  20115. };
  20116. Camera.prototype.update = function () {
  20117. this._checkInputs();
  20118. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  20119. this._updateRigCameras();
  20120. }
  20121. };
  20122. Camera.prototype._checkInputs = function () {
  20123. this.onAfterCheckInputsObservable.notifyObservers(this);
  20124. };
  20125. Object.defineProperty(Camera.prototype, "rigCameras", {
  20126. get: function () {
  20127. return this._rigCameras;
  20128. },
  20129. enumerable: true,
  20130. configurable: true
  20131. });
  20132. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  20133. get: function () {
  20134. return this._rigPostProcess;
  20135. },
  20136. enumerable: true,
  20137. configurable: true
  20138. });
  20139. /**
  20140. * Internal, gets the first post proces.
  20141. * @returns the first post process to be run on this camera.
  20142. */
  20143. Camera.prototype._getFirstPostProcess = function () {
  20144. for (var pp in this._postProcesses) {
  20145. if (this._postProcesses[pp] !== null) {
  20146. return this._postProcesses[pp];
  20147. }
  20148. }
  20149. return null;
  20150. };
  20151. Camera.prototype._cascadePostProcessesToRigCams = function () {
  20152. // invalidate framebuffer
  20153. var firstPostProcess = this._getFirstPostProcess();
  20154. if (firstPostProcess) {
  20155. firstPostProcess.markTextureDirty();
  20156. }
  20157. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  20158. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  20159. var cam = this._rigCameras[i];
  20160. var rigPostProcess = cam._rigPostProcess;
  20161. // for VR rig, there does not have to be a post process
  20162. if (rigPostProcess) {
  20163. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  20164. if (isPass) {
  20165. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  20166. cam.isIntermediate = this._postProcesses.length === 0;
  20167. }
  20168. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  20169. rigPostProcess.markTextureDirty();
  20170. }
  20171. else {
  20172. cam._postProcesses = this._postProcesses.slice(0);
  20173. }
  20174. }
  20175. };
  20176. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  20177. if (insertAt === void 0) { insertAt = null; }
  20178. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  20179. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  20180. return 0;
  20181. }
  20182. if (insertAt == null || insertAt < 0) {
  20183. this._postProcesses.push(postProcess);
  20184. }
  20185. else if (this._postProcesses[insertAt] === null) {
  20186. this._postProcesses[insertAt] = postProcess;
  20187. }
  20188. else {
  20189. this._postProcesses.splice(insertAt, 0, postProcess);
  20190. }
  20191. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  20192. return this._postProcesses.indexOf(postProcess);
  20193. };
  20194. Camera.prototype.detachPostProcess = function (postProcess) {
  20195. var idx = this._postProcesses.indexOf(postProcess);
  20196. if (idx !== -1) {
  20197. this._postProcesses[idx] = null;
  20198. }
  20199. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  20200. };
  20201. Camera.prototype.getWorldMatrix = function () {
  20202. if (!this._worldMatrix) {
  20203. this._worldMatrix = BABYLON.Matrix.Identity();
  20204. }
  20205. var viewMatrix = this.getViewMatrix();
  20206. viewMatrix.invertToRef(this._worldMatrix);
  20207. return this._worldMatrix;
  20208. };
  20209. Camera.prototype._getViewMatrix = function () {
  20210. return BABYLON.Matrix.Identity();
  20211. };
  20212. Camera.prototype.getViewMatrix = function (force) {
  20213. if (!force && this._isSynchronizedViewMatrix()) {
  20214. return this._computedViewMatrix;
  20215. }
  20216. this.updateCache();
  20217. this._computedViewMatrix = this._getViewMatrix();
  20218. this._currentRenderId = this.getScene().getRenderId();
  20219. this._refreshFrustumPlanes = true;
  20220. if (!this.parent || !this.parent.getWorldMatrix) {
  20221. this._globalPosition.copyFrom(this.position);
  20222. }
  20223. else {
  20224. if (!this._worldMatrix) {
  20225. this._worldMatrix = BABYLON.Matrix.Identity();
  20226. }
  20227. this._computedViewMatrix.invertToRef(this._worldMatrix);
  20228. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  20229. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  20230. this._computedViewMatrix.invert();
  20231. this._markSyncedWithParent();
  20232. }
  20233. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  20234. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  20235. }
  20236. this.onViewMatrixChangedObservable.notifyObservers(this);
  20237. return this._computedViewMatrix;
  20238. };
  20239. Camera.prototype.freezeProjectionMatrix = function (projection) {
  20240. this._doNotComputeProjectionMatrix = true;
  20241. if (projection !== undefined) {
  20242. this._projectionMatrix = projection;
  20243. }
  20244. };
  20245. ;
  20246. Camera.prototype.unfreezeProjectionMatrix = function () {
  20247. this._doNotComputeProjectionMatrix = false;
  20248. };
  20249. ;
  20250. Camera.prototype.getProjectionMatrix = function (force) {
  20251. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  20252. return this._projectionMatrix;
  20253. }
  20254. // Cache
  20255. this._cache.mode = this.mode;
  20256. this._cache.minZ = this.minZ;
  20257. this._cache.maxZ = this.maxZ;
  20258. // Matrix
  20259. this._refreshFrustumPlanes = true;
  20260. var engine = this.getEngine();
  20261. var scene = this.getScene();
  20262. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  20263. this._cache.fov = this.fov;
  20264. this._cache.fovMode = this.fovMode;
  20265. this._cache.aspectRatio = engine.getAspectRatio(this);
  20266. if (this.minZ <= 0) {
  20267. this.minZ = 0.1;
  20268. }
  20269. if (scene.useRightHandedSystem) {
  20270. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  20271. }
  20272. else {
  20273. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  20274. }
  20275. }
  20276. else {
  20277. var halfWidth = engine.getRenderWidth() / 2.0;
  20278. var halfHeight = engine.getRenderHeight() / 2.0;
  20279. if (scene.useRightHandedSystem) {
  20280. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  20281. }
  20282. else {
  20283. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  20284. }
  20285. this._cache.orthoLeft = this.orthoLeft;
  20286. this._cache.orthoRight = this.orthoRight;
  20287. this._cache.orthoBottom = this.orthoBottom;
  20288. this._cache.orthoTop = this.orthoTop;
  20289. this._cache.renderWidth = engine.getRenderWidth();
  20290. this._cache.renderHeight = engine.getRenderHeight();
  20291. }
  20292. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  20293. return this._projectionMatrix;
  20294. };
  20295. Camera.prototype.getTranformationMatrix = function () {
  20296. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  20297. return this._transformMatrix;
  20298. };
  20299. Camera.prototype.updateFrustumPlanes = function () {
  20300. if (!this._refreshFrustumPlanes) {
  20301. return;
  20302. }
  20303. this.getTranformationMatrix();
  20304. if (!this._frustumPlanes) {
  20305. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  20306. }
  20307. else {
  20308. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  20309. }
  20310. this._refreshFrustumPlanes = false;
  20311. };
  20312. Camera.prototype.isInFrustum = function (target) {
  20313. this.updateFrustumPlanes();
  20314. return target.isInFrustum(this._frustumPlanes);
  20315. };
  20316. Camera.prototype.isCompletelyInFrustum = function (target) {
  20317. this.updateFrustumPlanes();
  20318. return target.isCompletelyInFrustum(this._frustumPlanes);
  20319. };
  20320. Camera.prototype.getForwardRay = function (length, transform, origin) {
  20321. if (length === void 0) { length = 100; }
  20322. if (!transform) {
  20323. transform = this.getWorldMatrix();
  20324. }
  20325. if (!origin) {
  20326. origin = this.position;
  20327. }
  20328. var forward = new BABYLON.Vector3(0, 0, 1);
  20329. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  20330. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  20331. return new BABYLON.Ray(origin, direction, length);
  20332. };
  20333. /**
  20334. * Releases resources associated with this node.
  20335. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  20336. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  20337. */
  20338. Camera.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  20339. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  20340. // Observables
  20341. this.onViewMatrixChangedObservable.clear();
  20342. this.onProjectionMatrixChangedObservable.clear();
  20343. this.onAfterCheckInputsObservable.clear();
  20344. this.onRestoreStateObservable.clear();
  20345. // Inputs
  20346. if (this.inputs) {
  20347. this.inputs.clear();
  20348. }
  20349. // Animations
  20350. this.getScene().stopAnimation(this);
  20351. // Remove from scene
  20352. this.getScene().removeCamera(this);
  20353. while (this._rigCameras.length > 0) {
  20354. var camera = this._rigCameras.pop();
  20355. if (camera) {
  20356. camera.dispose();
  20357. }
  20358. }
  20359. // Postprocesses
  20360. if (this._rigPostProcess) {
  20361. this._rigPostProcess.dispose(this);
  20362. this._rigPostProcess = null;
  20363. this._postProcesses = [];
  20364. }
  20365. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  20366. this._rigPostProcess = null;
  20367. this._postProcesses = [];
  20368. }
  20369. else {
  20370. var i = this._postProcesses.length;
  20371. while (--i >= 0) {
  20372. var postProcess = this._postProcesses[i];
  20373. if (postProcess) {
  20374. postProcess.dispose(this);
  20375. }
  20376. }
  20377. }
  20378. // Render targets
  20379. var i = this.customRenderTargets.length;
  20380. while (--i >= 0) {
  20381. this.customRenderTargets[i].dispose();
  20382. }
  20383. this.customRenderTargets = [];
  20384. // Active Meshes
  20385. this._activeMeshes.dispose();
  20386. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  20387. };
  20388. Object.defineProperty(Camera.prototype, "leftCamera", {
  20389. // ---- Camera rigs section ----
  20390. get: function () {
  20391. if (this._rigCameras.length < 1) {
  20392. return null;
  20393. }
  20394. return this._rigCameras[0];
  20395. },
  20396. enumerable: true,
  20397. configurable: true
  20398. });
  20399. Object.defineProperty(Camera.prototype, "rightCamera", {
  20400. get: function () {
  20401. if (this._rigCameras.length < 2) {
  20402. return null;
  20403. }
  20404. return this._rigCameras[1];
  20405. },
  20406. enumerable: true,
  20407. configurable: true
  20408. });
  20409. Camera.prototype.getLeftTarget = function () {
  20410. if (this._rigCameras.length < 1) {
  20411. return null;
  20412. }
  20413. return this._rigCameras[0].getTarget();
  20414. };
  20415. Camera.prototype.getRightTarget = function () {
  20416. if (this._rigCameras.length < 2) {
  20417. return null;
  20418. }
  20419. return this._rigCameras[1].getTarget();
  20420. };
  20421. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  20422. if (this.cameraRigMode === mode) {
  20423. return;
  20424. }
  20425. while (this._rigCameras.length > 0) {
  20426. var camera = this._rigCameras.pop();
  20427. if (camera) {
  20428. camera.dispose();
  20429. }
  20430. }
  20431. this.cameraRigMode = mode;
  20432. this._cameraRigParams = {};
  20433. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  20434. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  20435. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  20436. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  20437. // create the rig cameras, unless none
  20438. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  20439. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  20440. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  20441. if (leftCamera && rightCamera) {
  20442. this._rigCameras.push(leftCamera);
  20443. this._rigCameras.push(rightCamera);
  20444. }
  20445. }
  20446. switch (this.cameraRigMode) {
  20447. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  20448. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  20449. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  20450. break;
  20451. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  20452. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  20453. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  20454. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  20455. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  20456. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  20457. break;
  20458. case Camera.RIG_MODE_VR:
  20459. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  20460. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  20461. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  20462. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  20463. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  20464. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  20465. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  20466. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  20467. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  20468. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  20469. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  20470. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  20471. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  20472. if (metrics.compensateDistortion) {
  20473. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  20474. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  20475. }
  20476. break;
  20477. case Camera.RIG_MODE_WEBVR:
  20478. if (rigParams.vrDisplay) {
  20479. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  20480. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  20481. //Left eye
  20482. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  20483. this._rigCameras[0].setCameraRigParameter("left", true);
  20484. //leaving this for future reference
  20485. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  20486. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  20487. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  20488. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  20489. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  20490. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  20491. this._rigCameras[0].parent = this;
  20492. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  20493. //Right eye
  20494. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  20495. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  20496. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  20497. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  20498. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  20499. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  20500. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  20501. this._rigCameras[1].parent = this;
  20502. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  20503. if (Camera.UseAlternateWebVRRendering) {
  20504. this._rigCameras[1]._skipRendering = true;
  20505. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  20506. }
  20507. }
  20508. break;
  20509. }
  20510. this._cascadePostProcessesToRigCams();
  20511. this.update();
  20512. };
  20513. Camera.prototype._getVRProjectionMatrix = function () {
  20514. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  20515. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  20516. return this._projectionMatrix;
  20517. };
  20518. Camera.prototype._updateCameraRotationMatrix = function () {
  20519. //Here for WebVR
  20520. };
  20521. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  20522. //Here for WebVR
  20523. };
  20524. /**
  20525. * This function MUST be overwritten by the different WebVR cameras available.
  20526. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  20527. */
  20528. Camera.prototype._getWebVRProjectionMatrix = function () {
  20529. return BABYLON.Matrix.Identity();
  20530. };
  20531. /**
  20532. * This function MUST be overwritten by the different WebVR cameras available.
  20533. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  20534. */
  20535. Camera.prototype._getWebVRViewMatrix = function () {
  20536. return BABYLON.Matrix.Identity();
  20537. };
  20538. Camera.prototype.setCameraRigParameter = function (name, value) {
  20539. if (!this._cameraRigParams) {
  20540. this._cameraRigParams = {};
  20541. }
  20542. this._cameraRigParams[name] = value;
  20543. //provisionnally:
  20544. if (name === "interaxialDistance") {
  20545. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  20546. }
  20547. };
  20548. /**
  20549. * needs to be overridden by children so sub has required properties to be copied
  20550. */
  20551. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  20552. return null;
  20553. };
  20554. /**
  20555. * May need to be overridden by children
  20556. */
  20557. Camera.prototype._updateRigCameras = function () {
  20558. for (var i = 0; i < this._rigCameras.length; i++) {
  20559. this._rigCameras[i].minZ = this.minZ;
  20560. this._rigCameras[i].maxZ = this.maxZ;
  20561. this._rigCameras[i].fov = this.fov;
  20562. }
  20563. // only update viewport when ANAGLYPH
  20564. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  20565. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  20566. }
  20567. };
  20568. Camera.prototype._setupInputs = function () {
  20569. };
  20570. Camera.prototype.serialize = function () {
  20571. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  20572. // Type
  20573. serializationObject.type = this.getClassName();
  20574. // Parent
  20575. if (this.parent) {
  20576. serializationObject.parentId = this.parent.id;
  20577. }
  20578. if (this.inputs) {
  20579. this.inputs.serialize(serializationObject);
  20580. }
  20581. // Animations
  20582. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  20583. serializationObject.ranges = this.serializeAnimationRanges();
  20584. return serializationObject;
  20585. };
  20586. Camera.prototype.clone = function (name) {
  20587. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  20588. };
  20589. Camera.prototype.getDirection = function (localAxis) {
  20590. var result = BABYLON.Vector3.Zero();
  20591. this.getDirectionToRef(localAxis, result);
  20592. return result;
  20593. };
  20594. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  20595. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  20596. };
  20597. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  20598. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  20599. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  20600. switch (type) {
  20601. case "ArcRotateCamera":
  20602. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  20603. case "DeviceOrientationCamera":
  20604. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  20605. case "FollowCamera":
  20606. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  20607. case "ArcFollowCamera":
  20608. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  20609. case "GamepadCamera":
  20610. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  20611. case "TouchCamera":
  20612. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  20613. case "VirtualJoysticksCamera":
  20614. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  20615. case "WebVRFreeCamera":
  20616. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  20617. case "WebVRGamepadCamera":
  20618. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  20619. case "VRDeviceOrientationFreeCamera":
  20620. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  20621. case "VRDeviceOrientationGamepadCamera":
  20622. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  20623. case "AnaglyphArcRotateCamera":
  20624. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20625. case "AnaglyphFreeCamera":
  20626. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20627. case "AnaglyphGamepadCamera":
  20628. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20629. case "AnaglyphUniversalCamera":
  20630. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20631. case "StereoscopicArcRotateCamera":
  20632. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20633. case "StereoscopicFreeCamera":
  20634. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20635. case "StereoscopicGamepadCamera":
  20636. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20637. case "StereoscopicUniversalCamera":
  20638. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20639. case "FreeCamera":// Forcing Universal here
  20640. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  20641. default:// Universal Camera is the default value
  20642. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  20643. }
  20644. };
  20645. Camera.prototype.computeWorldMatrix = function () {
  20646. return this.getWorldMatrix();
  20647. };
  20648. Camera.Parse = function (parsedCamera, scene) {
  20649. var type = parsedCamera.type;
  20650. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  20651. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  20652. // Parent
  20653. if (parsedCamera.parentId) {
  20654. camera._waitingParentId = parsedCamera.parentId;
  20655. }
  20656. //If camera has an input manager, let it parse inputs settings
  20657. if (camera.inputs) {
  20658. camera.inputs.parse(parsedCamera);
  20659. camera._setupInputs();
  20660. }
  20661. if (camera.setPosition) {
  20662. camera.position.copyFromFloats(0, 0, 0);
  20663. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  20664. }
  20665. // Target
  20666. if (parsedCamera.target) {
  20667. if (camera.setTarget) {
  20668. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  20669. }
  20670. }
  20671. // Apply 3d rig, when found
  20672. if (parsedCamera.cameraRigMode) {
  20673. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  20674. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  20675. }
  20676. // Animations
  20677. if (parsedCamera.animations) {
  20678. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  20679. var parsedAnimation = parsedCamera.animations[animationIndex];
  20680. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  20681. }
  20682. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  20683. }
  20684. if (parsedCamera.autoAnimate) {
  20685. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  20686. }
  20687. return camera;
  20688. };
  20689. // Statics
  20690. Camera._PERSPECTIVE_CAMERA = 0;
  20691. Camera._ORTHOGRAPHIC_CAMERA = 1;
  20692. Camera._FOVMODE_VERTICAL_FIXED = 0;
  20693. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  20694. Camera._RIG_MODE_NONE = 0;
  20695. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  20696. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  20697. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  20698. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  20699. Camera._RIG_MODE_VR = 20;
  20700. Camera._RIG_MODE_WEBVR = 21;
  20701. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  20702. Camera.UseAlternateWebVRRendering = false;
  20703. __decorate([
  20704. BABYLON.serializeAsVector3()
  20705. ], Camera.prototype, "position", void 0);
  20706. __decorate([
  20707. BABYLON.serializeAsVector3()
  20708. ], Camera.prototype, "upVector", void 0);
  20709. __decorate([
  20710. BABYLON.serialize()
  20711. ], Camera.prototype, "orthoLeft", void 0);
  20712. __decorate([
  20713. BABYLON.serialize()
  20714. ], Camera.prototype, "orthoRight", void 0);
  20715. __decorate([
  20716. BABYLON.serialize()
  20717. ], Camera.prototype, "orthoBottom", void 0);
  20718. __decorate([
  20719. BABYLON.serialize()
  20720. ], Camera.prototype, "orthoTop", void 0);
  20721. __decorate([
  20722. BABYLON.serialize()
  20723. ], Camera.prototype, "fov", void 0);
  20724. __decorate([
  20725. BABYLON.serialize()
  20726. ], Camera.prototype, "minZ", void 0);
  20727. __decorate([
  20728. BABYLON.serialize()
  20729. ], Camera.prototype, "maxZ", void 0);
  20730. __decorate([
  20731. BABYLON.serialize()
  20732. ], Camera.prototype, "inertia", void 0);
  20733. __decorate([
  20734. BABYLON.serialize()
  20735. ], Camera.prototype, "mode", void 0);
  20736. __decorate([
  20737. BABYLON.serialize()
  20738. ], Camera.prototype, "layerMask", void 0);
  20739. __decorate([
  20740. BABYLON.serialize()
  20741. ], Camera.prototype, "fovMode", void 0);
  20742. __decorate([
  20743. BABYLON.serialize()
  20744. ], Camera.prototype, "cameraRigMode", void 0);
  20745. __decorate([
  20746. BABYLON.serialize()
  20747. ], Camera.prototype, "interaxialDistance", void 0);
  20748. __decorate([
  20749. BABYLON.serialize()
  20750. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  20751. return Camera;
  20752. }(BABYLON.Node));
  20753. BABYLON.Camera = Camera;
  20754. })(BABYLON || (BABYLON = {}));
  20755. //# sourceMappingURL=babylon.camera.js.map
  20756. var BABYLON;
  20757. (function (BABYLON) {
  20758. var RenderingManager = /** @class */ (function () {
  20759. function RenderingManager(scene) {
  20760. this._renderingGroups = new Array();
  20761. this._autoClearDepthStencil = {};
  20762. this._customOpaqueSortCompareFn = {};
  20763. this._customAlphaTestSortCompareFn = {};
  20764. this._customTransparentSortCompareFn = {};
  20765. this._renderinGroupInfo = null;
  20766. this._scene = scene;
  20767. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  20768. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  20769. }
  20770. }
  20771. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  20772. if (depth === void 0) { depth = true; }
  20773. if (stencil === void 0) { stencil = true; }
  20774. if (this._depthStencilBufferAlreadyCleaned) {
  20775. return;
  20776. }
  20777. this._scene.getEngine().clear(null, false, depth, stencil);
  20778. this._depthStencilBufferAlreadyCleaned = true;
  20779. };
  20780. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  20781. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  20782. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  20783. var info = null;
  20784. if (observable) {
  20785. if (!this._renderinGroupInfo) {
  20786. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  20787. }
  20788. info = this._renderinGroupInfo;
  20789. info.scene = this._scene;
  20790. info.camera = this._scene.activeCamera;
  20791. }
  20792. // Dispatch sprites
  20793. if (renderSprites) {
  20794. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  20795. var manager = this._scene.spriteManagers[index];
  20796. this.dispatchSprites(manager);
  20797. }
  20798. }
  20799. // Render
  20800. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  20801. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  20802. var renderingGroup = this._renderingGroups[index];
  20803. if (!renderingGroup && !observable)
  20804. continue;
  20805. var renderingGroupMask = 0;
  20806. // Fire PRECLEAR stage
  20807. if (observable && info) {
  20808. renderingGroupMask = Math.pow(2, index);
  20809. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  20810. info.renderingGroupId = index;
  20811. observable.notifyObservers(info, renderingGroupMask);
  20812. }
  20813. // Clear depth/stencil if needed
  20814. if (RenderingManager.AUTOCLEAR) {
  20815. var autoClear = this._autoClearDepthStencil[index];
  20816. if (autoClear && autoClear.autoClear) {
  20817. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  20818. }
  20819. }
  20820. if (observable && info) {
  20821. // Fire PREOPAQUE stage
  20822. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  20823. observable.notifyObservers(info, renderingGroupMask);
  20824. // Fire PRETRANSPARENT stage
  20825. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  20826. observable.notifyObservers(info, renderingGroupMask);
  20827. }
  20828. if (renderingGroup)
  20829. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  20830. // Fire POSTTRANSPARENT stage
  20831. if (observable && info) {
  20832. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  20833. observable.notifyObservers(info, renderingGroupMask);
  20834. }
  20835. }
  20836. };
  20837. RenderingManager.prototype.reset = function () {
  20838. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  20839. var renderingGroup = this._renderingGroups[index];
  20840. if (renderingGroup) {
  20841. renderingGroup.prepare();
  20842. }
  20843. }
  20844. };
  20845. RenderingManager.prototype.dispose = function () {
  20846. this.freeRenderingGroups();
  20847. this._renderingGroups.length = 0;
  20848. };
  20849. /**
  20850. * Clear the info related to rendering groups preventing retention points during dispose.
  20851. */
  20852. RenderingManager.prototype.freeRenderingGroups = function () {
  20853. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  20854. var renderingGroup = this._renderingGroups[index];
  20855. if (renderingGroup) {
  20856. renderingGroup.dispose();
  20857. }
  20858. }
  20859. };
  20860. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  20861. if (this._renderingGroups[renderingGroupId] === undefined) {
  20862. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  20863. }
  20864. };
  20865. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  20866. var renderingGroupId = spriteManager.renderingGroupId || 0;
  20867. this._prepareRenderingGroup(renderingGroupId);
  20868. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  20869. };
  20870. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  20871. var renderingGroupId = particleSystem.renderingGroupId || 0;
  20872. this._prepareRenderingGroup(renderingGroupId);
  20873. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  20874. };
  20875. /**
  20876. * @param subMesh The submesh to dispatch
  20877. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  20878. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  20879. */
  20880. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  20881. if (mesh === undefined) {
  20882. mesh = subMesh.getMesh();
  20883. }
  20884. var renderingGroupId = mesh.renderingGroupId || 0;
  20885. this._prepareRenderingGroup(renderingGroupId);
  20886. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  20887. };
  20888. /**
  20889. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  20890. * This allowed control for front to back rendering or reversly depending of the special needs.
  20891. *
  20892. * @param renderingGroupId The rendering group id corresponding to its index
  20893. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  20894. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  20895. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  20896. */
  20897. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  20898. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  20899. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  20900. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  20901. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  20902. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  20903. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  20904. if (this._renderingGroups[renderingGroupId]) {
  20905. var group = this._renderingGroups[renderingGroupId];
  20906. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  20907. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  20908. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  20909. }
  20910. };
  20911. /**
  20912. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  20913. *
  20914. * @param renderingGroupId The rendering group id corresponding to its index
  20915. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  20916. * @param depth Automatically clears depth between groups if true and autoClear is true.
  20917. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  20918. */
  20919. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  20920. if (depth === void 0) { depth = true; }
  20921. if (stencil === void 0) { stencil = true; }
  20922. this._autoClearDepthStencil[renderingGroupId] = {
  20923. autoClear: autoClearDepthStencil,
  20924. depth: depth,
  20925. stencil: stencil
  20926. };
  20927. };
  20928. /**
  20929. * The max id used for rendering groups (not included)
  20930. */
  20931. RenderingManager.MAX_RENDERINGGROUPS = 4;
  20932. /**
  20933. * The min id used for rendering groups (included)
  20934. */
  20935. RenderingManager.MIN_RENDERINGGROUPS = 0;
  20936. /**
  20937. * Used to globally prevent autoclearing scenes.
  20938. */
  20939. RenderingManager.AUTOCLEAR = true;
  20940. return RenderingManager;
  20941. }());
  20942. BABYLON.RenderingManager = RenderingManager;
  20943. })(BABYLON || (BABYLON = {}));
  20944. //# sourceMappingURL=babylon.renderingManager.js.map
  20945. var BABYLON;
  20946. (function (BABYLON) {
  20947. var RenderingGroup = /** @class */ (function () {
  20948. /**
  20949. * Creates a new rendering group.
  20950. * @param index The rendering group index
  20951. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  20952. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  20953. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  20954. */
  20955. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  20956. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  20957. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  20958. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  20959. this.index = index;
  20960. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  20961. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  20962. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  20963. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  20964. this._particleSystems = new BABYLON.SmartArray(256);
  20965. this._spriteManagers = new BABYLON.SmartArray(256);
  20966. this._edgesRenderers = new BABYLON.SmartArray(16);
  20967. this._scene = scene;
  20968. this.opaqueSortCompareFn = opaqueSortCompareFn;
  20969. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  20970. this.transparentSortCompareFn = transparentSortCompareFn;
  20971. }
  20972. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  20973. /**
  20974. * Set the opaque sort comparison function.
  20975. * If null the sub meshes will be render in the order they were created
  20976. */
  20977. set: function (value) {
  20978. this._opaqueSortCompareFn = value;
  20979. if (value) {
  20980. this._renderOpaque = this.renderOpaqueSorted;
  20981. }
  20982. else {
  20983. this._renderOpaque = RenderingGroup.renderUnsorted;
  20984. }
  20985. },
  20986. enumerable: true,
  20987. configurable: true
  20988. });
  20989. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  20990. /**
  20991. * Set the alpha test sort comparison function.
  20992. * If null the sub meshes will be render in the order they were created
  20993. */
  20994. set: function (value) {
  20995. this._alphaTestSortCompareFn = value;
  20996. if (value) {
  20997. this._renderAlphaTest = this.renderAlphaTestSorted;
  20998. }
  20999. else {
  21000. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  21001. }
  21002. },
  21003. enumerable: true,
  21004. configurable: true
  21005. });
  21006. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  21007. /**
  21008. * Set the transparent sort comparison function.
  21009. * If null the sub meshes will be render in the order they were created
  21010. */
  21011. set: function (value) {
  21012. if (value) {
  21013. this._transparentSortCompareFn = value;
  21014. }
  21015. else {
  21016. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  21017. }
  21018. this._renderTransparent = this.renderTransparentSorted;
  21019. },
  21020. enumerable: true,
  21021. configurable: true
  21022. });
  21023. /**
  21024. * Render all the sub meshes contained in the group.
  21025. * @param customRenderFunction Used to override the default render behaviour of the group.
  21026. * @returns true if rendered some submeshes.
  21027. */
  21028. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  21029. if (customRenderFunction) {
  21030. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  21031. return;
  21032. }
  21033. var engine = this._scene.getEngine();
  21034. // Depth only
  21035. if (this._depthOnlySubMeshes.length !== 0) {
  21036. engine.setColorWrite(false);
  21037. this._renderAlphaTest(this._depthOnlySubMeshes);
  21038. engine.setColorWrite(true);
  21039. }
  21040. // Opaque
  21041. if (this._opaqueSubMeshes.length !== 0) {
  21042. this._renderOpaque(this._opaqueSubMeshes);
  21043. }
  21044. // Alpha test
  21045. if (this._alphaTestSubMeshes.length !== 0) {
  21046. this._renderAlphaTest(this._alphaTestSubMeshes);
  21047. }
  21048. var stencilState = engine.getStencilBuffer();
  21049. engine.setStencilBuffer(false);
  21050. // Sprites
  21051. if (renderSprites) {
  21052. this._renderSprites();
  21053. }
  21054. // Particles
  21055. if (renderParticles) {
  21056. this._renderParticles(activeMeshes);
  21057. }
  21058. if (this.onBeforeTransparentRendering) {
  21059. this.onBeforeTransparentRendering();
  21060. }
  21061. // Transparent
  21062. if (this._transparentSubMeshes.length !== 0) {
  21063. this._renderTransparent(this._transparentSubMeshes);
  21064. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  21065. }
  21066. // Set back stencil to false in case it changes before the edge renderer.
  21067. engine.setStencilBuffer(false);
  21068. // Edges
  21069. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  21070. this._edgesRenderers.data[edgesRendererIndex].render();
  21071. }
  21072. // Restore Stencil state.
  21073. engine.setStencilBuffer(stencilState);
  21074. };
  21075. /**
  21076. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  21077. * @param subMeshes The submeshes to render
  21078. */
  21079. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  21080. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  21081. };
  21082. /**
  21083. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  21084. * @param subMeshes The submeshes to render
  21085. */
  21086. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  21087. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  21088. };
  21089. /**
  21090. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  21091. * @param subMeshes The submeshes to render
  21092. */
  21093. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  21094. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  21095. };
  21096. /**
  21097. * Renders the submeshes in a specified order.
  21098. * @param subMeshes The submeshes to sort before render
  21099. * @param sortCompareFn The comparison function use to sort
  21100. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  21101. * @param transparent Specifies to activate blending if true
  21102. */
  21103. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  21104. var subIndex = 0;
  21105. var subMesh;
  21106. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  21107. for (; subIndex < subMeshes.length; subIndex++) {
  21108. subMesh = subMeshes.data[subIndex];
  21109. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  21110. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  21111. }
  21112. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  21113. if (sortCompareFn) {
  21114. sortedArray.sort(sortCompareFn);
  21115. }
  21116. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  21117. subMesh = sortedArray[subIndex];
  21118. if (transparent) {
  21119. var material = subMesh.getMaterial();
  21120. if (material && material.needDepthPrePass) {
  21121. var engine = material.getScene().getEngine();
  21122. engine.setColorWrite(false);
  21123. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  21124. subMesh.render(false);
  21125. engine.setColorWrite(true);
  21126. }
  21127. }
  21128. subMesh.render(transparent);
  21129. }
  21130. };
  21131. /**
  21132. * Renders the submeshes in the order they were dispatched (no sort applied).
  21133. * @param subMeshes The submeshes to render
  21134. */
  21135. RenderingGroup.renderUnsorted = function (subMeshes) {
  21136. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  21137. var submesh = subMeshes.data[subIndex];
  21138. submesh.render(false);
  21139. }
  21140. };
  21141. /**
  21142. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  21143. * are rendered back to front if in the same alpha index.
  21144. *
  21145. * @param a The first submesh
  21146. * @param b The second submesh
  21147. * @returns The result of the comparison
  21148. */
  21149. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  21150. // Alpha index first
  21151. if (a._alphaIndex > b._alphaIndex) {
  21152. return 1;
  21153. }
  21154. if (a._alphaIndex < b._alphaIndex) {
  21155. return -1;
  21156. }
  21157. // Then distance to camera
  21158. return RenderingGroup.backToFrontSortCompare(a, b);
  21159. };
  21160. /**
  21161. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  21162. * are rendered back to front.
  21163. *
  21164. * @param a The first submesh
  21165. * @param b The second submesh
  21166. * @returns The result of the comparison
  21167. */
  21168. RenderingGroup.backToFrontSortCompare = function (a, b) {
  21169. // Then distance to camera
  21170. if (a._distanceToCamera < b._distanceToCamera) {
  21171. return 1;
  21172. }
  21173. if (a._distanceToCamera > b._distanceToCamera) {
  21174. return -1;
  21175. }
  21176. return 0;
  21177. };
  21178. /**
  21179. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  21180. * are rendered front to back (prevent overdraw).
  21181. *
  21182. * @param a The first submesh
  21183. * @param b The second submesh
  21184. * @returns The result of the comparison
  21185. */
  21186. RenderingGroup.frontToBackSortCompare = function (a, b) {
  21187. // Then distance to camera
  21188. if (a._distanceToCamera < b._distanceToCamera) {
  21189. return -1;
  21190. }
  21191. if (a._distanceToCamera > b._distanceToCamera) {
  21192. return 1;
  21193. }
  21194. return 0;
  21195. };
  21196. /**
  21197. * Resets the different lists of submeshes to prepare a new frame.
  21198. */
  21199. RenderingGroup.prototype.prepare = function () {
  21200. this._opaqueSubMeshes.reset();
  21201. this._transparentSubMeshes.reset();
  21202. this._alphaTestSubMeshes.reset();
  21203. this._depthOnlySubMeshes.reset();
  21204. this._particleSystems.reset();
  21205. this._spriteManagers.reset();
  21206. this._edgesRenderers.reset();
  21207. };
  21208. RenderingGroup.prototype.dispose = function () {
  21209. this._opaqueSubMeshes.dispose();
  21210. this._transparentSubMeshes.dispose();
  21211. this._alphaTestSubMeshes.dispose();
  21212. this._depthOnlySubMeshes.dispose();
  21213. this._particleSystems.dispose();
  21214. this._spriteManagers.dispose();
  21215. this._edgesRenderers.dispose();
  21216. };
  21217. /**
  21218. * Inserts the submesh in its correct queue depending on its material.
  21219. * @param subMesh The submesh to dispatch
  21220. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  21221. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  21222. */
  21223. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  21224. // Get mesh and materials if not provided
  21225. if (mesh === undefined) {
  21226. mesh = subMesh.getMesh();
  21227. }
  21228. if (material === undefined) {
  21229. material = subMesh.getMaterial();
  21230. }
  21231. if (material === null || material === undefined) {
  21232. return;
  21233. }
  21234. if (material.needAlphaBlendingForMesh(mesh)) {
  21235. this._transparentSubMeshes.push(subMesh);
  21236. }
  21237. else if (material.needAlphaTesting()) {
  21238. if (material.needDepthPrePass) {
  21239. this._depthOnlySubMeshes.push(subMesh);
  21240. }
  21241. this._alphaTestSubMeshes.push(subMesh);
  21242. }
  21243. else {
  21244. if (material.needDepthPrePass) {
  21245. this._depthOnlySubMeshes.push(subMesh);
  21246. }
  21247. this._opaqueSubMeshes.push(subMesh); // Opaque
  21248. }
  21249. if (mesh._edgesRenderer !== null && mesh._edgesRenderer !== undefined) {
  21250. this._edgesRenderers.push(mesh._edgesRenderer);
  21251. }
  21252. };
  21253. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  21254. this._spriteManagers.push(spriteManager);
  21255. };
  21256. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  21257. this._particleSystems.push(particleSystem);
  21258. };
  21259. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  21260. if (this._particleSystems.length === 0) {
  21261. return;
  21262. }
  21263. // Particles
  21264. var activeCamera = this._scene.activeCamera;
  21265. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  21266. for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {
  21267. var particleSystem = this._particleSystems.data[particleIndex];
  21268. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  21269. continue;
  21270. }
  21271. var emitter = particleSystem.emitter;
  21272. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  21273. this._scene._activeParticles.addCount(particleSystem.render(), false);
  21274. }
  21275. }
  21276. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  21277. };
  21278. RenderingGroup.prototype._renderSprites = function () {
  21279. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  21280. return;
  21281. }
  21282. // Sprites
  21283. var activeCamera = this._scene.activeCamera;
  21284. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  21285. for (var id = 0; id < this._spriteManagers.length; id++) {
  21286. var spriteManager = this._spriteManagers.data[id];
  21287. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  21288. spriteManager.render();
  21289. }
  21290. }
  21291. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  21292. };
  21293. return RenderingGroup;
  21294. }());
  21295. BABYLON.RenderingGroup = RenderingGroup;
  21296. })(BABYLON || (BABYLON = {}));
  21297. //# sourceMappingURL=babylon.renderingGroup.js.map
  21298. var BABYLON;
  21299. (function (BABYLON) {
  21300. var ClickInfo = /** @class */ (function () {
  21301. function ClickInfo() {
  21302. this._singleClick = false;
  21303. this._doubleClick = false;
  21304. this._hasSwiped = false;
  21305. this._ignore = false;
  21306. }
  21307. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  21308. get: function () {
  21309. return this._singleClick;
  21310. },
  21311. set: function (b) {
  21312. this._singleClick = b;
  21313. },
  21314. enumerable: true,
  21315. configurable: true
  21316. });
  21317. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  21318. get: function () {
  21319. return this._doubleClick;
  21320. },
  21321. set: function (b) {
  21322. this._doubleClick = b;
  21323. },
  21324. enumerable: true,
  21325. configurable: true
  21326. });
  21327. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  21328. get: function () {
  21329. return this._hasSwiped;
  21330. },
  21331. set: function (b) {
  21332. this._hasSwiped = b;
  21333. },
  21334. enumerable: true,
  21335. configurable: true
  21336. });
  21337. Object.defineProperty(ClickInfo.prototype, "ignore", {
  21338. get: function () {
  21339. return this._ignore;
  21340. },
  21341. set: function (b) {
  21342. this._ignore = b;
  21343. },
  21344. enumerable: true,
  21345. configurable: true
  21346. });
  21347. return ClickInfo;
  21348. }());
  21349. /**
  21350. * This class is used by the onRenderingGroupObservable
  21351. */
  21352. var RenderingGroupInfo = /** @class */ (function () {
  21353. function RenderingGroupInfo() {
  21354. }
  21355. /**
  21356. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  21357. * This stage will be fired no matter what
  21358. */
  21359. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  21360. /**
  21361. * Called before opaque object are rendered.
  21362. * This stage will be fired only if there's 3D Opaque content to render
  21363. */
  21364. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  21365. /**
  21366. * Called after the opaque objects are rendered and before the transparent ones
  21367. * This stage will be fired only if there's 3D transparent content to render
  21368. */
  21369. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  21370. /**
  21371. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  21372. * This stage will be fired no matter what
  21373. */
  21374. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  21375. return RenderingGroupInfo;
  21376. }());
  21377. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  21378. /**
  21379. * Represents a scene to be rendered by the engine.
  21380. * @see http://doc.babylonjs.com/page.php?p=21911
  21381. */
  21382. var Scene = /** @class */ (function () {
  21383. /**
  21384. * @constructor
  21385. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  21386. */
  21387. function Scene(engine) {
  21388. // Members
  21389. this.autoClear = true;
  21390. this.autoClearDepthAndStencil = true;
  21391. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  21392. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  21393. this.forceWireframe = false;
  21394. this._forcePointsCloud = false;
  21395. this.forceShowBoundingBoxes = false;
  21396. this.animationsEnabled = true;
  21397. this.useConstantAnimationDeltaTime = false;
  21398. this.constantlyUpdateMeshUnderPointer = false;
  21399. this.hoverCursor = "pointer";
  21400. this.defaultCursor = "";
  21401. /**
  21402. * This is used to call preventDefault() on pointer down
  21403. * in order to block unwanted artifacts like system double clicks
  21404. */
  21405. this.preventDefaultOnPointerDown = true;
  21406. // Metadata
  21407. this.metadata = null;
  21408. /**
  21409. * An event triggered when the scene is disposed.
  21410. * @type {BABYLON.Observable}
  21411. */
  21412. this.onDisposeObservable = new BABYLON.Observable();
  21413. /**
  21414. * An event triggered before rendering the scene (right after animations and physics)
  21415. * @type {BABYLON.Observable}
  21416. */
  21417. this.onBeforeRenderObservable = new BABYLON.Observable();
  21418. /**
  21419. * An event triggered after rendering the scene
  21420. * @type {BABYLON.Observable}
  21421. */
  21422. this.onAfterRenderObservable = new BABYLON.Observable();
  21423. /**
  21424. * An event triggered before animating the scene
  21425. * @type {BABYLON.Observable}
  21426. */
  21427. this.onBeforeAnimationsObservable = new BABYLON.Observable();
  21428. /**
  21429. * An event triggered after animations processing
  21430. * @type {BABYLON.Observable}
  21431. */
  21432. this.onAfterAnimationsObservable = new BABYLON.Observable();
  21433. /**
  21434. * An event triggered before draw calls are ready to be sent
  21435. * @type {BABYLON.Observable}
  21436. */
  21437. this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  21438. /**
  21439. * An event triggered after draw calls have been sent
  21440. * @type {BABYLON.Observable}
  21441. */
  21442. this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  21443. /**
  21444. * An event triggered when physic simulation is about to be run
  21445. * @type {BABYLON.Observable}
  21446. */
  21447. this.onBeforePhysicsObservable = new BABYLON.Observable();
  21448. /**
  21449. * An event triggered when physic simulation has been done
  21450. * @type {BABYLON.Observable}
  21451. */
  21452. this.onAfterPhysicsObservable = new BABYLON.Observable();
  21453. /**
  21454. * An event triggered when the scene is ready
  21455. * @type {BABYLON.Observable}
  21456. */
  21457. this.onReadyObservable = new BABYLON.Observable();
  21458. /**
  21459. * An event triggered before rendering a camera
  21460. * @type {BABYLON.Observable}
  21461. */
  21462. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  21463. /**
  21464. * An event triggered after rendering a camera
  21465. * @type {BABYLON.Observable}
  21466. */
  21467. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  21468. /**
  21469. * An event triggered when active meshes evaluation is about to start
  21470. * @type {BABYLON.Observable}
  21471. */
  21472. this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  21473. /**
  21474. * An event triggered when active meshes evaluation is done
  21475. * @type {BABYLON.Observable}
  21476. */
  21477. this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  21478. /**
  21479. * An event triggered when particles rendering is about to start
  21480. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  21481. * @type {BABYLON.Observable}
  21482. */
  21483. this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  21484. /**
  21485. * An event triggered when particles rendering is done
  21486. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  21487. * @type {BABYLON.Observable}
  21488. */
  21489. this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  21490. /**
  21491. * An event triggered when sprites rendering is about to start
  21492. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  21493. * @type {BABYLON.Observable}
  21494. */
  21495. this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  21496. /**
  21497. * An event triggered when sprites rendering is done
  21498. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  21499. * @type {BABYLON.Observable}
  21500. */
  21501. this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  21502. /**
  21503. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  21504. * @type {BABYLON.Observable}
  21505. */
  21506. this.onDataLoadedObservable = new BABYLON.Observable();
  21507. /**
  21508. * An event triggered when a camera is created
  21509. * @type {BABYLON.Observable}
  21510. */
  21511. this.onNewCameraAddedObservable = new BABYLON.Observable();
  21512. /**
  21513. * An event triggered when a camera is removed
  21514. * @type {BABYLON.Observable}
  21515. */
  21516. this.onCameraRemovedObservable = new BABYLON.Observable();
  21517. /**
  21518. * An event triggered when a light is created
  21519. * @type {BABYLON.Observable}
  21520. */
  21521. this.onNewLightAddedObservable = new BABYLON.Observable();
  21522. /**
  21523. * An event triggered when a light is removed
  21524. * @type {BABYLON.Observable}
  21525. */
  21526. this.onLightRemovedObservable = new BABYLON.Observable();
  21527. /**
  21528. * An event triggered when a geometry is created
  21529. * @type {BABYLON.Observable}
  21530. */
  21531. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  21532. /**
  21533. * An event triggered when a geometry is removed
  21534. * @type {BABYLON.Observable}
  21535. */
  21536. this.onGeometryRemovedObservable = new BABYLON.Observable();
  21537. /**
  21538. * An event triggered when a transform node is created
  21539. * @type {BABYLON.Observable}
  21540. */
  21541. this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  21542. /**
  21543. * An event triggered when a transform node is removed
  21544. * @type {BABYLON.Observable}
  21545. */
  21546. this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  21547. /**
  21548. * An event triggered when a mesh is created
  21549. * @type {BABYLON.Observable}
  21550. */
  21551. this.onNewMeshAddedObservable = new BABYLON.Observable();
  21552. /**
  21553. * An event triggered when a mesh is removed
  21554. * @type {BABYLON.Observable}
  21555. */
  21556. this.onMeshRemovedObservable = new BABYLON.Observable();
  21557. /**
  21558. * An event triggered when render targets are about to be rendered
  21559. * Can happen multiple times per frame.
  21560. * @type {BABYLON.Observable}
  21561. */
  21562. this.OnBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  21563. /**
  21564. * An event triggered when render targets were rendered.
  21565. * Can happen multiple times per frame.
  21566. * @type {BABYLON.Observable}
  21567. */
  21568. this.OnAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  21569. /**
  21570. * An event triggered before calculating deterministic simulation step
  21571. * @type {BABYLON.Observable}
  21572. */
  21573. this.onBeforeStepObservable = new BABYLON.Observable();
  21574. /**
  21575. * An event triggered after calculating deterministic simulation step
  21576. * @type {BABYLON.Observable}
  21577. */
  21578. this.onAfterStepObservable = new BABYLON.Observable();
  21579. /**
  21580. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  21581. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  21582. * 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)
  21583. */
  21584. this.onRenderingGroupObservable = new BABYLON.Observable();
  21585. // Animations
  21586. this.animations = [];
  21587. /**
  21588. * 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).
  21589. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  21590. */
  21591. this.onPrePointerObservable = new BABYLON.Observable();
  21592. /**
  21593. * Observable event triggered each time an input event is received from the rendering canvas
  21594. */
  21595. this.onPointerObservable = new BABYLON.Observable();
  21596. this._meshPickProceed = false;
  21597. this._currentPickResult = null;
  21598. this._previousPickResult = null;
  21599. this._totalPointersPressed = 0;
  21600. this._doubleClickOccured = false;
  21601. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  21602. this.cameraToUseForPointers = null;
  21603. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  21604. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  21605. this._startingPointerTime = 0;
  21606. this._previousStartingPointerTime = 0;
  21607. // Deterministic lockstep
  21608. this._timeAccumulator = 0;
  21609. this._currentStepId = 0;
  21610. this._currentInternalStep = 0;
  21611. // Keyboard
  21612. /**
  21613. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  21614. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  21615. */
  21616. this.onPreKeyboardObservable = new BABYLON.Observable();
  21617. /**
  21618. * Observable event triggered each time an keyboard event is received from the hosting window
  21619. */
  21620. this.onKeyboardObservable = new BABYLON.Observable();
  21621. // Coordinate system
  21622. /**
  21623. * use right-handed coordinate system on this scene.
  21624. * @type {boolean}
  21625. */
  21626. this._useRightHandedSystem = false;
  21627. // Fog
  21628. this._fogEnabled = true;
  21629. this._fogMode = Scene.FOGMODE_NONE;
  21630. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  21631. this.fogDensity = 0.1;
  21632. this.fogStart = 0;
  21633. this.fogEnd = 1000.0;
  21634. // Lights
  21635. /**
  21636. * is shadow enabled on this scene.
  21637. * @type {boolean}
  21638. */
  21639. this._shadowsEnabled = true;
  21640. /**
  21641. * is light enabled on this scene.
  21642. * @type {boolean}
  21643. */
  21644. this._lightsEnabled = true;
  21645. /**
  21646. * All of the lights added to this scene.
  21647. * @see BABYLON.Light
  21648. * @type {BABYLON.Light[]}
  21649. */
  21650. this.lights = new Array();
  21651. // Cameras
  21652. /** All of the cameras added to this scene. */
  21653. this.cameras = new Array();
  21654. /** All of the active cameras added to this scene. */
  21655. this.activeCameras = new Array();
  21656. // Meshes
  21657. /**
  21658. * All of the tranform nodes added to this scene.
  21659. * @see BABYLON.TransformNode
  21660. * @type {BABYLON.TransformNode[]}
  21661. */
  21662. this.transformNodes = new Array();
  21663. /**
  21664. * All of the (abstract) meshes added to this scene.
  21665. * @see BABYLON.AbstractMesh
  21666. * @type {BABYLON.AbstractMesh[]}
  21667. */
  21668. this.meshes = new Array();
  21669. /**
  21670. * All of the animation groups added to this scene.
  21671. * @see BABYLON.AnimationGroup
  21672. * @type {BABYLON.AnimationGroup[]}
  21673. */
  21674. this.animationGroups = new Array();
  21675. // Geometries
  21676. this._geometries = new Array();
  21677. this.materials = new Array();
  21678. this.multiMaterials = new Array();
  21679. // Textures
  21680. this._texturesEnabled = true;
  21681. this.textures = new Array();
  21682. // Particles
  21683. this.particlesEnabled = true;
  21684. this.particleSystems = new Array();
  21685. // Sprites
  21686. this.spritesEnabled = true;
  21687. this.spriteManagers = new Array();
  21688. /**
  21689. * The list of layers (background and foreground) of the scene.
  21690. */
  21691. this.layers = new Array();
  21692. /**
  21693. * The list of effect layers (highlights/glow) contained in the scene.
  21694. */
  21695. this.effectLayers = new Array();
  21696. // Skeletons
  21697. this._skeletonsEnabled = true;
  21698. this.skeletons = new Array();
  21699. // Morph targets
  21700. this.morphTargetManagers = new Array();
  21701. // Lens flares
  21702. this.lensFlaresEnabled = true;
  21703. this.lensFlareSystems = new Array();
  21704. // Collisions
  21705. this.collisionsEnabled = true;
  21706. /** Defines the gravity applied to this scene */
  21707. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  21708. // Postprocesses
  21709. this.postProcesses = new Array();
  21710. this.postProcessesEnabled = true;
  21711. // Customs render targets
  21712. this.renderTargetsEnabled = true;
  21713. this.dumpNextRenderTargets = false;
  21714. this.customRenderTargets = new Array();
  21715. // Imported meshes
  21716. this.importedMeshesFiles = new Array();
  21717. // Probes
  21718. this.probesEnabled = true;
  21719. this.reflectionProbes = new Array();
  21720. this._actionManagers = new Array();
  21721. this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  21722. // Procedural textures
  21723. this.proceduralTexturesEnabled = true;
  21724. this._proceduralTextures = new Array();
  21725. this.soundTracks = new Array();
  21726. this._audioEnabled = true;
  21727. this._headphone = false;
  21728. // Performance counters
  21729. this._totalVertices = new BABYLON.PerfCounter();
  21730. this._activeIndices = new BABYLON.PerfCounter();
  21731. this._activeParticles = new BABYLON.PerfCounter();
  21732. this._activeBones = new BABYLON.PerfCounter();
  21733. this._animationTime = 0;
  21734. this.animationTimeScale = 1;
  21735. this._renderId = 0;
  21736. this._executeWhenReadyTimeoutId = -1;
  21737. this._intermediateRendering = false;
  21738. this._viewUpdateFlag = -1;
  21739. this._projectionUpdateFlag = -1;
  21740. this._alternateViewUpdateFlag = -1;
  21741. this._alternateProjectionUpdateFlag = -1;
  21742. this._toBeDisposed = new BABYLON.SmartArray(256);
  21743. this._activeRequests = new Array();
  21744. this._pendingData = new Array();
  21745. this._isDisposed = false;
  21746. this.dispatchAllSubMeshesOfActiveMeshes = false;
  21747. this._activeMeshes = new BABYLON.SmartArray(256);
  21748. this._processedMaterials = new BABYLON.SmartArray(256);
  21749. this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  21750. this._activeParticleSystems = new BABYLON.SmartArray(256);
  21751. this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  21752. this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  21753. this._activeAnimatables = new Array();
  21754. this._transformMatrix = BABYLON.Matrix.Zero();
  21755. this._useAlternateCameraConfiguration = false;
  21756. this._alternateRendering = false;
  21757. this.requireLightSorting = false;
  21758. this._depthRenderer = {};
  21759. this._activeMeshesFrozen = false;
  21760. this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  21761. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  21762. this._engine.scenes.push(this);
  21763. this._uid = null;
  21764. this._renderingManager = new BABYLON.RenderingManager(this);
  21765. this.postProcessManager = new BABYLON.PostProcessManager(this);
  21766. if (BABYLON.OutlineRenderer) {
  21767. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  21768. }
  21769. if (BABYLON.Tools.IsWindowObjectExist()) {
  21770. this.attachControl();
  21771. }
  21772. //simplification queue
  21773. if (BABYLON.SimplificationQueue) {
  21774. this.simplificationQueue = new BABYLON.SimplificationQueue();
  21775. }
  21776. //collision coordinator initialization. For now legacy per default.
  21777. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  21778. // Uniform Buffer
  21779. this._createUbo();
  21780. // Default Image processing definition.
  21781. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  21782. }
  21783. Object.defineProperty(Scene, "FOGMODE_NONE", {
  21784. /** The fog is deactivated */
  21785. get: function () {
  21786. return Scene._FOGMODE_NONE;
  21787. },
  21788. enumerable: true,
  21789. configurable: true
  21790. });
  21791. Object.defineProperty(Scene, "FOGMODE_EXP", {
  21792. /** The fog density is following an exponential function */
  21793. get: function () {
  21794. return Scene._FOGMODE_EXP;
  21795. },
  21796. enumerable: true,
  21797. configurable: true
  21798. });
  21799. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  21800. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  21801. get: function () {
  21802. return Scene._FOGMODE_EXP2;
  21803. },
  21804. enumerable: true,
  21805. configurable: true
  21806. });
  21807. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  21808. /** The fog density is following a linear function. */
  21809. get: function () {
  21810. return Scene._FOGMODE_LINEAR;
  21811. },
  21812. enumerable: true,
  21813. configurable: true
  21814. });
  21815. Object.defineProperty(Scene.prototype, "environmentTexture", {
  21816. /**
  21817. * Texture used in all pbr material as the reflection texture.
  21818. * As in the majority of the scene they are the same (exception for multi room and so on),
  21819. * this is easier to reference from here than from all the materials.
  21820. */
  21821. get: function () {
  21822. return this._environmentTexture;
  21823. },
  21824. /**
  21825. * Texture used in all pbr material as the reflection texture.
  21826. * As in the majority of the scene they are the same (exception for multi room and so on),
  21827. * this is easier to set here than in all the materials.
  21828. */
  21829. set: function (value) {
  21830. if (this._environmentTexture === value) {
  21831. return;
  21832. }
  21833. this._environmentTexture = value;
  21834. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  21835. },
  21836. enumerable: true,
  21837. configurable: true
  21838. });
  21839. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  21840. /**
  21841. * Default image processing configuration used either in the rendering
  21842. * Forward main pass or through the imageProcessingPostProcess if present.
  21843. * As in the majority of the scene they are the same (exception for multi camera),
  21844. * this is easier to reference from here than from all the materials and post process.
  21845. *
  21846. * No setter as we it is a shared configuration, you can set the values instead.
  21847. */
  21848. get: function () {
  21849. return this._imageProcessingConfiguration;
  21850. },
  21851. enumerable: true,
  21852. configurable: true
  21853. });
  21854. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  21855. get: function () {
  21856. return this._forcePointsCloud;
  21857. },
  21858. set: function (value) {
  21859. if (this._forcePointsCloud === value) {
  21860. return;
  21861. }
  21862. this._forcePointsCloud = value;
  21863. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  21864. },
  21865. enumerable: true,
  21866. configurable: true
  21867. });
  21868. Object.defineProperty(Scene.prototype, "onDispose", {
  21869. /** A function to be executed when this scene is disposed. */
  21870. set: function (callback) {
  21871. if (this._onDisposeObserver) {
  21872. this.onDisposeObservable.remove(this._onDisposeObserver);
  21873. }
  21874. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  21875. },
  21876. enumerable: true,
  21877. configurable: true
  21878. });
  21879. Object.defineProperty(Scene.prototype, "beforeRender", {
  21880. /** A function to be executed before rendering this scene */
  21881. set: function (callback) {
  21882. if (this._onBeforeRenderObserver) {
  21883. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  21884. }
  21885. if (callback) {
  21886. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  21887. }
  21888. },
  21889. enumerable: true,
  21890. configurable: true
  21891. });
  21892. Object.defineProperty(Scene.prototype, "afterRender", {
  21893. /** A function to be executed after rendering this scene */
  21894. set: function (callback) {
  21895. if (this._onAfterRenderObserver) {
  21896. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  21897. }
  21898. if (callback) {
  21899. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  21900. }
  21901. },
  21902. enumerable: true,
  21903. configurable: true
  21904. });
  21905. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  21906. set: function (callback) {
  21907. if (this._onBeforeCameraRenderObserver) {
  21908. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  21909. }
  21910. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  21911. },
  21912. enumerable: true,
  21913. configurable: true
  21914. });
  21915. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  21916. set: function (callback) {
  21917. if (this._onAfterCameraRenderObserver) {
  21918. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  21919. }
  21920. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  21921. },
  21922. enumerable: true,
  21923. configurable: true
  21924. });
  21925. Object.defineProperty(Scene.prototype, "gamepadManager", {
  21926. get: function () {
  21927. if (!this._gamepadManager) {
  21928. this._gamepadManager = new BABYLON.GamepadManager(this);
  21929. }
  21930. return this._gamepadManager;
  21931. },
  21932. enumerable: true,
  21933. configurable: true
  21934. });
  21935. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  21936. get: function () {
  21937. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  21938. },
  21939. enumerable: true,
  21940. configurable: true
  21941. });
  21942. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  21943. get: function () {
  21944. return this._useRightHandedSystem;
  21945. },
  21946. set: function (value) {
  21947. if (this._useRightHandedSystem === value) {
  21948. return;
  21949. }
  21950. this._useRightHandedSystem = value;
  21951. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  21952. },
  21953. enumerable: true,
  21954. configurable: true
  21955. });
  21956. Scene.prototype.setStepId = function (newStepId) {
  21957. this._currentStepId = newStepId;
  21958. };
  21959. ;
  21960. Scene.prototype.getStepId = function () {
  21961. return this._currentStepId;
  21962. };
  21963. ;
  21964. Scene.prototype.getInternalStep = function () {
  21965. return this._currentInternalStep;
  21966. };
  21967. ;
  21968. Object.defineProperty(Scene.prototype, "fogEnabled", {
  21969. get: function () {
  21970. return this._fogEnabled;
  21971. },
  21972. /**
  21973. * is fog enabled on this scene.
  21974. */
  21975. set: function (value) {
  21976. if (this._fogEnabled === value) {
  21977. return;
  21978. }
  21979. this._fogEnabled = value;
  21980. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  21981. },
  21982. enumerable: true,
  21983. configurable: true
  21984. });
  21985. Object.defineProperty(Scene.prototype, "fogMode", {
  21986. get: function () {
  21987. return this._fogMode;
  21988. },
  21989. set: function (value) {
  21990. if (this._fogMode === value) {
  21991. return;
  21992. }
  21993. this._fogMode = value;
  21994. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  21995. },
  21996. enumerable: true,
  21997. configurable: true
  21998. });
  21999. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  22000. get: function () {
  22001. return this._shadowsEnabled;
  22002. },
  22003. set: function (value) {
  22004. if (this._shadowsEnabled === value) {
  22005. return;
  22006. }
  22007. this._shadowsEnabled = value;
  22008. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  22009. },
  22010. enumerable: true,
  22011. configurable: true
  22012. });
  22013. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  22014. get: function () {
  22015. return this._lightsEnabled;
  22016. },
  22017. set: function (value) {
  22018. if (this._lightsEnabled === value) {
  22019. return;
  22020. }
  22021. this._lightsEnabled = value;
  22022. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  22023. },
  22024. enumerable: true,
  22025. configurable: true
  22026. });
  22027. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  22028. /** The default material used on meshes when no material is affected */
  22029. get: function () {
  22030. if (!this._defaultMaterial) {
  22031. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  22032. }
  22033. return this._defaultMaterial;
  22034. },
  22035. /** The default material used on meshes when no material is affected */
  22036. set: function (value) {
  22037. this._defaultMaterial = value;
  22038. },
  22039. enumerable: true,
  22040. configurable: true
  22041. });
  22042. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  22043. get: function () {
  22044. return this._texturesEnabled;
  22045. },
  22046. set: function (value) {
  22047. if (this._texturesEnabled === value) {
  22048. return;
  22049. }
  22050. this._texturesEnabled = value;
  22051. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  22052. },
  22053. enumerable: true,
  22054. configurable: true
  22055. });
  22056. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  22057. get: function () {
  22058. return this._skeletonsEnabled;
  22059. },
  22060. set: function (value) {
  22061. if (this._skeletonsEnabled === value) {
  22062. return;
  22063. }
  22064. this._skeletonsEnabled = value;
  22065. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  22066. },
  22067. enumerable: true,
  22068. configurable: true
  22069. });
  22070. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  22071. get: function () {
  22072. if (!this._postProcessRenderPipelineManager) {
  22073. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  22074. }
  22075. return this._postProcessRenderPipelineManager;
  22076. },
  22077. enumerable: true,
  22078. configurable: true
  22079. });
  22080. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  22081. get: function () {
  22082. if (!this._mainSoundTrack) {
  22083. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  22084. }
  22085. return this._mainSoundTrack;
  22086. },
  22087. enumerable: true,
  22088. configurable: true
  22089. });
  22090. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  22091. get: function () {
  22092. return this._alternateRendering;
  22093. },
  22094. enumerable: true,
  22095. configurable: true
  22096. });
  22097. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  22098. get: function () {
  22099. return this._frustumPlanes;
  22100. },
  22101. enumerable: true,
  22102. configurable: true
  22103. });
  22104. Object.defineProperty(Scene.prototype, "geometryBufferRenderer", {
  22105. /**
  22106. * Gets the current geometry buffer associated to the scene.
  22107. */
  22108. get: function () {
  22109. return this._geometryBufferRenderer;
  22110. },
  22111. /**
  22112. * Sets the current geometry buffer for the scene.
  22113. */
  22114. set: function (geometryBufferRenderer) {
  22115. if (geometryBufferRenderer && geometryBufferRenderer.isSupported) {
  22116. this._geometryBufferRenderer = geometryBufferRenderer;
  22117. }
  22118. },
  22119. enumerable: true,
  22120. configurable: true
  22121. });
  22122. Object.defineProperty(Scene.prototype, "debugLayer", {
  22123. // Properties
  22124. get: function () {
  22125. if (!this._debugLayer) {
  22126. this._debugLayer = new BABYLON.DebugLayer(this);
  22127. }
  22128. return this._debugLayer;
  22129. },
  22130. enumerable: true,
  22131. configurable: true
  22132. });
  22133. Object.defineProperty(Scene.prototype, "workerCollisions", {
  22134. get: function () {
  22135. return this._workerCollisions;
  22136. },
  22137. set: function (enabled) {
  22138. if (!BABYLON.CollisionCoordinatorLegacy) {
  22139. return;
  22140. }
  22141. enabled = (enabled && !!Worker && !!BABYLON.CollisionWorker);
  22142. this._workerCollisions = enabled;
  22143. if (this.collisionCoordinator) {
  22144. this.collisionCoordinator.destroy();
  22145. }
  22146. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  22147. this.collisionCoordinator.init(this);
  22148. },
  22149. enumerable: true,
  22150. configurable: true
  22151. });
  22152. Object.defineProperty(Scene.prototype, "selectionOctree", {
  22153. get: function () {
  22154. return this._selectionOctree;
  22155. },
  22156. enumerable: true,
  22157. configurable: true
  22158. });
  22159. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  22160. /**
  22161. * The mesh that is currently under the pointer.
  22162. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  22163. */
  22164. get: function () {
  22165. return this._pointerOverMesh;
  22166. },
  22167. enumerable: true,
  22168. configurable: true
  22169. });
  22170. Object.defineProperty(Scene.prototype, "pointerX", {
  22171. /**
  22172. * Current on-screen X position of the pointer
  22173. * @return {number} X position of the pointer
  22174. */
  22175. get: function () {
  22176. return this._pointerX;
  22177. },
  22178. enumerable: true,
  22179. configurable: true
  22180. });
  22181. Object.defineProperty(Scene.prototype, "pointerY", {
  22182. /**
  22183. * Current on-screen Y position of the pointer
  22184. * @return {number} Y position of the pointer
  22185. */
  22186. get: function () {
  22187. return this._pointerY;
  22188. },
  22189. enumerable: true,
  22190. configurable: true
  22191. });
  22192. Scene.prototype.getCachedMaterial = function () {
  22193. return this._cachedMaterial;
  22194. };
  22195. Scene.prototype.getCachedEffect = function () {
  22196. return this._cachedEffect;
  22197. };
  22198. Scene.prototype.getCachedVisibility = function () {
  22199. return this._cachedVisibility;
  22200. };
  22201. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  22202. if (visibility === void 0) { visibility = 1; }
  22203. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  22204. };
  22205. Scene.prototype.getBoundingBoxRenderer = function () {
  22206. if (!this._boundingBoxRenderer) {
  22207. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  22208. }
  22209. return this._boundingBoxRenderer;
  22210. };
  22211. Scene.prototype.getOutlineRenderer = function () {
  22212. return this._outlineRenderer;
  22213. };
  22214. Scene.prototype.getEngine = function () {
  22215. return this._engine;
  22216. };
  22217. Scene.prototype.getTotalVertices = function () {
  22218. return this._totalVertices.current;
  22219. };
  22220. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  22221. get: function () {
  22222. return this._totalVertices;
  22223. },
  22224. enumerable: true,
  22225. configurable: true
  22226. });
  22227. Scene.prototype.getActiveIndices = function () {
  22228. return this._activeIndices.current;
  22229. };
  22230. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  22231. get: function () {
  22232. return this._activeIndices;
  22233. },
  22234. enumerable: true,
  22235. configurable: true
  22236. });
  22237. Scene.prototype.getActiveParticles = function () {
  22238. return this._activeParticles.current;
  22239. };
  22240. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  22241. get: function () {
  22242. return this._activeParticles;
  22243. },
  22244. enumerable: true,
  22245. configurable: true
  22246. });
  22247. Scene.prototype.getActiveBones = function () {
  22248. return this._activeBones.current;
  22249. };
  22250. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  22251. get: function () {
  22252. return this._activeBones;
  22253. },
  22254. enumerable: true,
  22255. configurable: true
  22256. });
  22257. // Stats
  22258. Scene.prototype.getInterFramePerfCounter = function () {
  22259. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  22260. return 0;
  22261. };
  22262. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  22263. get: function () {
  22264. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  22265. return null;
  22266. },
  22267. enumerable: true,
  22268. configurable: true
  22269. });
  22270. Scene.prototype.getLastFrameDuration = function () {
  22271. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  22272. return 0;
  22273. };
  22274. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  22275. get: function () {
  22276. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  22277. return null;
  22278. },
  22279. enumerable: true,
  22280. configurable: true
  22281. });
  22282. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  22283. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  22284. return 0;
  22285. };
  22286. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  22287. get: function () {
  22288. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  22289. return null;
  22290. },
  22291. enumerable: true,
  22292. configurable: true
  22293. });
  22294. Scene.prototype.getActiveMeshes = function () {
  22295. return this._activeMeshes;
  22296. };
  22297. Scene.prototype.getRenderTargetsDuration = function () {
  22298. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  22299. return 0;
  22300. };
  22301. Scene.prototype.getRenderDuration = function () {
  22302. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  22303. return 0;
  22304. };
  22305. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  22306. get: function () {
  22307. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  22308. return null;
  22309. },
  22310. enumerable: true,
  22311. configurable: true
  22312. });
  22313. Scene.prototype.getParticlesDuration = function () {
  22314. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  22315. return 0;
  22316. };
  22317. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  22318. get: function () {
  22319. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  22320. return null;
  22321. },
  22322. enumerable: true,
  22323. configurable: true
  22324. });
  22325. Scene.prototype.getSpritesDuration = function () {
  22326. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  22327. return 0;
  22328. };
  22329. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  22330. get: function () {
  22331. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  22332. return null;
  22333. },
  22334. enumerable: true,
  22335. configurable: true
  22336. });
  22337. Scene.prototype.getAnimationRatio = function () {
  22338. return this._animationRatio;
  22339. };
  22340. Scene.prototype.getRenderId = function () {
  22341. return this._renderId;
  22342. };
  22343. Scene.prototype.incrementRenderId = function () {
  22344. this._renderId++;
  22345. };
  22346. Scene.prototype._updatePointerPosition = function (evt) {
  22347. var canvasRect = this._engine.getRenderingCanvasClientRect();
  22348. if (!canvasRect) {
  22349. return;
  22350. }
  22351. this._pointerX = evt.clientX - canvasRect.left;
  22352. this._pointerY = evt.clientY - canvasRect.top;
  22353. this._unTranslatedPointerX = this._pointerX;
  22354. this._unTranslatedPointerY = this._pointerY;
  22355. };
  22356. Scene.prototype._createUbo = function () {
  22357. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  22358. this._sceneUbo.addUniform("viewProjection", 16);
  22359. this._sceneUbo.addUniform("view", 16);
  22360. };
  22361. Scene.prototype._createAlternateUbo = function () {
  22362. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  22363. this._alternateSceneUbo.addUniform("viewProjection", 16);
  22364. this._alternateSceneUbo.addUniform("view", 16);
  22365. };
  22366. // Pointers handling
  22367. /**
  22368. * Use this method to simulate a pointer move on a mesh
  22369. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  22370. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  22371. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  22372. */
  22373. Scene.prototype.simulatePointerMove = function (pickResult, pointerEventInit) {
  22374. var evt = new PointerEvent("pointermove", pointerEventInit);
  22375. return this._processPointerMove(pickResult, evt);
  22376. };
  22377. Scene.prototype._processPointerMove = function (pickResult, evt) {
  22378. var canvas = this._engine.getRenderingCanvas();
  22379. if (!canvas) {
  22380. return this;
  22381. }
  22382. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  22383. this.setPointerOverSprite(null);
  22384. this.setPointerOverMesh(pickResult.pickedMesh);
  22385. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  22386. if (this._pointerOverMesh.actionManager.hoverCursor) {
  22387. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  22388. }
  22389. else {
  22390. canvas.style.cursor = this.hoverCursor;
  22391. }
  22392. }
  22393. else {
  22394. canvas.style.cursor = this.defaultCursor;
  22395. }
  22396. }
  22397. else {
  22398. this.setPointerOverMesh(null);
  22399. // Sprites
  22400. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  22401. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  22402. this.setPointerOverSprite(pickResult.pickedSprite);
  22403. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  22404. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  22405. }
  22406. else {
  22407. canvas.style.cursor = this.hoverCursor;
  22408. }
  22409. }
  22410. else {
  22411. this.setPointerOverSprite(null);
  22412. // Restore pointer
  22413. canvas.style.cursor = this.defaultCursor;
  22414. }
  22415. }
  22416. if (pickResult) {
  22417. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  22418. if (this.onPointerMove) {
  22419. this.onPointerMove(evt, pickResult, type);
  22420. }
  22421. if (this.onPointerObservable.hasObservers()) {
  22422. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22423. this.onPointerObservable.notifyObservers(pi, type);
  22424. }
  22425. }
  22426. return this;
  22427. };
  22428. /**
  22429. * Use this method to simulate a pointer down on a mesh
  22430. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  22431. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  22432. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  22433. */
  22434. Scene.prototype.simulatePointerDown = function (pickResult, pointerEventInit) {
  22435. var evt = new PointerEvent("pointerdown", pointerEventInit);
  22436. return this._processPointerDown(pickResult, evt);
  22437. };
  22438. Scene.prototype._processPointerDown = function (pickResult, evt) {
  22439. var _this = this;
  22440. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  22441. this._pickedDownMesh = pickResult.pickedMesh;
  22442. var actionManager = pickResult.pickedMesh.actionManager;
  22443. if (actionManager) {
  22444. if (actionManager.hasPickTriggers) {
  22445. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22446. switch (evt.button) {
  22447. case 0:
  22448. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22449. break;
  22450. case 1:
  22451. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22452. break;
  22453. case 2:
  22454. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22455. break;
  22456. }
  22457. }
  22458. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  22459. window.setTimeout(function () {
  22460. 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);
  22461. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  22462. if (_this._totalPointersPressed !== 0 &&
  22463. ((new Date().getTime() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  22464. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  22465. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  22466. _this._startingPointerTime = 0;
  22467. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22468. }
  22469. }
  22470. }, Scene.LongPressDelay);
  22471. }
  22472. }
  22473. }
  22474. if (pickResult) {
  22475. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  22476. if (this.onPointerDown) {
  22477. this.onPointerDown(evt, pickResult, type);
  22478. }
  22479. if (this.onPointerObservable.hasObservers()) {
  22480. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22481. this.onPointerObservable.notifyObservers(pi, type);
  22482. }
  22483. }
  22484. return this;
  22485. };
  22486. /**
  22487. * Use this method to simulate a pointer up on a mesh
  22488. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  22489. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  22490. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  22491. */
  22492. Scene.prototype.simulatePointerUp = function (pickResult, pointerEventInit) {
  22493. var evt = new PointerEvent("pointerup", pointerEventInit);
  22494. var clickInfo = new ClickInfo();
  22495. clickInfo.singleClick = true;
  22496. clickInfo.ignore = true;
  22497. return this._processPointerUp(pickResult, evt, clickInfo);
  22498. };
  22499. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  22500. if (pickResult && pickResult && pickResult.pickedMesh) {
  22501. this._pickedUpMesh = pickResult.pickedMesh;
  22502. if (this._pickedDownMesh === this._pickedUpMesh) {
  22503. if (this.onPointerPick) {
  22504. this.onPointerPick(evt, pickResult);
  22505. }
  22506. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  22507. var type_1 = BABYLON.PointerEventTypes.POINTERPICK;
  22508. var pi = new BABYLON.PointerInfo(type_1, evt, pickResult);
  22509. this.onPointerObservable.notifyObservers(pi, type_1);
  22510. }
  22511. }
  22512. if (pickResult.pickedMesh.actionManager) {
  22513. if (clickInfo.ignore) {
  22514. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22515. }
  22516. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  22517. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22518. }
  22519. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  22520. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22521. }
  22522. }
  22523. }
  22524. if (this._pickedDownMesh &&
  22525. this._pickedDownMesh.actionManager &&
  22526. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  22527. this._pickedDownMesh !== this._pickedUpMesh) {
  22528. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  22529. }
  22530. var type = BABYLON.PointerEventTypes.POINTERUP;
  22531. if (this.onPointerObservable.hasObservers()) {
  22532. if (!clickInfo.ignore) {
  22533. if (!clickInfo.hasSwiped) {
  22534. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  22535. var type_2 = BABYLON.PointerEventTypes.POINTERTAP;
  22536. var pi = new BABYLON.PointerInfo(type_2, evt, pickResult);
  22537. this.onPointerObservable.notifyObservers(pi, type_2);
  22538. }
  22539. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  22540. var type_3 = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  22541. var pi = new BABYLON.PointerInfo(type_3, evt, pickResult);
  22542. this.onPointerObservable.notifyObservers(pi, type_3);
  22543. }
  22544. }
  22545. }
  22546. else {
  22547. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22548. this.onPointerObservable.notifyObservers(pi, type);
  22549. }
  22550. }
  22551. if (this.onPointerUp) {
  22552. this.onPointerUp(evt, pickResult, type);
  22553. }
  22554. return this;
  22555. };
  22556. /**
  22557. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  22558. * @param attachUp defines if you want to attach events to pointerup
  22559. * @param attachDown defines if you want to attach events to pointerdown
  22560. * @param attachMove defines if you want to attach events to pointermove
  22561. */
  22562. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  22563. var _this = this;
  22564. if (attachUp === void 0) { attachUp = true; }
  22565. if (attachDown === void 0) { attachDown = true; }
  22566. if (attachMove === void 0) { attachMove = true; }
  22567. this._initActionManager = function (act, clickInfo) {
  22568. if (!_this._meshPickProceed) {
  22569. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  22570. _this._currentPickResult = pickResult;
  22571. if (pickResult) {
  22572. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  22573. }
  22574. _this._meshPickProceed = true;
  22575. }
  22576. return act;
  22577. };
  22578. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  22579. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  22580. if ((new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  22581. btn !== _this._previousButtonPressed) {
  22582. _this._doubleClickOccured = false;
  22583. clickInfo.singleClick = true;
  22584. clickInfo.ignore = false;
  22585. cb(clickInfo, _this._currentPickResult);
  22586. }
  22587. };
  22588. this._initClickEvent = function (obs1, obs2, evt, cb) {
  22589. var clickInfo = new ClickInfo();
  22590. _this._currentPickResult = null;
  22591. var act = null;
  22592. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  22593. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  22594. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  22595. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  22596. act = _this._initActionManager(act, clickInfo);
  22597. if (act)
  22598. checkPicking = act.hasPickTriggers;
  22599. }
  22600. if (checkPicking) {
  22601. var btn = evt.button;
  22602. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  22603. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  22604. if (!clickInfo.hasSwiped) {
  22605. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  22606. if (!checkSingleClickImmediately) {
  22607. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  22608. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  22609. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  22610. act = _this._initActionManager(act, clickInfo);
  22611. if (act)
  22612. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  22613. }
  22614. }
  22615. if (checkSingleClickImmediately) {
  22616. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  22617. if (new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  22618. btn !== _this._previousButtonPressed) {
  22619. clickInfo.singleClick = true;
  22620. cb(clickInfo, _this._currentPickResult);
  22621. }
  22622. }
  22623. else {
  22624. // wait that no double click has been raised during the double click delay
  22625. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  22626. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  22627. }
  22628. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  22629. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  22630. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  22631. act = _this._initActionManager(act, clickInfo);
  22632. if (act)
  22633. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  22634. }
  22635. if (checkDoubleClick) {
  22636. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  22637. if (btn === _this._previousButtonPressed &&
  22638. new Date().getTime() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  22639. !_this._doubleClickOccured) {
  22640. // pointer has not moved for 2 clicks, it's a double click
  22641. if (!clickInfo.hasSwiped &&
  22642. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  22643. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  22644. _this._previousStartingPointerTime = 0;
  22645. _this._doubleClickOccured = true;
  22646. clickInfo.doubleClick = true;
  22647. clickInfo.ignore = false;
  22648. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  22649. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  22650. }
  22651. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  22652. cb(clickInfo, _this._currentPickResult);
  22653. }
  22654. else {
  22655. _this._doubleClickOccured = false;
  22656. _this._previousStartingPointerTime = _this._startingPointerTime;
  22657. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  22658. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  22659. _this._previousButtonPressed = btn;
  22660. if (Scene.ExclusiveDoubleClickMode) {
  22661. if (_this._previousDelayedSimpleClickTimeout) {
  22662. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  22663. }
  22664. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  22665. cb(clickInfo, _this._previousPickResult);
  22666. }
  22667. else {
  22668. cb(clickInfo, _this._currentPickResult);
  22669. }
  22670. }
  22671. }
  22672. else {
  22673. _this._doubleClickOccured = false;
  22674. _this._previousStartingPointerTime = _this._startingPointerTime;
  22675. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  22676. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  22677. _this._previousButtonPressed = btn;
  22678. }
  22679. }
  22680. }
  22681. }
  22682. clickInfo.ignore = true;
  22683. cb(clickInfo, _this._currentPickResult);
  22684. };
  22685. this._spritePredicate = function (sprite) {
  22686. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  22687. };
  22688. this._onPointerMove = function (evt) {
  22689. _this._updatePointerPosition(evt);
  22690. // PreObservable support
  22691. if (_this.onPrePointerObservable.hasObservers()) {
  22692. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  22693. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22694. _this.onPrePointerObservable.notifyObservers(pi, type);
  22695. if (pi.skipOnPointerObservable) {
  22696. return;
  22697. }
  22698. }
  22699. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  22700. return;
  22701. }
  22702. if (!_this.pointerMovePredicate) {
  22703. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  22704. }
  22705. // Meshes
  22706. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  22707. _this._processPointerMove(pickResult, evt);
  22708. };
  22709. this._onPointerDown = function (evt) {
  22710. _this._totalPointersPressed++;
  22711. _this._pickedDownMesh = null;
  22712. _this._meshPickProceed = false;
  22713. _this._updatePointerPosition(evt);
  22714. if (_this.preventDefaultOnPointerDown && canvas) {
  22715. evt.preventDefault();
  22716. canvas.focus();
  22717. }
  22718. // PreObservable support
  22719. if (_this.onPrePointerObservable.hasObservers()) {
  22720. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  22721. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22722. _this.onPrePointerObservable.notifyObservers(pi, type);
  22723. if (pi.skipOnPointerObservable) {
  22724. return;
  22725. }
  22726. }
  22727. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  22728. return;
  22729. }
  22730. _this._startingPointerPosition.x = _this._pointerX;
  22731. _this._startingPointerPosition.y = _this._pointerY;
  22732. _this._startingPointerTime = new Date().getTime();
  22733. if (!_this.pointerDownPredicate) {
  22734. _this.pointerDownPredicate = function (mesh) {
  22735. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  22736. };
  22737. }
  22738. // Meshes
  22739. _this._pickedDownMesh = null;
  22740. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  22741. _this._processPointerDown(pickResult, evt);
  22742. // Sprites
  22743. _this._pickedDownSprite = null;
  22744. if (_this.spriteManagers.length > 0) {
  22745. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  22746. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  22747. if (pickResult.pickedSprite.actionManager) {
  22748. _this._pickedDownSprite = pickResult.pickedSprite;
  22749. switch (evt.button) {
  22750. case 0:
  22751. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22752. break;
  22753. case 1:
  22754. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22755. break;
  22756. case 2:
  22757. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22758. break;
  22759. }
  22760. if (pickResult.pickedSprite.actionManager) {
  22761. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22762. }
  22763. }
  22764. }
  22765. }
  22766. };
  22767. this._onPointerUp = function (evt) {
  22768. if (_this._totalPointersPressed === 0) {
  22769. return; // So we need to test it the pointer down was pressed before.
  22770. }
  22771. _this._totalPointersPressed--;
  22772. _this._pickedUpMesh = null;
  22773. _this._meshPickProceed = false;
  22774. _this._updatePointerPosition(evt);
  22775. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  22776. // PreObservable support
  22777. if (_this.onPrePointerObservable.hasObservers()) {
  22778. if (!clickInfo.ignore) {
  22779. if (!clickInfo.hasSwiped) {
  22780. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  22781. var type = BABYLON.PointerEventTypes.POINTERTAP;
  22782. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22783. _this.onPrePointerObservable.notifyObservers(pi, type);
  22784. if (pi.skipOnPointerObservable) {
  22785. return;
  22786. }
  22787. }
  22788. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  22789. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  22790. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22791. _this.onPrePointerObservable.notifyObservers(pi, type);
  22792. if (pi.skipOnPointerObservable) {
  22793. return;
  22794. }
  22795. }
  22796. }
  22797. }
  22798. else {
  22799. var type = BABYLON.PointerEventTypes.POINTERUP;
  22800. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22801. _this.onPrePointerObservable.notifyObservers(pi, type);
  22802. if (pi.skipOnPointerObservable) {
  22803. return;
  22804. }
  22805. }
  22806. }
  22807. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  22808. return;
  22809. }
  22810. if (!_this.pointerUpPredicate) {
  22811. _this.pointerUpPredicate = function (mesh) {
  22812. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  22813. };
  22814. }
  22815. // Meshes
  22816. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  22817. _this._initActionManager(null, clickInfo);
  22818. }
  22819. if (!pickResult) {
  22820. pickResult = _this._currentPickResult;
  22821. }
  22822. _this._processPointerUp(pickResult, evt, clickInfo);
  22823. // Sprites
  22824. if (_this.spriteManagers.length > 0) {
  22825. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  22826. if (spritePickResult) {
  22827. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  22828. if (spritePickResult.pickedSprite.actionManager) {
  22829. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  22830. if (spritePickResult.pickedSprite.actionManager) {
  22831. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  22832. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  22833. }
  22834. }
  22835. }
  22836. }
  22837. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  22838. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  22839. }
  22840. }
  22841. }
  22842. _this._previousPickResult = _this._currentPickResult;
  22843. });
  22844. };
  22845. this._onKeyDown = function (evt) {
  22846. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  22847. if (_this.onPreKeyboardObservable.hasObservers()) {
  22848. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  22849. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  22850. if (pi.skipOnPointerObservable) {
  22851. return;
  22852. }
  22853. }
  22854. if (_this.onKeyboardObservable.hasObservers()) {
  22855. var pi = new BABYLON.KeyboardInfo(type, evt);
  22856. _this.onKeyboardObservable.notifyObservers(pi, type);
  22857. }
  22858. if (_this.actionManager) {
  22859. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  22860. }
  22861. };
  22862. this._onKeyUp = function (evt) {
  22863. var type = BABYLON.KeyboardEventTypes.KEYUP;
  22864. if (_this.onPreKeyboardObservable.hasObservers()) {
  22865. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  22866. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  22867. if (pi.skipOnPointerObservable) {
  22868. return;
  22869. }
  22870. }
  22871. if (_this.onKeyboardObservable.hasObservers()) {
  22872. var pi = new BABYLON.KeyboardInfo(type, evt);
  22873. _this.onKeyboardObservable.notifyObservers(pi, type);
  22874. }
  22875. if (_this.actionManager) {
  22876. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  22877. }
  22878. };
  22879. var engine = this.getEngine();
  22880. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  22881. if (!canvas) {
  22882. return;
  22883. }
  22884. canvas.addEventListener("keydown", _this._onKeyDown, false);
  22885. canvas.addEventListener("keyup", _this._onKeyUp, false);
  22886. });
  22887. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  22888. if (!canvas) {
  22889. return;
  22890. }
  22891. canvas.removeEventListener("keydown", _this._onKeyDown);
  22892. canvas.removeEventListener("keyup", _this._onKeyUp);
  22893. });
  22894. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  22895. var canvas = this._engine.getRenderingCanvas();
  22896. if (!canvas) {
  22897. return;
  22898. }
  22899. if (attachMove) {
  22900. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  22901. // Wheel
  22902. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  22903. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  22904. }
  22905. if (attachDown) {
  22906. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  22907. }
  22908. if (attachUp) {
  22909. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  22910. }
  22911. canvas.tabIndex = 1;
  22912. };
  22913. Scene.prototype.detachControl = function () {
  22914. var engine = this.getEngine();
  22915. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  22916. var canvas = engine.getRenderingCanvas();
  22917. if (!canvas) {
  22918. return;
  22919. }
  22920. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  22921. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  22922. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  22923. if (this._onCanvasBlurObserver) {
  22924. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  22925. }
  22926. if (this._onCanvasFocusObserver) {
  22927. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  22928. }
  22929. // Wheel
  22930. canvas.removeEventListener('mousewheel', this._onPointerMove);
  22931. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  22932. // Keyboard
  22933. canvas.removeEventListener("keydown", this._onKeyDown);
  22934. canvas.removeEventListener("keyup", this._onKeyUp);
  22935. // Observables
  22936. this.onKeyboardObservable.clear();
  22937. this.onPreKeyboardObservable.clear();
  22938. this.onPointerObservable.clear();
  22939. this.onPrePointerObservable.clear();
  22940. };
  22941. /**
  22942. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  22943. * Delay loaded resources are not taking in account
  22944. * @return true if all required resources are ready
  22945. */
  22946. Scene.prototype.isReady = function () {
  22947. if (this._isDisposed) {
  22948. return false;
  22949. }
  22950. if (this._pendingData.length > 0) {
  22951. return false;
  22952. }
  22953. var index;
  22954. var engine = this.getEngine();
  22955. // Geometries
  22956. for (index = 0; index < this._geometries.length; index++) {
  22957. var geometry = this._geometries[index];
  22958. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  22959. return false;
  22960. }
  22961. }
  22962. // Meshes
  22963. for (index = 0; index < this.meshes.length; index++) {
  22964. var mesh = this.meshes[index];
  22965. if (!mesh.isEnabled()) {
  22966. continue;
  22967. }
  22968. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  22969. continue;
  22970. }
  22971. if (!mesh.isReady(true)) {
  22972. return false;
  22973. }
  22974. // Effect layers
  22975. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  22976. for (var _i = 0, _a = this.effectLayers; _i < _a.length; _i++) {
  22977. var layer = _a[_i];
  22978. if (!layer.hasMesh(mesh)) {
  22979. continue;
  22980. }
  22981. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  22982. var subMesh = _c[_b];
  22983. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  22984. return false;
  22985. }
  22986. }
  22987. }
  22988. }
  22989. // Particles
  22990. for (var _d = 0, _e = this.particleSystems; _d < _e.length; _d++) {
  22991. var particleSystem = _e[_d];
  22992. if (!particleSystem.isReady()) {
  22993. return false;
  22994. }
  22995. }
  22996. return true;
  22997. };
  22998. Scene.prototype.resetCachedMaterial = function () {
  22999. this._cachedMaterial = null;
  23000. this._cachedEffect = null;
  23001. this._cachedVisibility = null;
  23002. };
  23003. Scene.prototype.registerBeforeRender = function (func) {
  23004. this.onBeforeRenderObservable.add(func);
  23005. };
  23006. Scene.prototype.unregisterBeforeRender = function (func) {
  23007. this.onBeforeRenderObservable.removeCallback(func);
  23008. };
  23009. Scene.prototype.registerAfterRender = function (func) {
  23010. this.onAfterRenderObservable.add(func);
  23011. };
  23012. Scene.prototype.unregisterAfterRender = function (func) {
  23013. this.onAfterRenderObservable.removeCallback(func);
  23014. };
  23015. Scene.prototype._executeOnceBeforeRender = function (func) {
  23016. var _this = this;
  23017. var execFunc = function () {
  23018. func();
  23019. setTimeout(function () {
  23020. _this.unregisterBeforeRender(execFunc);
  23021. });
  23022. };
  23023. this.registerBeforeRender(execFunc);
  23024. };
  23025. /**
  23026. * The provided function will run before render once and will be disposed afterwards.
  23027. * A timeout delay can be provided so that the function will be executed in N ms.
  23028. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  23029. * @param func The function to be executed.
  23030. * @param timeout optional delay in ms
  23031. */
  23032. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  23033. var _this = this;
  23034. if (timeout !== undefined) {
  23035. setTimeout(function () {
  23036. _this._executeOnceBeforeRender(func);
  23037. }, timeout);
  23038. }
  23039. else {
  23040. this._executeOnceBeforeRender(func);
  23041. }
  23042. };
  23043. Scene.prototype._addPendingData = function (data) {
  23044. this._pendingData.push(data);
  23045. };
  23046. Scene.prototype._removePendingData = function (data) {
  23047. var wasLoading = this.isLoading;
  23048. var index = this._pendingData.indexOf(data);
  23049. if (index !== -1) {
  23050. this._pendingData.splice(index, 1);
  23051. }
  23052. if (wasLoading && !this.isLoading) {
  23053. this.onDataLoadedObservable.notifyObservers(this);
  23054. }
  23055. };
  23056. Scene.prototype.getWaitingItemsCount = function () {
  23057. return this._pendingData.length;
  23058. };
  23059. Object.defineProperty(Scene.prototype, "isLoading", {
  23060. get: function () {
  23061. return this._pendingData.length > 0;
  23062. },
  23063. enumerable: true,
  23064. configurable: true
  23065. });
  23066. /**
  23067. * Registers a function to be executed when the scene is ready.
  23068. * @param {Function} func - the function to be executed.
  23069. */
  23070. Scene.prototype.executeWhenReady = function (func) {
  23071. var _this = this;
  23072. this.onReadyObservable.add(func);
  23073. if (this._executeWhenReadyTimeoutId !== -1) {
  23074. return;
  23075. }
  23076. this._executeWhenReadyTimeoutId = setTimeout(function () {
  23077. _this._checkIsReady();
  23078. }, 150);
  23079. };
  23080. /**
  23081. * Returns a promise that resolves when the scene is ready.
  23082. * @returns A promise that resolves when the scene is ready.
  23083. */
  23084. Scene.prototype.whenReadyAsync = function () {
  23085. var _this = this;
  23086. return new Promise(function (resolve) {
  23087. _this.executeWhenReady(function () {
  23088. resolve();
  23089. });
  23090. });
  23091. };
  23092. Scene.prototype._checkIsReady = function () {
  23093. var _this = this;
  23094. if (this.isReady()) {
  23095. this.onReadyObservable.notifyObservers(this);
  23096. this.onReadyObservable.clear();
  23097. this._executeWhenReadyTimeoutId = -1;
  23098. return;
  23099. }
  23100. this._executeWhenReadyTimeoutId = setTimeout(function () {
  23101. _this._checkIsReady();
  23102. }, 150);
  23103. };
  23104. // Animations
  23105. /**
  23106. * Will start the animation sequence of a given target
  23107. * @param target - the target
  23108. * @param {number} from - from which frame should animation start
  23109. * @param {number} to - till which frame should animation run.
  23110. * @param {boolean} [loop] - should the animation loop
  23111. * @param {number} [speedRatio] - the speed in which to run the animation
  23112. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  23113. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  23114. * Returns {BABYLON.Animatable} the animatable object created for this animation
  23115. * See BABYLON.Animatable
  23116. */
  23117. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  23118. if (speedRatio === void 0) { speedRatio = 1.0; }
  23119. if (from > to && speedRatio > 0) {
  23120. speedRatio *= -1;
  23121. }
  23122. this.stopAnimation(target);
  23123. if (!animatable) {
  23124. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  23125. }
  23126. // Local animations
  23127. if (target.animations) {
  23128. animatable.appendAnimations(target, target.animations);
  23129. }
  23130. // Children animations
  23131. if (target.getAnimatables) {
  23132. var animatables = target.getAnimatables();
  23133. for (var index = 0; index < animatables.length; index++) {
  23134. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  23135. }
  23136. }
  23137. animatable.reset();
  23138. return animatable;
  23139. };
  23140. /**
  23141. * Begin a new animation on a given node
  23142. * @param {BABYLON.Node} node defines the root node where the animation will take place
  23143. * @param {BABYLON.Animation[]} defines the list of animations to start
  23144. * @param {number} from defines the initial value
  23145. * @param {number} to defines the final value
  23146. * @param {boolean} loop defines if you want animation to loop (off by default)
  23147. * @param {number} speedRatio defines the speed ratio to apply to all animations
  23148. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  23149. * @returns the list of created animatables
  23150. */
  23151. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  23152. if (speedRatio === undefined) {
  23153. speedRatio = 1.0;
  23154. }
  23155. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  23156. return animatable;
  23157. };
  23158. /**
  23159. * Begin a new animation on a given node and its hierarchy
  23160. * @param {BABYLON.Node} node defines the root node where the animation will take place
  23161. * @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.
  23162. * @param {BABYLON.Animation[]} defines the list of animations to start
  23163. * @param {number} from defines the initial value
  23164. * @param {number} to defines the final value
  23165. * @param {boolean} loop defines if you want animation to loop (off by default)
  23166. * @param {number} speedRatio defines the speed ratio to apply to all animations
  23167. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  23168. * @returns the list of animatables created for all nodes
  23169. */
  23170. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  23171. var children = target.getDescendants(directDescendantsOnly);
  23172. var result = [];
  23173. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  23174. var child = children_1[_i];
  23175. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  23176. }
  23177. return result;
  23178. };
  23179. Scene.prototype.getAnimatableByTarget = function (target) {
  23180. for (var index = 0; index < this._activeAnimatables.length; index++) {
  23181. if (this._activeAnimatables[index].target === target) {
  23182. return this._activeAnimatables[index];
  23183. }
  23184. }
  23185. return null;
  23186. };
  23187. Object.defineProperty(Scene.prototype, "animatables", {
  23188. get: function () {
  23189. return this._activeAnimatables;
  23190. },
  23191. enumerable: true,
  23192. configurable: true
  23193. });
  23194. /**
  23195. * Will stop the animation of the given target
  23196. * @param target - the target
  23197. * @param animationName - the name of the animation to stop (all animations will be stopped is empty)
  23198. * @see beginAnimation
  23199. */
  23200. Scene.prototype.stopAnimation = function (target, animationName) {
  23201. var animatable = this.getAnimatableByTarget(target);
  23202. if (animatable) {
  23203. animatable.stop(animationName);
  23204. }
  23205. };
  23206. /**
  23207. * Stops and removes all animations that have been applied to the scene
  23208. */
  23209. Scene.prototype.stopAllAnimations = function () {
  23210. if (this._activeAnimatables) {
  23211. for (var i = 0; i < this._activeAnimatables.length; i++) {
  23212. this._activeAnimatables[i].stop();
  23213. }
  23214. this._activeAnimatables = [];
  23215. }
  23216. };
  23217. Scene.prototype._animate = function () {
  23218. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  23219. return;
  23220. }
  23221. // Getting time
  23222. var now = BABYLON.Tools.Now;
  23223. if (!this._animationTimeLast) {
  23224. if (this._pendingData.length > 0) {
  23225. return;
  23226. }
  23227. this._animationTimeLast = now;
  23228. }
  23229. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  23230. this._animationTime += deltaTime;
  23231. this._animationTimeLast = now;
  23232. for (var index = 0; index < this._activeAnimatables.length; index++) {
  23233. this._activeAnimatables[index]._animate(this._animationTime);
  23234. }
  23235. };
  23236. // Matrix
  23237. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  23238. this._useAlternateCameraConfiguration = active;
  23239. };
  23240. Scene.prototype.getViewMatrix = function () {
  23241. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  23242. };
  23243. Scene.prototype.getProjectionMatrix = function () {
  23244. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  23245. };
  23246. Scene.prototype.getTransformMatrix = function () {
  23247. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  23248. };
  23249. Scene.prototype.setTransformMatrix = function (view, projection) {
  23250. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  23251. return;
  23252. }
  23253. this._viewUpdateFlag = view.updateFlag;
  23254. this._projectionUpdateFlag = projection.updateFlag;
  23255. this._viewMatrix = view;
  23256. this._projectionMatrix = projection;
  23257. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  23258. // Update frustum
  23259. if (!this._frustumPlanes) {
  23260. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  23261. }
  23262. else {
  23263. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  23264. }
  23265. if (this.activeCamera && this.activeCamera._alternateCamera) {
  23266. var otherCamera = this.activeCamera._alternateCamera;
  23267. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  23268. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  23269. }
  23270. if (this._sceneUbo.useUbo) {
  23271. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  23272. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  23273. this._sceneUbo.update();
  23274. }
  23275. };
  23276. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  23277. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  23278. return;
  23279. }
  23280. this._alternateViewUpdateFlag = view.updateFlag;
  23281. this._alternateProjectionUpdateFlag = projection.updateFlag;
  23282. this._alternateViewMatrix = view;
  23283. this._alternateProjectionMatrix = projection;
  23284. if (!this._alternateTransformMatrix) {
  23285. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  23286. }
  23287. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  23288. if (!this._alternateSceneUbo) {
  23289. this._createAlternateUbo();
  23290. }
  23291. if (this._alternateSceneUbo.useUbo) {
  23292. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  23293. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  23294. this._alternateSceneUbo.update();
  23295. }
  23296. };
  23297. Scene.prototype.getSceneUniformBuffer = function () {
  23298. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  23299. };
  23300. // Methods
  23301. Scene.prototype.getUniqueId = function () {
  23302. var result = Scene._uniqueIdCounter;
  23303. Scene._uniqueIdCounter++;
  23304. return result;
  23305. };
  23306. Scene.prototype.addMesh = function (newMesh) {
  23307. this.meshes.push(newMesh);
  23308. //notify the collision coordinator
  23309. if (this.collisionCoordinator) {
  23310. this.collisionCoordinator.onMeshAdded(newMesh);
  23311. }
  23312. newMesh._resyncLightSources();
  23313. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  23314. };
  23315. Scene.prototype.removeMesh = function (toRemove) {
  23316. var index = this.meshes.indexOf(toRemove);
  23317. if (index !== -1) {
  23318. // Remove from the scene if mesh found
  23319. this.meshes.splice(index, 1);
  23320. }
  23321. this.onMeshRemovedObservable.notifyObservers(toRemove);
  23322. return index;
  23323. };
  23324. Scene.prototype.addTransformNode = function (newTransformNode) {
  23325. this.transformNodes.push(newTransformNode);
  23326. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  23327. };
  23328. Scene.prototype.removeTransformNode = function (toRemove) {
  23329. var index = this.transformNodes.indexOf(toRemove);
  23330. if (index !== -1) {
  23331. // Remove from the scene if found
  23332. this.transformNodes.splice(index, 1);
  23333. }
  23334. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  23335. return index;
  23336. };
  23337. Scene.prototype.removeSkeleton = function (toRemove) {
  23338. var index = this.skeletons.indexOf(toRemove);
  23339. if (index !== -1) {
  23340. // Remove from the scene if found
  23341. this.skeletons.splice(index, 1);
  23342. }
  23343. return index;
  23344. };
  23345. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  23346. var index = this.morphTargetManagers.indexOf(toRemove);
  23347. if (index !== -1) {
  23348. // Remove from the scene if found
  23349. this.morphTargetManagers.splice(index, 1);
  23350. }
  23351. return index;
  23352. };
  23353. Scene.prototype.removeLight = function (toRemove) {
  23354. var index = this.lights.indexOf(toRemove);
  23355. if (index !== -1) {
  23356. // Remove from meshes
  23357. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  23358. var mesh = _a[_i];
  23359. mesh._removeLightSource(toRemove);
  23360. }
  23361. // Remove from the scene if mesh found
  23362. this.lights.splice(index, 1);
  23363. this.sortLightsByPriority();
  23364. }
  23365. this.onLightRemovedObservable.notifyObservers(toRemove);
  23366. return index;
  23367. };
  23368. Scene.prototype.removeCamera = function (toRemove) {
  23369. var index = this.cameras.indexOf(toRemove);
  23370. if (index !== -1) {
  23371. // Remove from the scene if mesh found
  23372. this.cameras.splice(index, 1);
  23373. }
  23374. // Remove from activeCameras
  23375. var index2 = this.activeCameras.indexOf(toRemove);
  23376. if (index2 !== -1) {
  23377. // Remove from the scene if mesh found
  23378. this.activeCameras.splice(index2, 1);
  23379. }
  23380. // Reset the activeCamera
  23381. if (this.activeCamera === toRemove) {
  23382. if (this.cameras.length > 0) {
  23383. this.activeCamera = this.cameras[0];
  23384. }
  23385. else {
  23386. this.activeCamera = null;
  23387. }
  23388. }
  23389. this.onCameraRemovedObservable.notifyObservers(toRemove);
  23390. return index;
  23391. };
  23392. Scene.prototype.removeParticleSystem = function (toRemove) {
  23393. var index = this.particleSystems.indexOf(toRemove);
  23394. if (index !== -1) {
  23395. this.particleSystems.splice(index, 1);
  23396. }
  23397. return index;
  23398. };
  23399. ;
  23400. Scene.prototype.removeAnimation = function (toRemove) {
  23401. var index = this.animations.indexOf(toRemove);
  23402. if (index !== -1) {
  23403. this.animations.splice(index, 1);
  23404. }
  23405. return index;
  23406. };
  23407. ;
  23408. Scene.prototype.removeMultiMaterial = function (toRemove) {
  23409. var index = this.multiMaterials.indexOf(toRemove);
  23410. if (index !== -1) {
  23411. this.multiMaterials.splice(index, 1);
  23412. }
  23413. return index;
  23414. };
  23415. ;
  23416. Scene.prototype.removeMaterial = function (toRemove) {
  23417. var index = this.materials.indexOf(toRemove);
  23418. if (index !== -1) {
  23419. this.materials.splice(index, 1);
  23420. }
  23421. return index;
  23422. };
  23423. ;
  23424. Scene.prototype.removeLensFlareSystem = function (toRemove) {
  23425. var index = this.lensFlareSystems.indexOf(toRemove);
  23426. if (index !== -1) {
  23427. this.lensFlareSystems.splice(index, 1);
  23428. }
  23429. return index;
  23430. };
  23431. ;
  23432. Scene.prototype.removeActionManager = function (toRemove) {
  23433. var index = this._actionManagers.indexOf(toRemove);
  23434. if (index !== -1) {
  23435. this._actionManagers.splice(index, 1);
  23436. }
  23437. return index;
  23438. };
  23439. ;
  23440. Scene.prototype.addLight = function (newLight) {
  23441. this.lights.push(newLight);
  23442. this.sortLightsByPriority();
  23443. // Add light to all meshes (To support if the light is removed and then readded)
  23444. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  23445. var mesh = _a[_i];
  23446. if (mesh._lightSources.indexOf(newLight) === -1) {
  23447. mesh._lightSources.push(newLight);
  23448. mesh._resyncLightSources();
  23449. }
  23450. }
  23451. this.onNewLightAddedObservable.notifyObservers(newLight);
  23452. };
  23453. Scene.prototype.sortLightsByPriority = function () {
  23454. if (this.requireLightSorting) {
  23455. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  23456. }
  23457. };
  23458. Scene.prototype.addCamera = function (newCamera) {
  23459. this.cameras.push(newCamera);
  23460. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  23461. };
  23462. Scene.prototype.addSkeleton = function (newSkeleton) {
  23463. this.skeletons.push(newSkeleton);
  23464. };
  23465. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  23466. this.particleSystems.push(newParticleSystem);
  23467. };
  23468. Scene.prototype.addAnimation = function (newAnimation) {
  23469. this.animations.push(newAnimation);
  23470. };
  23471. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  23472. this.multiMaterials.push(newMultiMaterial);
  23473. };
  23474. Scene.prototype.addMaterial = function (newMaterial) {
  23475. this.materials.push(newMaterial);
  23476. };
  23477. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  23478. this.morphTargetManagers.push(newMorphTargetManager);
  23479. };
  23480. Scene.prototype.addGeometry = function (newGeometrie) {
  23481. this._geometries.push(newGeometrie);
  23482. };
  23483. Scene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  23484. this.lensFlareSystems.push(newLensFlareSystem);
  23485. };
  23486. Scene.prototype.addActionManager = function (newActionManager) {
  23487. this._actionManagers.push(newActionManager);
  23488. };
  23489. /**
  23490. * Switch active camera
  23491. * @param {Camera} newCamera - new active camera
  23492. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  23493. */
  23494. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  23495. if (attachControl === void 0) { attachControl = true; }
  23496. var canvas = this._engine.getRenderingCanvas();
  23497. if (!canvas) {
  23498. return;
  23499. }
  23500. if (this.activeCamera) {
  23501. this.activeCamera.detachControl(canvas);
  23502. }
  23503. this.activeCamera = newCamera;
  23504. if (attachControl) {
  23505. newCamera.attachControl(canvas);
  23506. }
  23507. };
  23508. /**
  23509. * sets the active camera of the scene using its ID
  23510. * @param {string} id - the camera's ID
  23511. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  23512. * @see activeCamera
  23513. */
  23514. Scene.prototype.setActiveCameraByID = function (id) {
  23515. var camera = this.getCameraByID(id);
  23516. if (camera) {
  23517. this.activeCamera = camera;
  23518. return camera;
  23519. }
  23520. return null;
  23521. };
  23522. /**
  23523. * sets the active camera of the scene using its name
  23524. * @param {string} name - the camera's name
  23525. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  23526. * @see activeCamera
  23527. */
  23528. Scene.prototype.setActiveCameraByName = function (name) {
  23529. var camera = this.getCameraByName(name);
  23530. if (camera) {
  23531. this.activeCamera = camera;
  23532. return camera;
  23533. }
  23534. return null;
  23535. };
  23536. /**
  23537. * get an animation group using its name
  23538. * @param {string} the material's name
  23539. * @return {BABYLON.AnimationGroup|null} the animation group or null if none found.
  23540. */
  23541. Scene.prototype.getAnimationGroupByName = function (name) {
  23542. for (var index = 0; index < this.animationGroups.length; index++) {
  23543. if (this.animationGroups[index].name === name) {
  23544. return this.animationGroups[index];
  23545. }
  23546. }
  23547. return null;
  23548. };
  23549. /**
  23550. * get a material using its id
  23551. * @param {string} the material's ID
  23552. * @return {BABYLON.Material|null} the material or null if none found.
  23553. */
  23554. Scene.prototype.getMaterialByID = function (id) {
  23555. for (var index = 0; index < this.materials.length; index++) {
  23556. if (this.materials[index].id === id) {
  23557. return this.materials[index];
  23558. }
  23559. }
  23560. return null;
  23561. };
  23562. /**
  23563. * get a material using its name
  23564. * @param {string} the material's name
  23565. * @return {BABYLON.Material|null} the material or null if none found.
  23566. */
  23567. Scene.prototype.getMaterialByName = function (name) {
  23568. for (var index = 0; index < this.materials.length; index++) {
  23569. if (this.materials[index].name === name) {
  23570. return this.materials[index];
  23571. }
  23572. }
  23573. return null;
  23574. };
  23575. Scene.prototype.getLensFlareSystemByName = function (name) {
  23576. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  23577. if (this.lensFlareSystems[index].name === name) {
  23578. return this.lensFlareSystems[index];
  23579. }
  23580. }
  23581. return null;
  23582. };
  23583. Scene.prototype.getLensFlareSystemByID = function (id) {
  23584. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  23585. if (this.lensFlareSystems[index].id === id) {
  23586. return this.lensFlareSystems[index];
  23587. }
  23588. }
  23589. return null;
  23590. };
  23591. Scene.prototype.getCameraByID = function (id) {
  23592. for (var index = 0; index < this.cameras.length; index++) {
  23593. if (this.cameras[index].id === id) {
  23594. return this.cameras[index];
  23595. }
  23596. }
  23597. return null;
  23598. };
  23599. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  23600. for (var index = 0; index < this.cameras.length; index++) {
  23601. if (this.cameras[index].uniqueId === uniqueId) {
  23602. return this.cameras[index];
  23603. }
  23604. }
  23605. return null;
  23606. };
  23607. /**
  23608. * get a camera using its name
  23609. * @param {string} the camera's name
  23610. * @return {BABYLON.Camera|null} the camera or null if none found.
  23611. */
  23612. Scene.prototype.getCameraByName = function (name) {
  23613. for (var index = 0; index < this.cameras.length; index++) {
  23614. if (this.cameras[index].name === name) {
  23615. return this.cameras[index];
  23616. }
  23617. }
  23618. return null;
  23619. };
  23620. /**
  23621. * get a bone using its id
  23622. * @param {string} the bone's id
  23623. * @return {BABYLON.Bone|null} the bone or null if not found
  23624. */
  23625. Scene.prototype.getBoneByID = function (id) {
  23626. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  23627. var skeleton = this.skeletons[skeletonIndex];
  23628. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  23629. if (skeleton.bones[boneIndex].id === id) {
  23630. return skeleton.bones[boneIndex];
  23631. }
  23632. }
  23633. }
  23634. return null;
  23635. };
  23636. /**
  23637. * get a bone using its id
  23638. * @param {string} the bone's name
  23639. * @return {BABYLON.Bone|null} the bone or null if not found
  23640. */
  23641. Scene.prototype.getBoneByName = function (name) {
  23642. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  23643. var skeleton = this.skeletons[skeletonIndex];
  23644. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  23645. if (skeleton.bones[boneIndex].name === name) {
  23646. return skeleton.bones[boneIndex];
  23647. }
  23648. }
  23649. }
  23650. return null;
  23651. };
  23652. /**
  23653. * get a light node using its name
  23654. * @param {string} the light's name
  23655. * @return {BABYLON.Light|null} the light or null if none found.
  23656. */
  23657. Scene.prototype.getLightByName = function (name) {
  23658. for (var index = 0; index < this.lights.length; index++) {
  23659. if (this.lights[index].name === name) {
  23660. return this.lights[index];
  23661. }
  23662. }
  23663. return null;
  23664. };
  23665. /**
  23666. * get a light node using its ID
  23667. * @param {string} the light's id
  23668. * @return {BABYLON.Light|null} the light or null if none found.
  23669. */
  23670. Scene.prototype.getLightByID = function (id) {
  23671. for (var index = 0; index < this.lights.length; index++) {
  23672. if (this.lights[index].id === id) {
  23673. return this.lights[index];
  23674. }
  23675. }
  23676. return null;
  23677. };
  23678. /**
  23679. * get a light node using its scene-generated unique ID
  23680. * @param {number} the light's unique id
  23681. * @return {BABYLON.Light|null} the light or null if none found.
  23682. */
  23683. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  23684. for (var index = 0; index < this.lights.length; index++) {
  23685. if (this.lights[index].uniqueId === uniqueId) {
  23686. return this.lights[index];
  23687. }
  23688. }
  23689. return null;
  23690. };
  23691. /**
  23692. * get a particle system by id
  23693. * @param id {number} the particle system id
  23694. * @return {BABYLON.IParticleSystem|null} the corresponding system or null if none found.
  23695. */
  23696. Scene.prototype.getParticleSystemByID = function (id) {
  23697. for (var index = 0; index < this.particleSystems.length; index++) {
  23698. if (this.particleSystems[index].id === id) {
  23699. return this.particleSystems[index];
  23700. }
  23701. }
  23702. return null;
  23703. };
  23704. /**
  23705. * get a geometry using its ID
  23706. * @param {string} the geometry's id
  23707. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  23708. */
  23709. Scene.prototype.getGeometryByID = function (id) {
  23710. for (var index = 0; index < this._geometries.length; index++) {
  23711. if (this._geometries[index].id === id) {
  23712. return this._geometries[index];
  23713. }
  23714. }
  23715. return null;
  23716. };
  23717. /**
  23718. * add a new geometry to this scene.
  23719. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  23720. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  23721. * @return {boolean} was the geometry added or not
  23722. */
  23723. Scene.prototype.pushGeometry = function (geometry, force) {
  23724. if (!force && this.getGeometryByID(geometry.id)) {
  23725. return false;
  23726. }
  23727. this._geometries.push(geometry);
  23728. //notify the collision coordinator
  23729. if (this.collisionCoordinator) {
  23730. this.collisionCoordinator.onGeometryAdded(geometry);
  23731. }
  23732. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  23733. return true;
  23734. };
  23735. /**
  23736. * Removes an existing geometry
  23737. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  23738. * @return {boolean} was the geometry removed or not
  23739. */
  23740. Scene.prototype.removeGeometry = function (geometry) {
  23741. var index = this._geometries.indexOf(geometry);
  23742. if (index > -1) {
  23743. this._geometries.splice(index, 1);
  23744. //notify the collision coordinator
  23745. if (this.collisionCoordinator) {
  23746. this.collisionCoordinator.onGeometryDeleted(geometry);
  23747. }
  23748. this.onGeometryRemovedObservable.notifyObservers(geometry);
  23749. return true;
  23750. }
  23751. return false;
  23752. };
  23753. Scene.prototype.getGeometries = function () {
  23754. return this._geometries;
  23755. };
  23756. /**
  23757. * Get the first added mesh found of a given ID
  23758. * @param {string} id - the id to search for
  23759. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  23760. */
  23761. Scene.prototype.getMeshByID = function (id) {
  23762. for (var index = 0; index < this.meshes.length; index++) {
  23763. if (this.meshes[index].id === id) {
  23764. return this.meshes[index];
  23765. }
  23766. }
  23767. return null;
  23768. };
  23769. Scene.prototype.getMeshesByID = function (id) {
  23770. return this.meshes.filter(function (m) {
  23771. return m.id === id;
  23772. });
  23773. };
  23774. /**
  23775. * Get the first added transform node found of a given ID
  23776. * @param {string} id - the id to search for
  23777. * @return {BABYLON.TransformNode|null} the transform node found or null if not found at all.
  23778. */
  23779. Scene.prototype.getTransformNodeByID = function (id) {
  23780. for (var index = 0; index < this.transformNodes.length; index++) {
  23781. if (this.transformNodes[index].id === id) {
  23782. return this.transformNodes[index];
  23783. }
  23784. }
  23785. return null;
  23786. };
  23787. Scene.prototype.getTransformNodesByID = function (id) {
  23788. return this.transformNodes.filter(function (m) {
  23789. return m.id === id;
  23790. });
  23791. };
  23792. /**
  23793. * Get a mesh with its auto-generated unique id
  23794. * @param {number} uniqueId - the unique id to search for
  23795. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  23796. */
  23797. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  23798. for (var index = 0; index < this.meshes.length; index++) {
  23799. if (this.meshes[index].uniqueId === uniqueId) {
  23800. return this.meshes[index];
  23801. }
  23802. }
  23803. return null;
  23804. };
  23805. /**
  23806. * Get a the last added mesh found of a given ID
  23807. * @param {string} id - the id to search for
  23808. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  23809. */
  23810. Scene.prototype.getLastMeshByID = function (id) {
  23811. for (var index = this.meshes.length - 1; index >= 0; index--) {
  23812. if (this.meshes[index].id === id) {
  23813. return this.meshes[index];
  23814. }
  23815. }
  23816. return null;
  23817. };
  23818. /**
  23819. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  23820. * @param {string} id - the id to search for
  23821. * @return {BABYLON.Node|null} the node found or null if not found at all.
  23822. */
  23823. Scene.prototype.getLastEntryByID = function (id) {
  23824. var index;
  23825. for (index = this.meshes.length - 1; index >= 0; index--) {
  23826. if (this.meshes[index].id === id) {
  23827. return this.meshes[index];
  23828. }
  23829. }
  23830. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  23831. if (this.transformNodes[index].id === id) {
  23832. return this.transformNodes[index];
  23833. }
  23834. }
  23835. for (index = this.cameras.length - 1; index >= 0; index--) {
  23836. if (this.cameras[index].id === id) {
  23837. return this.cameras[index];
  23838. }
  23839. }
  23840. for (index = this.lights.length - 1; index >= 0; index--) {
  23841. if (this.lights[index].id === id) {
  23842. return this.lights[index];
  23843. }
  23844. }
  23845. return null;
  23846. };
  23847. Scene.prototype.getNodeByID = function (id) {
  23848. var mesh = this.getMeshByID(id);
  23849. if (mesh) {
  23850. return mesh;
  23851. }
  23852. var light = this.getLightByID(id);
  23853. if (light) {
  23854. return light;
  23855. }
  23856. var camera = this.getCameraByID(id);
  23857. if (camera) {
  23858. return camera;
  23859. }
  23860. var bone = this.getBoneByID(id);
  23861. return bone;
  23862. };
  23863. Scene.prototype.getNodeByName = function (name) {
  23864. var mesh = this.getMeshByName(name);
  23865. if (mesh) {
  23866. return mesh;
  23867. }
  23868. var light = this.getLightByName(name);
  23869. if (light) {
  23870. return light;
  23871. }
  23872. var camera = this.getCameraByName(name);
  23873. if (camera) {
  23874. return camera;
  23875. }
  23876. var bone = this.getBoneByName(name);
  23877. return bone;
  23878. };
  23879. Scene.prototype.getMeshByName = function (name) {
  23880. for (var index = 0; index < this.meshes.length; index++) {
  23881. if (this.meshes[index].name === name) {
  23882. return this.meshes[index];
  23883. }
  23884. }
  23885. return null;
  23886. };
  23887. Scene.prototype.getTransformNodeByName = function (name) {
  23888. for (var index = 0; index < this.transformNodes.length; index++) {
  23889. if (this.transformNodes[index].name === name) {
  23890. return this.transformNodes[index];
  23891. }
  23892. }
  23893. return null;
  23894. };
  23895. Scene.prototype.getSoundByName = function (name) {
  23896. var index;
  23897. if (BABYLON.AudioEngine) {
  23898. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  23899. if (this.mainSoundTrack.soundCollection[index].name === name) {
  23900. return this.mainSoundTrack.soundCollection[index];
  23901. }
  23902. }
  23903. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  23904. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  23905. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  23906. return this.soundTracks[sdIndex].soundCollection[index];
  23907. }
  23908. }
  23909. }
  23910. }
  23911. return null;
  23912. };
  23913. Scene.prototype.getLastSkeletonByID = function (id) {
  23914. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  23915. if (this.skeletons[index].id === id) {
  23916. return this.skeletons[index];
  23917. }
  23918. }
  23919. return null;
  23920. };
  23921. Scene.prototype.getSkeletonById = function (id) {
  23922. for (var index = 0; index < this.skeletons.length; index++) {
  23923. if (this.skeletons[index].id === id) {
  23924. return this.skeletons[index];
  23925. }
  23926. }
  23927. return null;
  23928. };
  23929. Scene.prototype.getSkeletonByName = function (name) {
  23930. for (var index = 0; index < this.skeletons.length; index++) {
  23931. if (this.skeletons[index].name === name) {
  23932. return this.skeletons[index];
  23933. }
  23934. }
  23935. return null;
  23936. };
  23937. Scene.prototype.getMorphTargetManagerById = function (id) {
  23938. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  23939. if (this.morphTargetManagers[index].uniqueId === id) {
  23940. return this.morphTargetManagers[index];
  23941. }
  23942. }
  23943. return null;
  23944. };
  23945. Scene.prototype.isActiveMesh = function (mesh) {
  23946. return (this._activeMeshes.indexOf(mesh) !== -1);
  23947. };
  23948. /**
  23949. * Return a the first highlight layer of the scene with a given name.
  23950. * @param name The name of the highlight layer to look for.
  23951. * @return The highlight layer if found otherwise null.
  23952. */
  23953. Scene.prototype.getHighlightLayerByName = function (name) {
  23954. for (var index = 0; index < this.effectLayers.length; index++) {
  23955. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.HighlightLayer.EffectName) {
  23956. return this.effectLayers[index];
  23957. }
  23958. }
  23959. return null;
  23960. };
  23961. /**
  23962. * Return a the first highlight layer of the scene with a given name.
  23963. * @param name The name of the highlight layer to look for.
  23964. * @return The highlight layer if found otherwise null.
  23965. */
  23966. Scene.prototype.getGlowLayerByName = function (name) {
  23967. for (var index = 0; index < this.effectLayers.length; index++) {
  23968. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.GlowLayer.EffectName) {
  23969. return this.effectLayers[index];
  23970. }
  23971. }
  23972. return null;
  23973. };
  23974. Object.defineProperty(Scene.prototype, "uid", {
  23975. /**
  23976. * Return a unique id as a string which can serve as an identifier for the scene
  23977. */
  23978. get: function () {
  23979. if (!this._uid) {
  23980. this._uid = BABYLON.Tools.RandomId();
  23981. }
  23982. return this._uid;
  23983. },
  23984. enumerable: true,
  23985. configurable: true
  23986. });
  23987. /**
  23988. * Add an externaly attached data from its key.
  23989. * This method call will fail and return false, if such key already exists.
  23990. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  23991. * @param key the unique key that identifies the data
  23992. * @param data the data object to associate to the key for this Engine instance
  23993. * @return true if no such key were already present and the data was added successfully, false otherwise
  23994. */
  23995. Scene.prototype.addExternalData = function (key, data) {
  23996. if (!this._externalData) {
  23997. this._externalData = new BABYLON.StringDictionary();
  23998. }
  23999. return this._externalData.add(key, data);
  24000. };
  24001. /**
  24002. * Get an externaly attached data from its key
  24003. * @param key the unique key that identifies the data
  24004. * @return the associated data, if present (can be null), or undefined if not present
  24005. */
  24006. Scene.prototype.getExternalData = function (key) {
  24007. if (!this._externalData) {
  24008. return null;
  24009. }
  24010. return this._externalData.get(key);
  24011. };
  24012. /**
  24013. * Get an externaly attached data from its key, create it using a factory if it's not already present
  24014. * @param key the unique key that identifies the data
  24015. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  24016. * @return the associated data, can be null if the factory returned null.
  24017. */
  24018. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  24019. if (!this._externalData) {
  24020. this._externalData = new BABYLON.StringDictionary();
  24021. }
  24022. return this._externalData.getOrAddWithFactory(key, factory);
  24023. };
  24024. /**
  24025. * Remove an externaly attached data from the Engine instance
  24026. * @param key the unique key that identifies the data
  24027. * @return true if the data was successfully removed, false if it doesn't exist
  24028. */
  24029. Scene.prototype.removeExternalData = function (key) {
  24030. return this._externalData.remove(key);
  24031. };
  24032. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  24033. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  24034. if (mesh.showSubMeshesBoundingBox) {
  24035. var boundingInfo = subMesh.getBoundingInfo();
  24036. if (boundingInfo !== null && boundingInfo !== undefined) {
  24037. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  24038. }
  24039. }
  24040. var material = subMesh.getMaterial();
  24041. if (material !== null && material !== undefined) {
  24042. // Render targets
  24043. if (material.getRenderTargetTextures !== undefined) {
  24044. if (this._processedMaterials.indexOf(material) === -1) {
  24045. this._processedMaterials.push(material);
  24046. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  24047. }
  24048. }
  24049. // Dispatch
  24050. this._activeIndices.addCount(subMesh.indexCount, false);
  24051. this._renderingManager.dispatch(subMesh, mesh, material);
  24052. }
  24053. }
  24054. };
  24055. /**
  24056. * Clear the processed materials smart array preventing retention point in material dispose.
  24057. */
  24058. Scene.prototype.freeProcessedMaterials = function () {
  24059. this._processedMaterials.dispose();
  24060. };
  24061. /**
  24062. * Clear the active meshes smart array preventing retention point in mesh dispose.
  24063. */
  24064. Scene.prototype.freeActiveMeshes = function () {
  24065. this._activeMeshes.dispose();
  24066. if (this.activeCamera && this.activeCamera._activeMeshes) {
  24067. this.activeCamera._activeMeshes.dispose();
  24068. }
  24069. if (this.activeCameras) {
  24070. for (var i = 0; i < this.activeCameras.length; i++) {
  24071. var activeCamera = this.activeCameras[i];
  24072. if (activeCamera && activeCamera._activeMeshes) {
  24073. activeCamera._activeMeshes.dispose();
  24074. }
  24075. }
  24076. }
  24077. };
  24078. /**
  24079. * Clear the info related to rendering groups preventing retention points during dispose.
  24080. */
  24081. Scene.prototype.freeRenderingGroups = function () {
  24082. if (this._renderingManager) {
  24083. this._renderingManager.freeRenderingGroups();
  24084. }
  24085. if (this.textures) {
  24086. for (var i = 0; i < this.textures.length; i++) {
  24087. var texture = this.textures[i];
  24088. if (texture && texture.renderList) {
  24089. texture.freeRenderingGroups();
  24090. }
  24091. }
  24092. }
  24093. };
  24094. Scene.prototype._isInIntermediateRendering = function () {
  24095. return this._intermediateRendering;
  24096. };
  24097. Scene.prototype.setActiveMeshCandidateProvider = function (provider) {
  24098. this._activeMeshCandidateProvider = provider;
  24099. };
  24100. Scene.prototype.getActiveMeshCandidateProvider = function () {
  24101. return this._activeMeshCandidateProvider;
  24102. };
  24103. /**
  24104. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  24105. */
  24106. Scene.prototype.freezeActiveMeshes = function () {
  24107. if (!this.activeCamera) {
  24108. return this;
  24109. }
  24110. if (!this._frustumPlanes) {
  24111. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  24112. }
  24113. this._evaluateActiveMeshes();
  24114. this._activeMeshesFrozen = true;
  24115. return this;
  24116. };
  24117. /**
  24118. * Use this function to restart evaluating active meshes on every frame
  24119. */
  24120. Scene.prototype.unfreezeActiveMeshes = function () {
  24121. this._activeMeshesFrozen = false;
  24122. return this;
  24123. };
  24124. Scene.prototype._evaluateActiveMeshes = function () {
  24125. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  24126. return;
  24127. }
  24128. if (!this.activeCamera) {
  24129. return;
  24130. }
  24131. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  24132. this.activeCamera._activeMeshes.reset();
  24133. this._activeMeshes.reset();
  24134. this._renderingManager.reset();
  24135. this._processedMaterials.reset();
  24136. this._activeParticleSystems.reset();
  24137. this._activeSkeletons.reset();
  24138. this._softwareSkinnedMeshes.reset();
  24139. if (this._boundingBoxRenderer) {
  24140. this._boundingBoxRenderer.reset();
  24141. }
  24142. // Meshes
  24143. var meshes;
  24144. var len;
  24145. var checkIsEnabled = true;
  24146. // Determine mesh candidates
  24147. if (this._activeMeshCandidateProvider !== undefined) {
  24148. // Use _activeMeshCandidateProvider
  24149. meshes = this._activeMeshCandidateProvider.getMeshes(this);
  24150. checkIsEnabled = this._activeMeshCandidateProvider.checksIsEnabled === false;
  24151. if (meshes !== undefined) {
  24152. len = meshes.length;
  24153. }
  24154. else {
  24155. len = 0;
  24156. }
  24157. }
  24158. else if (this._selectionOctree !== undefined) {
  24159. // Octree
  24160. var selection = this._selectionOctree.select(this._frustumPlanes);
  24161. meshes = selection.data;
  24162. len = selection.length;
  24163. }
  24164. else {
  24165. // Full scene traversal
  24166. len = this.meshes.length;
  24167. meshes = this.meshes;
  24168. }
  24169. // Check each mesh
  24170. for (var meshIndex = 0, mesh, meshLOD; meshIndex < len; meshIndex++) {
  24171. mesh = meshes[meshIndex];
  24172. if (mesh.isBlocked) {
  24173. continue;
  24174. }
  24175. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  24176. if (!mesh.isReady() || (checkIsEnabled && !mesh.isEnabled())) {
  24177. continue;
  24178. }
  24179. mesh.computeWorldMatrix();
  24180. // Intersections
  24181. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  24182. this._meshesForIntersections.pushNoDuplicate(mesh);
  24183. }
  24184. // Switch to current LOD
  24185. meshLOD = mesh.getLOD(this.activeCamera);
  24186. if (meshLOD === undefined || meshLOD === null) {
  24187. continue;
  24188. }
  24189. mesh._preActivate();
  24190. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  24191. this._activeMeshes.push(mesh);
  24192. this.activeCamera._activeMeshes.push(mesh);
  24193. mesh._activate(this._renderId);
  24194. if (meshLOD !== mesh) {
  24195. meshLOD._activate(this._renderId);
  24196. }
  24197. this._activeMesh(mesh, meshLOD);
  24198. }
  24199. }
  24200. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  24201. // Particle systems
  24202. if (this.particlesEnabled) {
  24203. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  24204. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  24205. var particleSystem = this.particleSystems[particleIndex];
  24206. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  24207. continue;
  24208. }
  24209. var emitter = particleSystem.emitter;
  24210. if (!emitter.position || emitter.isEnabled()) {
  24211. this._activeParticleSystems.push(particleSystem);
  24212. particleSystem.animate();
  24213. this._renderingManager.dispatchParticles(particleSystem);
  24214. }
  24215. }
  24216. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  24217. }
  24218. };
  24219. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  24220. if (this.skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  24221. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  24222. mesh.skeleton.prepare();
  24223. }
  24224. if (!mesh.computeBonesUsingShaders) {
  24225. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  24226. }
  24227. }
  24228. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  24229. var boundingInfo = sourceMesh.getBoundingInfo();
  24230. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  24231. }
  24232. if (mesh !== undefined && mesh !== null
  24233. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  24234. // Submeshes Octrees
  24235. var len;
  24236. var subMeshes;
  24237. if (mesh.useOctreeForRenderingSelection && mesh._submeshesOctree !== undefined && mesh._submeshesOctree !== null) {
  24238. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  24239. len = intersections.length;
  24240. subMeshes = intersections.data;
  24241. }
  24242. else {
  24243. subMeshes = mesh.subMeshes;
  24244. len = subMeshes.length;
  24245. }
  24246. for (var subIndex = 0, subMesh; subIndex < len; subIndex++) {
  24247. subMesh = subMeshes[subIndex];
  24248. this._evaluateSubMesh(subMesh, mesh);
  24249. }
  24250. }
  24251. };
  24252. Scene.prototype.updateTransformMatrix = function (force) {
  24253. if (!this.activeCamera) {
  24254. return;
  24255. }
  24256. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  24257. };
  24258. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  24259. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  24260. };
  24261. Scene.prototype._renderForCamera = function (camera, rigParent) {
  24262. if (camera && camera._skipRendering) {
  24263. return;
  24264. }
  24265. var engine = this._engine;
  24266. this.activeCamera = camera;
  24267. if (!this.activeCamera)
  24268. throw new Error("Active camera not set");
  24269. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  24270. // Viewport
  24271. engine.setViewport(this.activeCamera.viewport);
  24272. // Camera
  24273. this.resetCachedMaterial();
  24274. this._renderId++;
  24275. this.updateTransformMatrix();
  24276. if (camera._alternateCamera) {
  24277. this.updateAlternateTransformMatrix(camera._alternateCamera);
  24278. this._alternateRendering = true;
  24279. }
  24280. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  24281. // Meshes
  24282. this._evaluateActiveMeshes();
  24283. // Software skinning
  24284. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  24285. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  24286. mesh.applySkeleton(mesh.skeleton);
  24287. }
  24288. // Render targets
  24289. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  24290. var needsRestoreFrameBuffer = false;
  24291. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  24292. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  24293. }
  24294. if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) {
  24295. this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets);
  24296. }
  24297. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  24298. this._intermediateRendering = true;
  24299. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  24300. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  24301. var renderTarget = this._renderTargets.data[renderIndex];
  24302. if (renderTarget._shouldRender()) {
  24303. this._renderId++;
  24304. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  24305. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  24306. }
  24307. }
  24308. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  24309. this._intermediateRendering = false;
  24310. this._renderId++;
  24311. needsRestoreFrameBuffer = true; // Restore back buffer
  24312. }
  24313. // Render EffecttLayer Texture
  24314. var stencilState = this._engine.getStencilBuffer();
  24315. var renderEffects = false;
  24316. var needStencil = false;
  24317. if (this.renderTargetsEnabled && this.effectLayers && this.effectLayers.length > 0) {
  24318. this._intermediateRendering = true;
  24319. for (var i = 0; i < this.effectLayers.length; i++) {
  24320. var effectLayer = this.effectLayers[i];
  24321. if (effectLayer.shouldRender() &&
  24322. (!effectLayer.camera ||
  24323. (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
  24324. (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
  24325. renderEffects = true;
  24326. needStencil = needStencil || effectLayer.needStencil();
  24327. var renderTarget = effectLayer._mainTexture;
  24328. if (renderTarget._shouldRender()) {
  24329. this._renderId++;
  24330. renderTarget.render(false, false);
  24331. needsRestoreFrameBuffer = true;
  24332. }
  24333. }
  24334. }
  24335. this._intermediateRendering = false;
  24336. this._renderId++;
  24337. }
  24338. if (needsRestoreFrameBuffer) {
  24339. engine.restoreDefaultFramebuffer(); // Restore back buffer
  24340. }
  24341. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  24342. // Prepare Frame
  24343. this.postProcessManager._prepareFrame();
  24344. // Backgrounds
  24345. var layerIndex;
  24346. var layer;
  24347. if (this.layers.length) {
  24348. engine.setDepthBuffer(false);
  24349. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  24350. layer = this.layers[layerIndex];
  24351. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  24352. layer.render();
  24353. }
  24354. }
  24355. engine.setDepthBuffer(true);
  24356. }
  24357. // Activate effect Layer stencil
  24358. if (needStencil) {
  24359. this._engine.setStencilBuffer(true);
  24360. }
  24361. // Render
  24362. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  24363. this._renderingManager.render(null, null, true, true);
  24364. this.onAfterDrawPhaseObservable.notifyObservers(this);
  24365. // Restore effect Layer stencil
  24366. if (needStencil) {
  24367. this._engine.setStencilBuffer(stencilState);
  24368. }
  24369. // Bounding boxes
  24370. if (this._boundingBoxRenderer) {
  24371. this._boundingBoxRenderer.render();
  24372. }
  24373. // Lens flares
  24374. if (this.lensFlaresEnabled) {
  24375. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  24376. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  24377. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  24378. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  24379. lensFlareSystem.render();
  24380. }
  24381. }
  24382. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  24383. }
  24384. // Foregrounds
  24385. if (this.layers.length) {
  24386. engine.setDepthBuffer(false);
  24387. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  24388. layer = this.layers[layerIndex];
  24389. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  24390. layer.render();
  24391. }
  24392. }
  24393. engine.setDepthBuffer(true);
  24394. }
  24395. // Effect Layer
  24396. if (renderEffects) {
  24397. engine.setDepthBuffer(false);
  24398. for (var i = 0; i < this.effectLayers.length; i++) {
  24399. if (this.effectLayers[i].shouldRender()) {
  24400. this.effectLayers[i].render();
  24401. }
  24402. }
  24403. engine.setDepthBuffer(true);
  24404. }
  24405. // Finalize frame
  24406. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  24407. // Reset some special arrays
  24408. this._renderTargets.reset();
  24409. this._alternateRendering = false;
  24410. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  24411. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  24412. };
  24413. Scene.prototype._processSubCameras = function (camera) {
  24414. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  24415. this._renderForCamera(camera);
  24416. return;
  24417. }
  24418. // rig cameras
  24419. for (var index = 0; index < camera._rigCameras.length; index++) {
  24420. this._renderForCamera(camera._rigCameras[index], camera);
  24421. }
  24422. this.activeCamera = camera;
  24423. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  24424. };
  24425. Scene.prototype._checkIntersections = function () {
  24426. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  24427. var sourceMesh = this._meshesForIntersections.data[index];
  24428. if (!sourceMesh.actionManager) {
  24429. continue;
  24430. }
  24431. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  24432. var action = sourceMesh.actionManager.actions[actionIndex];
  24433. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  24434. var parameters = action.getTriggerParameter();
  24435. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  24436. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  24437. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  24438. if (areIntersecting && currentIntersectionInProgress === -1) {
  24439. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  24440. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  24441. sourceMesh._intersectionsInProgress.push(otherMesh);
  24442. }
  24443. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  24444. sourceMesh._intersectionsInProgress.push(otherMesh);
  24445. }
  24446. }
  24447. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  24448. //They intersected, and now they don't.
  24449. //is this trigger an exit trigger? execute an event.
  24450. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  24451. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  24452. }
  24453. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  24454. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  24455. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  24456. }
  24457. }
  24458. }
  24459. }
  24460. }
  24461. };
  24462. Scene.prototype.render = function () {
  24463. if (this.isDisposed) {
  24464. return;
  24465. }
  24466. this._activeParticles.fetchNewFrame();
  24467. this._totalVertices.fetchNewFrame();
  24468. this._activeIndices.fetchNewFrame();
  24469. this._activeBones.fetchNewFrame();
  24470. this._meshesForIntersections.reset();
  24471. this.resetCachedMaterial();
  24472. this.onBeforeAnimationsObservable.notifyObservers(this);
  24473. // Actions
  24474. if (this.actionManager) {
  24475. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  24476. }
  24477. //Simplification Queue
  24478. if (this.simplificationQueue && !this.simplificationQueue.running) {
  24479. this.simplificationQueue.executeNext();
  24480. }
  24481. if (this._engine.isDeterministicLockStep()) {
  24482. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  24483. var defaultFPS = (60.0 / 1000.0);
  24484. var defaultFrameTime = 1000 / 60; // frame time in MS
  24485. if (this._physicsEngine) {
  24486. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  24487. }
  24488. var stepsTaken = 0;
  24489. var maxSubSteps = this._engine.getLockstepMaxSteps();
  24490. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  24491. internalSteps = Math.min(internalSteps, maxSubSteps);
  24492. do {
  24493. this.onBeforeStepObservable.notifyObservers(this);
  24494. // Animations
  24495. this._animationRatio = defaultFrameTime * defaultFPS;
  24496. this._animate();
  24497. this.onAfterAnimationsObservable.notifyObservers(this);
  24498. // Physics
  24499. if (this._physicsEngine) {
  24500. this.onBeforePhysicsObservable.notifyObservers(this);
  24501. this._physicsEngine._step(defaultFrameTime / 1000);
  24502. this.onAfterPhysicsObservable.notifyObservers(this);
  24503. }
  24504. this.onAfterStepObservable.notifyObservers(this);
  24505. this._currentStepId++;
  24506. stepsTaken++;
  24507. deltaTime -= defaultFrameTime;
  24508. } while (deltaTime > 0 && stepsTaken < internalSteps);
  24509. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  24510. }
  24511. else {
  24512. // Animations
  24513. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  24514. this._animationRatio = deltaTime * (60.0 / 1000.0);
  24515. this._animate();
  24516. this.onAfterAnimationsObservable.notifyObservers(this);
  24517. // Physics
  24518. if (this._physicsEngine) {
  24519. this.onBeforePhysicsObservable.notifyObservers(this);
  24520. this._physicsEngine._step(deltaTime / 1000.0);
  24521. this.onAfterPhysicsObservable.notifyObservers(this);
  24522. }
  24523. }
  24524. // update gamepad manager
  24525. if (this._gamepadManager && this._gamepadManager._isMonitoring) {
  24526. this._gamepadManager._checkGamepadsStatus();
  24527. }
  24528. // Update Cameras
  24529. if (this.activeCameras.length > 0) {
  24530. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  24531. var camera = this.activeCameras[cameraIndex];
  24532. camera.update();
  24533. if (camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  24534. // rig cameras
  24535. for (var index = 0; index < camera._rigCameras.length; index++) {
  24536. camera._rigCameras[index].update();
  24537. }
  24538. }
  24539. }
  24540. }
  24541. else if (this.activeCamera) {
  24542. this.activeCamera.update();
  24543. if (this.activeCamera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  24544. // rig cameras
  24545. for (var index = 0; index < this.activeCamera._rigCameras.length; index++) {
  24546. this.activeCamera._rigCameras[index].update();
  24547. }
  24548. }
  24549. }
  24550. // Before render
  24551. this.onBeforeRenderObservable.notifyObservers(this);
  24552. // Customs render targets
  24553. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  24554. var engine = this.getEngine();
  24555. var currentActiveCamera = this.activeCamera;
  24556. if (this.renderTargetsEnabled) {
  24557. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  24558. this._intermediateRendering = true;
  24559. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  24560. var renderTarget = this.customRenderTargets[customIndex];
  24561. if (renderTarget._shouldRender()) {
  24562. this._renderId++;
  24563. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  24564. if (!this.activeCamera)
  24565. throw new Error("Active camera not set");
  24566. // Viewport
  24567. engine.setViewport(this.activeCamera.viewport);
  24568. // Camera
  24569. this.updateTransformMatrix();
  24570. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  24571. }
  24572. }
  24573. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  24574. this._intermediateRendering = false;
  24575. this._renderId++;
  24576. }
  24577. // Restore back buffer
  24578. if (this.customRenderTargets.length > 0) {
  24579. engine.restoreDefaultFramebuffer();
  24580. }
  24581. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  24582. this.activeCamera = currentActiveCamera;
  24583. // Procedural textures
  24584. if (this.proceduralTexturesEnabled) {
  24585. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  24586. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  24587. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  24588. if (proceduralTexture._shouldRender()) {
  24589. proceduralTexture.render();
  24590. }
  24591. }
  24592. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  24593. }
  24594. // Clear
  24595. if (this.autoClearDepthAndStencil || this.autoClear) {
  24596. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  24597. }
  24598. // Shadows
  24599. if (this.shadowsEnabled) {
  24600. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  24601. var light = this.lights[lightIndex];
  24602. var shadowGenerator = light.getShadowGenerator();
  24603. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  24604. var shadowMap = (shadowGenerator.getShadowMap());
  24605. if (this.textures.indexOf(shadowMap) !== -1) {
  24606. this._renderTargets.push(shadowMap);
  24607. }
  24608. }
  24609. }
  24610. }
  24611. // Depth renderer
  24612. for (var key in this._depthRenderer) {
  24613. this._renderTargets.push(this._depthRenderer[key].getDepthMap());
  24614. }
  24615. // Geometry renderer
  24616. if (this._geometryBufferRenderer) {
  24617. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  24618. }
  24619. // RenderPipeline
  24620. if (this._postProcessRenderPipelineManager) {
  24621. this._postProcessRenderPipelineManager.update();
  24622. }
  24623. // Multi-cameras?
  24624. if (this.activeCameras.length > 0) {
  24625. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  24626. if (cameraIndex > 0) {
  24627. this._engine.clear(null, false, true, true);
  24628. }
  24629. this._processSubCameras(this.activeCameras[cameraIndex]);
  24630. }
  24631. }
  24632. else {
  24633. if (!this.activeCamera) {
  24634. throw new Error("No camera defined");
  24635. }
  24636. this._processSubCameras(this.activeCamera);
  24637. }
  24638. // Intersection checks
  24639. this._checkIntersections();
  24640. // Update the audio listener attached to the camera
  24641. if (BABYLON.AudioEngine) {
  24642. this._updateAudioParameters();
  24643. }
  24644. // After render
  24645. if (this.afterRender) {
  24646. this.afterRender();
  24647. }
  24648. this.onAfterRenderObservable.notifyObservers(this);
  24649. // Cleaning
  24650. for (var index = 0; index < this._toBeDisposed.length; index++) {
  24651. var data = this._toBeDisposed.data[index];
  24652. if (data) {
  24653. data.dispose();
  24654. }
  24655. this._toBeDisposed[index] = null;
  24656. }
  24657. this._toBeDisposed.reset();
  24658. if (this.dumpNextRenderTargets) {
  24659. this.dumpNextRenderTargets = false;
  24660. }
  24661. this._activeBones.addCount(0, true);
  24662. this._activeIndices.addCount(0, true);
  24663. this._activeParticles.addCount(0, true);
  24664. };
  24665. Scene.prototype._updateAudioParameters = function () {
  24666. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  24667. return;
  24668. }
  24669. var listeningCamera;
  24670. var audioEngine = BABYLON.Engine.audioEngine;
  24671. if (this.activeCameras.length > 0) {
  24672. listeningCamera = this.activeCameras[0];
  24673. }
  24674. else {
  24675. listeningCamera = this.activeCamera;
  24676. }
  24677. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  24678. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  24679. // for VR cameras
  24680. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  24681. listeningCamera = listeningCamera.rigCameras[0];
  24682. }
  24683. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  24684. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  24685. cameraDirection.normalize();
  24686. // To avoid some errors on GearVR
  24687. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  24688. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  24689. }
  24690. var i;
  24691. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  24692. var sound = this.mainSoundTrack.soundCollection[i];
  24693. if (sound.useCustomAttenuation) {
  24694. sound.updateDistanceFromListener();
  24695. }
  24696. }
  24697. for (i = 0; i < this.soundTracks.length; i++) {
  24698. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  24699. sound = this.soundTracks[i].soundCollection[j];
  24700. if (sound.useCustomAttenuation) {
  24701. sound.updateDistanceFromListener();
  24702. }
  24703. }
  24704. }
  24705. }
  24706. };
  24707. Object.defineProperty(Scene.prototype, "audioEnabled", {
  24708. // Audio
  24709. get: function () {
  24710. return this._audioEnabled;
  24711. },
  24712. set: function (value) {
  24713. this._audioEnabled = value;
  24714. if (BABYLON.AudioEngine) {
  24715. if (this._audioEnabled) {
  24716. this._enableAudio();
  24717. }
  24718. else {
  24719. this._disableAudio();
  24720. }
  24721. }
  24722. },
  24723. enumerable: true,
  24724. configurable: true
  24725. });
  24726. Scene.prototype._disableAudio = function () {
  24727. var i;
  24728. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  24729. this.mainSoundTrack.soundCollection[i].pause();
  24730. }
  24731. for (i = 0; i < this.soundTracks.length; i++) {
  24732. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  24733. this.soundTracks[i].soundCollection[j].pause();
  24734. }
  24735. }
  24736. };
  24737. Scene.prototype._enableAudio = function () {
  24738. var i;
  24739. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  24740. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  24741. this.mainSoundTrack.soundCollection[i].play();
  24742. }
  24743. }
  24744. for (i = 0; i < this.soundTracks.length; i++) {
  24745. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  24746. if (this.soundTracks[i].soundCollection[j].isPaused) {
  24747. this.soundTracks[i].soundCollection[j].play();
  24748. }
  24749. }
  24750. }
  24751. };
  24752. Object.defineProperty(Scene.prototype, "headphone", {
  24753. get: function () {
  24754. return this._headphone;
  24755. },
  24756. set: function (value) {
  24757. this._headphone = value;
  24758. if (BABYLON.AudioEngine) {
  24759. if (this._headphone) {
  24760. this._switchAudioModeForHeadphones();
  24761. }
  24762. else {
  24763. this._switchAudioModeForNormalSpeakers();
  24764. }
  24765. }
  24766. },
  24767. enumerable: true,
  24768. configurable: true
  24769. });
  24770. Scene.prototype._switchAudioModeForHeadphones = function () {
  24771. this.mainSoundTrack.switchPanningModelToHRTF();
  24772. for (var i = 0; i < this.soundTracks.length; i++) {
  24773. this.soundTracks[i].switchPanningModelToHRTF();
  24774. }
  24775. };
  24776. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  24777. this.mainSoundTrack.switchPanningModelToEqualPower();
  24778. for (var i = 0; i < this.soundTracks.length; i++) {
  24779. this.soundTracks[i].switchPanningModelToEqualPower();
  24780. }
  24781. };
  24782. /**
  24783. * Creates a depth renderer a given camera which contains a depth map which can be used for post processing.
  24784. * @param camera The camera to create the depth renderer on (default: scene's active camera)
  24785. * @returns the created depth renderer
  24786. */
  24787. Scene.prototype.enableDepthRenderer = function (camera) {
  24788. camera = camera || this.activeCamera;
  24789. if (!camera) {
  24790. throw "No camera available to enable depth renderer";
  24791. }
  24792. if (!this._depthRenderer[camera.id]) {
  24793. this._depthRenderer[camera.id] = new BABYLON.DepthRenderer(this, BABYLON.Engine.TEXTURETYPE_FLOAT, camera);
  24794. }
  24795. return this._depthRenderer[camera.id];
  24796. };
  24797. /**
  24798. * Disables a depth renderer for a given camera
  24799. * @param camera The camera to disable the depth renderer on (default: scene's active camera)
  24800. */
  24801. Scene.prototype.disableDepthRenderer = function (camera) {
  24802. camera = camera || this.activeCamera;
  24803. if (!camera || !this._depthRenderer[camera.id]) {
  24804. return;
  24805. }
  24806. this._depthRenderer[camera.id].dispose();
  24807. delete this._depthRenderer[camera.id];
  24808. };
  24809. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  24810. if (ratio === void 0) { ratio = 1; }
  24811. if (this._geometryBufferRenderer) {
  24812. return this._geometryBufferRenderer;
  24813. }
  24814. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  24815. if (!this._geometryBufferRenderer.isSupported) {
  24816. this._geometryBufferRenderer = null;
  24817. }
  24818. return this._geometryBufferRenderer;
  24819. };
  24820. Scene.prototype.disableGeometryBufferRenderer = function () {
  24821. if (!this._geometryBufferRenderer) {
  24822. return;
  24823. }
  24824. this._geometryBufferRenderer.dispose();
  24825. this._geometryBufferRenderer = null;
  24826. };
  24827. Scene.prototype.freezeMaterials = function () {
  24828. for (var i = 0; i < this.materials.length; i++) {
  24829. this.materials[i].freeze();
  24830. }
  24831. };
  24832. Scene.prototype.unfreezeMaterials = function () {
  24833. for (var i = 0; i < this.materials.length; i++) {
  24834. this.materials[i].unfreeze();
  24835. }
  24836. };
  24837. Scene.prototype.dispose = function () {
  24838. this.beforeRender = null;
  24839. this.afterRender = null;
  24840. this.skeletons = [];
  24841. this.morphTargetManagers = [];
  24842. this.importedMeshesFiles = new Array();
  24843. this.stopAllAnimations();
  24844. this.resetCachedMaterial();
  24845. for (var key in this._depthRenderer) {
  24846. this._depthRenderer[key].dispose();
  24847. }
  24848. if (this._gamepadManager) {
  24849. this._gamepadManager.dispose();
  24850. this._gamepadManager = null;
  24851. }
  24852. // Smart arrays
  24853. if (this.activeCamera) {
  24854. this.activeCamera._activeMeshes.dispose();
  24855. this.activeCamera = null;
  24856. }
  24857. this._activeMeshes.dispose();
  24858. this._renderingManager.dispose();
  24859. this._processedMaterials.dispose();
  24860. this._activeParticleSystems.dispose();
  24861. this._activeSkeletons.dispose();
  24862. this._softwareSkinnedMeshes.dispose();
  24863. this._renderTargets.dispose();
  24864. if (this._boundingBoxRenderer) {
  24865. this._boundingBoxRenderer.dispose();
  24866. }
  24867. this._meshesForIntersections.dispose();
  24868. this._toBeDisposed.dispose();
  24869. // Abort active requests
  24870. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  24871. var request = _a[_i];
  24872. request.abort();
  24873. }
  24874. // Debug layer
  24875. if (this._debugLayer) {
  24876. this._debugLayer.hide();
  24877. }
  24878. // Events
  24879. this.onDisposeObservable.notifyObservers(this);
  24880. this.onDisposeObservable.clear();
  24881. this.onBeforeRenderObservable.clear();
  24882. this.onAfterRenderObservable.clear();
  24883. this.OnBeforeRenderTargetsRenderObservable.clear();
  24884. this.OnAfterRenderTargetsRenderObservable.clear();
  24885. this.onAfterStepObservable.clear();
  24886. this.onBeforeStepObservable.clear();
  24887. this.onBeforeActiveMeshesEvaluationObservable.clear();
  24888. this.onAfterActiveMeshesEvaluationObservable.clear();
  24889. this.onBeforeParticlesRenderingObservable.clear();
  24890. this.onAfterParticlesRenderingObservable.clear();
  24891. this.onBeforeSpritesRenderingObservable.clear();
  24892. this.onAfterSpritesRenderingObservable.clear();
  24893. this.onBeforeDrawPhaseObservable.clear();
  24894. this.onAfterDrawPhaseObservable.clear();
  24895. this.onBeforePhysicsObservable.clear();
  24896. this.onAfterPhysicsObservable.clear();
  24897. this.onBeforeAnimationsObservable.clear();
  24898. this.onAfterAnimationsObservable.clear();
  24899. this.onDataLoadedObservable.clear();
  24900. this.detachControl();
  24901. // Release sounds & sounds tracks
  24902. if (BABYLON.AudioEngine) {
  24903. this.disposeSounds();
  24904. }
  24905. // VR Helper
  24906. if (this.VRHelper) {
  24907. this.VRHelper.dispose();
  24908. }
  24909. // Detach cameras
  24910. var canvas = this._engine.getRenderingCanvas();
  24911. if (canvas) {
  24912. var index;
  24913. for (index = 0; index < this.cameras.length; index++) {
  24914. this.cameras[index].detachControl(canvas);
  24915. }
  24916. }
  24917. // Release animation groups
  24918. while (this.animationGroups.length) {
  24919. this.animationGroups[0].dispose();
  24920. }
  24921. // Release lights
  24922. while (this.lights.length) {
  24923. this.lights[0].dispose();
  24924. }
  24925. // Release meshes
  24926. while (this.meshes.length) {
  24927. this.meshes[0].dispose(true);
  24928. }
  24929. while (this.transformNodes.length) {
  24930. this.removeTransformNode(this.transformNodes[0]);
  24931. }
  24932. // Release cameras
  24933. while (this.cameras.length) {
  24934. this.cameras[0].dispose();
  24935. }
  24936. // Release materials
  24937. if (this.defaultMaterial) {
  24938. this.defaultMaterial.dispose();
  24939. }
  24940. while (this.multiMaterials.length) {
  24941. this.multiMaterials[0].dispose();
  24942. }
  24943. while (this.materials.length) {
  24944. this.materials[0].dispose();
  24945. }
  24946. // Release particles
  24947. while (this.particleSystems.length) {
  24948. this.particleSystems[0].dispose();
  24949. }
  24950. // Release sprites
  24951. while (this.spriteManagers.length) {
  24952. this.spriteManagers[0].dispose();
  24953. }
  24954. // Release postProcesses
  24955. while (this.postProcesses.length) {
  24956. this.postProcesses[0].dispose();
  24957. }
  24958. // Release layers
  24959. while (this.layers.length) {
  24960. this.layers[0].dispose();
  24961. }
  24962. while (this.effectLayers.length) {
  24963. this.effectLayers[0].dispose();
  24964. }
  24965. // Release textures
  24966. while (this.textures.length) {
  24967. this.textures[0].dispose();
  24968. }
  24969. // Release UBO
  24970. this._sceneUbo.dispose();
  24971. if (this._alternateSceneUbo) {
  24972. this._alternateSceneUbo.dispose();
  24973. }
  24974. // Post-processes
  24975. this.postProcessManager.dispose();
  24976. if (this._postProcessRenderPipelineManager) {
  24977. this._postProcessRenderPipelineManager.dispose();
  24978. }
  24979. // Physics
  24980. if (this._physicsEngine) {
  24981. this.disablePhysicsEngine();
  24982. }
  24983. // Remove from engine
  24984. index = this._engine.scenes.indexOf(this);
  24985. if (index > -1) {
  24986. this._engine.scenes.splice(index, 1);
  24987. }
  24988. this._engine.wipeCaches(true);
  24989. this._isDisposed = true;
  24990. };
  24991. Object.defineProperty(Scene.prototype, "isDisposed", {
  24992. get: function () {
  24993. return this._isDisposed;
  24994. },
  24995. enumerable: true,
  24996. configurable: true
  24997. });
  24998. // Release sounds & sounds tracks
  24999. Scene.prototype.disposeSounds = function () {
  25000. if (!this._mainSoundTrack) {
  25001. return;
  25002. }
  25003. this.mainSoundTrack.dispose();
  25004. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  25005. this.soundTracks[scIndex].dispose();
  25006. }
  25007. };
  25008. // Octrees
  25009. /**
  25010. * Get the world extend vectors with an optional filter
  25011. *
  25012. * @param filterPredicate the predicate - which meshes should be included when calculating the world size
  25013. * @returns {{ min: Vector3; max: Vector3 }} min and max vectors
  25014. */
  25015. Scene.prototype.getWorldExtends = function (filterPredicate) {
  25016. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  25017. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  25018. filterPredicate = filterPredicate || (function () { return true; });
  25019. this.meshes.filter(filterPredicate).forEach(function (mesh) {
  25020. mesh.computeWorldMatrix(true);
  25021. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  25022. return;
  25023. }
  25024. var boundingInfo = mesh.getBoundingInfo();
  25025. var minBox = boundingInfo.boundingBox.minimumWorld;
  25026. var maxBox = boundingInfo.boundingBox.maximumWorld;
  25027. BABYLON.Tools.CheckExtends(minBox, min, max);
  25028. BABYLON.Tools.CheckExtends(maxBox, min, max);
  25029. });
  25030. return {
  25031. min: min,
  25032. max: max
  25033. };
  25034. };
  25035. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  25036. if (maxCapacity === void 0) { maxCapacity = 64; }
  25037. if (maxDepth === void 0) { maxDepth = 2; }
  25038. if (!this._selectionOctree) {
  25039. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  25040. }
  25041. var worldExtends = this.getWorldExtends();
  25042. // Update octree
  25043. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  25044. return this._selectionOctree;
  25045. };
  25046. // Picking
  25047. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  25048. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  25049. var result = BABYLON.Ray.Zero();
  25050. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  25051. return result;
  25052. };
  25053. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  25054. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  25055. var engine = this._engine;
  25056. if (!camera) {
  25057. if (!this.activeCamera)
  25058. throw new Error("Active camera not set");
  25059. camera = this.activeCamera;
  25060. }
  25061. var cameraViewport = camera.viewport;
  25062. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  25063. // Moving coordinates to local viewport world
  25064. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  25065. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  25066. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  25067. return this;
  25068. };
  25069. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  25070. var result = BABYLON.Ray.Zero();
  25071. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  25072. return result;
  25073. };
  25074. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  25075. if (!BABYLON.PickingInfo) {
  25076. return this;
  25077. }
  25078. var engine = this._engine;
  25079. if (!camera) {
  25080. if (!this.activeCamera)
  25081. throw new Error("Active camera not set");
  25082. camera = this.activeCamera;
  25083. }
  25084. var cameraViewport = camera.viewport;
  25085. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  25086. var identity = BABYLON.Matrix.Identity();
  25087. // Moving coordinates to local viewport world
  25088. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  25089. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  25090. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  25091. return this;
  25092. };
  25093. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  25094. if (!BABYLON.PickingInfo) {
  25095. return null;
  25096. }
  25097. var pickingInfo = null;
  25098. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  25099. var mesh = this.meshes[meshIndex];
  25100. if (predicate) {
  25101. if (!predicate(mesh)) {
  25102. continue;
  25103. }
  25104. }
  25105. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  25106. continue;
  25107. }
  25108. var world = mesh.getWorldMatrix();
  25109. var ray = rayFunction(world);
  25110. var result = mesh.intersects(ray, fastCheck);
  25111. if (!result || !result.hit)
  25112. continue;
  25113. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  25114. continue;
  25115. pickingInfo = result;
  25116. if (fastCheck) {
  25117. break;
  25118. }
  25119. }
  25120. return pickingInfo || new BABYLON.PickingInfo();
  25121. };
  25122. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  25123. if (!BABYLON.PickingInfo) {
  25124. return null;
  25125. }
  25126. var pickingInfos = new Array();
  25127. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  25128. var mesh = this.meshes[meshIndex];
  25129. if (predicate) {
  25130. if (!predicate(mesh)) {
  25131. continue;
  25132. }
  25133. }
  25134. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  25135. continue;
  25136. }
  25137. var world = mesh.getWorldMatrix();
  25138. var ray = rayFunction(world);
  25139. var result = mesh.intersects(ray, false);
  25140. if (!result || !result.hit)
  25141. continue;
  25142. pickingInfos.push(result);
  25143. }
  25144. return pickingInfos;
  25145. };
  25146. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  25147. if (!BABYLON.PickingInfo) {
  25148. return null;
  25149. }
  25150. var pickingInfo = null;
  25151. if (!camera) {
  25152. if (!this.activeCamera) {
  25153. return null;
  25154. }
  25155. camera = this.activeCamera;
  25156. }
  25157. if (this.spriteManagers.length > 0) {
  25158. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  25159. var spriteManager = this.spriteManagers[spriteIndex];
  25160. if (!spriteManager.isPickable) {
  25161. continue;
  25162. }
  25163. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  25164. if (!result || !result.hit)
  25165. continue;
  25166. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  25167. continue;
  25168. pickingInfo = result;
  25169. if (fastCheck) {
  25170. break;
  25171. }
  25172. }
  25173. }
  25174. return pickingInfo || new BABYLON.PickingInfo();
  25175. };
  25176. /** Launch a ray to try to pick a mesh in the scene
  25177. * @param x position on screen
  25178. * @param y position on screen
  25179. * @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
  25180. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  25181. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  25182. */
  25183. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  25184. var _this = this;
  25185. if (!BABYLON.PickingInfo) {
  25186. return null;
  25187. }
  25188. return this._internalPick(function (world) {
  25189. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  25190. return _this._tempPickingRay;
  25191. }, predicate, fastCheck);
  25192. };
  25193. /** Launch a ray to try to pick a sprite in the scene
  25194. * @param x position on screen
  25195. * @param y position on screen
  25196. * @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
  25197. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  25198. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  25199. */
  25200. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  25201. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera);
  25202. return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera);
  25203. };
  25204. /** Use the given ray to pick a mesh in the scene
  25205. * @param ray The ray to use to pick meshes
  25206. * @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
  25207. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  25208. */
  25209. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  25210. var _this = this;
  25211. return this._internalPick(function (world) {
  25212. if (!_this._pickWithRayInverseMatrix) {
  25213. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  25214. }
  25215. world.invertToRef(_this._pickWithRayInverseMatrix);
  25216. if (!_this._cachedRayForTransform) {
  25217. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  25218. }
  25219. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  25220. return _this._cachedRayForTransform;
  25221. }, predicate, fastCheck);
  25222. };
  25223. /**
  25224. * Launch a ray to try to pick a mesh in the scene
  25225. * @param x X position on screen
  25226. * @param y Y position on screen
  25227. * @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
  25228. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  25229. */
  25230. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  25231. var _this = this;
  25232. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  25233. };
  25234. /**
  25235. * Launch a ray to try to pick a mesh in the scene
  25236. * @param ray Ray to use
  25237. * @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
  25238. */
  25239. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  25240. var _this = this;
  25241. return this._internalMultiPick(function (world) {
  25242. if (!_this._pickWithRayInverseMatrix) {
  25243. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  25244. }
  25245. world.invertToRef(_this._pickWithRayInverseMatrix);
  25246. if (!_this._cachedRayForTransform) {
  25247. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  25248. }
  25249. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  25250. return _this._cachedRayForTransform;
  25251. }, predicate);
  25252. };
  25253. Scene.prototype.setPointerOverMesh = function (mesh) {
  25254. if (this._pointerOverMesh === mesh) {
  25255. return;
  25256. }
  25257. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  25258. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  25259. }
  25260. this._pointerOverMesh = mesh;
  25261. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  25262. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  25263. }
  25264. };
  25265. Scene.prototype.getPointerOverMesh = function () {
  25266. return this._pointerOverMesh;
  25267. };
  25268. Scene.prototype.setPointerOverSprite = function (sprite) {
  25269. if (this._pointerOverSprite === sprite) {
  25270. return;
  25271. }
  25272. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  25273. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  25274. }
  25275. this._pointerOverSprite = sprite;
  25276. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  25277. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  25278. }
  25279. };
  25280. Scene.prototype.getPointerOverSprite = function () {
  25281. return this._pointerOverSprite;
  25282. };
  25283. // Physics
  25284. Scene.prototype.getPhysicsEngine = function () {
  25285. return this._physicsEngine;
  25286. };
  25287. /**
  25288. * Enables physics to the current scene
  25289. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  25290. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  25291. * @return {boolean} was the physics engine initialized
  25292. */
  25293. Scene.prototype.enablePhysics = function (gravity, plugin) {
  25294. if (gravity === void 0) { gravity = null; }
  25295. if (this._physicsEngine) {
  25296. return true;
  25297. }
  25298. try {
  25299. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  25300. return true;
  25301. }
  25302. catch (e) {
  25303. BABYLON.Tools.Error(e.message);
  25304. return false;
  25305. }
  25306. };
  25307. Scene.prototype.disablePhysicsEngine = function () {
  25308. if (!this._physicsEngine) {
  25309. return;
  25310. }
  25311. this._physicsEngine.dispose();
  25312. this._physicsEngine = null;
  25313. };
  25314. Scene.prototype.isPhysicsEnabled = function () {
  25315. return this._physicsEngine !== undefined;
  25316. };
  25317. Scene.prototype.deleteCompoundImpostor = function (compound) {
  25318. var mesh = compound.parts[0].mesh;
  25319. if (mesh.physicsImpostor) {
  25320. mesh.physicsImpostor.dispose();
  25321. mesh.physicsImpostor = null;
  25322. }
  25323. };
  25324. // Misc.
  25325. Scene.prototype._rebuildGeometries = function () {
  25326. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  25327. var geometry = _a[_i];
  25328. geometry._rebuild();
  25329. }
  25330. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  25331. var mesh = _c[_b];
  25332. mesh._rebuild();
  25333. }
  25334. if (this.postProcessManager) {
  25335. this.postProcessManager._rebuild();
  25336. }
  25337. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  25338. var layer = _e[_d];
  25339. layer._rebuild();
  25340. }
  25341. for (var _f = 0, _g = this.effectLayers; _f < _g.length; _f++) {
  25342. var effectLayer = _g[_f];
  25343. effectLayer._rebuild();
  25344. }
  25345. if (this._boundingBoxRenderer) {
  25346. this._boundingBoxRenderer._rebuild();
  25347. }
  25348. for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) {
  25349. var system = _j[_h];
  25350. system.rebuild();
  25351. }
  25352. if (this._postProcessRenderPipelineManager) {
  25353. this._postProcessRenderPipelineManager._rebuild();
  25354. }
  25355. };
  25356. Scene.prototype._rebuildTextures = function () {
  25357. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  25358. var texture = _a[_i];
  25359. texture._rebuild();
  25360. }
  25361. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  25362. };
  25363. /**
  25364. * Creates a default light for the scene.
  25365. * @param replace Whether to replace the existing lights in the scene.
  25366. */
  25367. Scene.prototype.createDefaultLight = function (replace) {
  25368. if (replace === void 0) { replace = false; }
  25369. // Dispose existing light in replace mode.
  25370. if (replace) {
  25371. if (this.lights) {
  25372. for (var i = 0; i < this.lights.length; i++) {
  25373. this.lights[i].dispose();
  25374. }
  25375. }
  25376. }
  25377. // Light
  25378. if (this.lights.length === 0) {
  25379. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  25380. }
  25381. };
  25382. /**
  25383. * Creates a default camera for the scene.
  25384. * @param createArcRotateCamera Whether to create an arc rotate or a free camera.
  25385. * @param replace Whether to replace the existing active camera in the scene.
  25386. * @param attachCameraControls Whether to attach camera controls to the canvas.
  25387. */
  25388. Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  25389. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  25390. if (replace === void 0) { replace = false; }
  25391. if (attachCameraControls === void 0) { attachCameraControls = false; }
  25392. // Dispose existing camera in replace mode.
  25393. if (replace) {
  25394. if (this.activeCamera) {
  25395. this.activeCamera.dispose();
  25396. this.activeCamera = null;
  25397. }
  25398. }
  25399. // Camera
  25400. if (!this.activeCamera) {
  25401. var worldExtends = this.getWorldExtends();
  25402. var worldSize = worldExtends.max.subtract(worldExtends.min);
  25403. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  25404. var camera;
  25405. var radius = worldSize.length() * 1.5;
  25406. // empty scene scenario!
  25407. if (!isFinite(radius)) {
  25408. radius = 1;
  25409. worldCenter.copyFromFloats(0, 0, 0);
  25410. }
  25411. if (createArcRotateCamera) {
  25412. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  25413. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  25414. arcRotateCamera.wheelPrecision = 100 / radius;
  25415. camera = arcRotateCamera;
  25416. }
  25417. else {
  25418. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  25419. freeCamera.setTarget(worldCenter);
  25420. camera = freeCamera;
  25421. }
  25422. camera.minZ = radius * 0.01;
  25423. camera.maxZ = radius * 1000;
  25424. camera.speed = radius * 0.2;
  25425. this.activeCamera = camera;
  25426. var canvas = this.getEngine().getRenderingCanvas();
  25427. if (attachCameraControls && canvas) {
  25428. camera.attachControl(canvas);
  25429. }
  25430. }
  25431. };
  25432. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  25433. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  25434. if (replace === void 0) { replace = false; }
  25435. if (attachCameraControls === void 0) { attachCameraControls = false; }
  25436. this.createDefaultLight(replace);
  25437. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  25438. };
  25439. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur) {
  25440. if (pbr === void 0) { pbr = false; }
  25441. if (scale === void 0) { scale = 1000; }
  25442. if (blur === void 0) { blur = 0; }
  25443. if (environmentTexture) {
  25444. this.environmentTexture = environmentTexture;
  25445. }
  25446. if (!this.environmentTexture) {
  25447. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  25448. return null;
  25449. }
  25450. // Skybox
  25451. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  25452. if (pbr) {
  25453. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  25454. hdrSkyboxMaterial.backFaceCulling = false;
  25455. hdrSkyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  25456. if (hdrSkyboxMaterial.reflectionTexture) {
  25457. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  25458. }
  25459. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  25460. hdrSkyboxMaterial.disableLighting = true;
  25461. hdrSkyboxMaterial.twoSidedLighting = true;
  25462. hdrSkybox.infiniteDistance = true;
  25463. hdrSkybox.material = hdrSkyboxMaterial;
  25464. }
  25465. else {
  25466. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  25467. skyboxMaterial.backFaceCulling = false;
  25468. skyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  25469. if (skyboxMaterial.reflectionTexture) {
  25470. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  25471. }
  25472. skyboxMaterial.disableLighting = true;
  25473. hdrSkybox.infiniteDistance = true;
  25474. hdrSkybox.material = skyboxMaterial;
  25475. }
  25476. return hdrSkybox;
  25477. };
  25478. Scene.prototype.createDefaultEnvironment = function (options) {
  25479. if (BABYLON.EnvironmentHelper) {
  25480. return new BABYLON.EnvironmentHelper(options, this);
  25481. }
  25482. return null;
  25483. };
  25484. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  25485. if (webVROptions === void 0) { webVROptions = {}; }
  25486. return new BABYLON.VRExperienceHelper(this, webVROptions);
  25487. };
  25488. // Tags
  25489. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  25490. if (tagsQuery === undefined) {
  25491. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  25492. return list;
  25493. }
  25494. var listByTags = [];
  25495. forEach = forEach || (function (item) { return; });
  25496. for (var i in list) {
  25497. var item = list[i];
  25498. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  25499. listByTags.push(item);
  25500. forEach(item);
  25501. }
  25502. }
  25503. return listByTags;
  25504. };
  25505. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  25506. return this._getByTags(this.meshes, tagsQuery, forEach);
  25507. };
  25508. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  25509. return this._getByTags(this.cameras, tagsQuery, forEach);
  25510. };
  25511. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  25512. return this._getByTags(this.lights, tagsQuery, forEach);
  25513. };
  25514. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  25515. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  25516. };
  25517. /**
  25518. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  25519. * This allowed control for front to back rendering or reversly depending of the special needs.
  25520. *
  25521. * @param renderingGroupId The rendering group id corresponding to its index
  25522. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  25523. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  25524. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  25525. */
  25526. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  25527. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  25528. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  25529. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  25530. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  25531. };
  25532. /**
  25533. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  25534. *
  25535. * @param renderingGroupId The rendering group id corresponding to its index
  25536. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  25537. * @param depth Automatically clears depth between groups if true and autoClear is true.
  25538. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  25539. */
  25540. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  25541. if (depth === void 0) { depth = true; }
  25542. if (stencil === void 0) { stencil = true; }
  25543. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  25544. };
  25545. /**
  25546. * Will flag all materials as dirty to trigger new shader compilation
  25547. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  25548. */
  25549. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  25550. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  25551. var material = _a[_i];
  25552. if (predicate && !predicate(material)) {
  25553. continue;
  25554. }
  25555. material.markAsDirty(flag);
  25556. }
  25557. };
  25558. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  25559. var _this = this;
  25560. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  25561. this._activeRequests.push(request);
  25562. request.onCompleteObservable.add(function (request) {
  25563. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  25564. });
  25565. return request;
  25566. };
  25567. /** @ignore */
  25568. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  25569. var _this = this;
  25570. return new Promise(function (resolve, reject) {
  25571. _this._loadFile(url, function (data) {
  25572. resolve(data);
  25573. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  25574. reject(exception);
  25575. });
  25576. });
  25577. };
  25578. // Statics
  25579. Scene._FOGMODE_NONE = 0;
  25580. Scene._FOGMODE_EXP = 1;
  25581. Scene._FOGMODE_EXP2 = 2;
  25582. Scene._FOGMODE_LINEAR = 3;
  25583. Scene._uniqueIdCounter = 0;
  25584. Scene.MinDeltaTime = 1.0;
  25585. Scene.MaxDeltaTime = 1000.0;
  25586. /** The distance in pixel that you have to move to prevent some events */
  25587. Scene.DragMovementThreshold = 10; // in pixels
  25588. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  25589. Scene.LongPressDelay = 500; // in milliseconds
  25590. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  25591. Scene.DoubleClickDelay = 300; // in milliseconds
  25592. /** If you need to check double click without raising a single click at first click, enable this flag */
  25593. Scene.ExclusiveDoubleClickMode = false;
  25594. return Scene;
  25595. }());
  25596. BABYLON.Scene = Scene;
  25597. })(BABYLON || (BABYLON = {}));
  25598. //# sourceMappingURL=babylon.scene.js.map
  25599. var BABYLON;
  25600. (function (BABYLON) {
  25601. /**
  25602. * Set of assets to keep when moving a scene into an asset container.
  25603. */
  25604. var KeepAssets = /** @class */ (function () {
  25605. function KeepAssets() {
  25606. /**
  25607. * Cameras to keep.
  25608. */
  25609. this.cameras = new Array();
  25610. /**
  25611. * Lights to keep.
  25612. */
  25613. this.lights = new Array();
  25614. /**
  25615. * Meshes to keep.
  25616. */
  25617. this.meshes = new Array();
  25618. /**
  25619. * Skeletons to keep.
  25620. */
  25621. this.skeletons = new Array();
  25622. /**
  25623. * ParticleSystems to keep.
  25624. */
  25625. this.particleSystems = new Array();
  25626. /**
  25627. * Animations to keep.
  25628. */
  25629. this.animations = new Array();
  25630. /**
  25631. * MultiMaterials to keep.
  25632. */
  25633. this.multiMaterials = new Array();
  25634. /**
  25635. * Materials to keep.
  25636. */
  25637. this.materials = new Array();
  25638. /**
  25639. * MorphTargetManagers to keep.
  25640. */
  25641. this.morphTargetManagers = new Array();
  25642. /**
  25643. * Geometries to keep.
  25644. */
  25645. this.geometries = new Array();
  25646. /**
  25647. * TransformNodes to keep.
  25648. */
  25649. this.transformNodes = new Array();
  25650. /**
  25651. * LensFlareSystems to keep.
  25652. */
  25653. this.lensFlareSystems = new Array();
  25654. /**
  25655. * ShadowGenerators to keep.
  25656. */
  25657. this.shadowGenerators = new Array();
  25658. /**
  25659. * ActionManagers to keep.
  25660. */
  25661. this.actionManagers = new Array();
  25662. /**
  25663. * Sounds to keep.
  25664. */
  25665. this.sounds = new Array();
  25666. }
  25667. return KeepAssets;
  25668. }());
  25669. BABYLON.KeepAssets = KeepAssets;
  25670. /**
  25671. * Container with a set of assets that can be added or removed from a scene.
  25672. */
  25673. var AssetContainer = /** @class */ (function () {
  25674. /**
  25675. * Instantiates an AssetContainer.
  25676. * @param scene The scene the AssetContainer belongs to.
  25677. */
  25678. function AssetContainer(scene) {
  25679. // Objects
  25680. /**
  25681. * Cameras populated in the container.
  25682. */
  25683. this.cameras = new Array();
  25684. /**
  25685. * Lights populated in the container.
  25686. */
  25687. this.lights = new Array();
  25688. /**
  25689. * Meshes populated in the container.
  25690. */
  25691. this.meshes = new Array();
  25692. /**
  25693. * Skeletons populated in the container.
  25694. */
  25695. this.skeletons = new Array();
  25696. /**
  25697. * ParticleSystems populated in the container.
  25698. */
  25699. this.particleSystems = new Array();
  25700. /**
  25701. * Animations populated in the container.
  25702. */
  25703. this.animations = new Array();
  25704. /**
  25705. * MultiMaterials populated in the container.
  25706. */
  25707. this.multiMaterials = new Array();
  25708. /**
  25709. * Materials populated in the container.
  25710. */
  25711. this.materials = new Array();
  25712. /**
  25713. * MorphTargetManagers populated in the container.
  25714. */
  25715. this.morphTargetManagers = new Array();
  25716. /**
  25717. * Geometries populated in the container.
  25718. */
  25719. this.geometries = new Array();
  25720. /**
  25721. * TransformNodes populated in the container.
  25722. */
  25723. this.transformNodes = new Array();
  25724. /**
  25725. * LensFlareSystems populated in the container.
  25726. */
  25727. this.lensFlareSystems = new Array();
  25728. /**
  25729. * ShadowGenerators populated in the container.
  25730. */
  25731. this.shadowGenerators = new Array();
  25732. /**
  25733. * ActionManagers populated in the container.
  25734. */
  25735. this.actionManagers = new Array();
  25736. /**
  25737. * Sounds populated in the container.
  25738. */
  25739. this.sounds = new Array();
  25740. this.scene = scene;
  25741. }
  25742. /**
  25743. * Adds all the assets from the container to the scene.
  25744. */
  25745. AssetContainer.prototype.addAllToScene = function () {
  25746. var _this = this;
  25747. this.cameras.forEach(function (o) {
  25748. _this.scene.addCamera(o);
  25749. });
  25750. this.lights.forEach(function (o) {
  25751. _this.scene.addLight(o);
  25752. });
  25753. this.meshes.forEach(function (o) {
  25754. _this.scene.addMesh(o);
  25755. });
  25756. this.skeletons.forEach(function (o) {
  25757. _this.scene.addSkeleton(o);
  25758. });
  25759. this.particleSystems.forEach(function (o) {
  25760. _this.scene.addParticleSystem(o);
  25761. });
  25762. this.animations.forEach(function (o) {
  25763. _this.scene.addAnimation(o);
  25764. });
  25765. this.multiMaterials.forEach(function (o) {
  25766. _this.scene.addMultiMaterial(o);
  25767. });
  25768. this.materials.forEach(function (o) {
  25769. _this.scene.addMaterial(o);
  25770. });
  25771. this.morphTargetManagers.forEach(function (o) {
  25772. _this.scene.addMorphTargetManager(o);
  25773. });
  25774. this.geometries.forEach(function (o) {
  25775. _this.scene.addGeometry(o);
  25776. });
  25777. this.transformNodes.forEach(function (o) {
  25778. _this.scene.addTransformNode(o);
  25779. });
  25780. this.lensFlareSystems.forEach(function (o) {
  25781. _this.scene.addLensFlareSystem(o);
  25782. });
  25783. this.actionManagers.forEach(function (o) {
  25784. _this.scene.addActionManager(o);
  25785. });
  25786. this.sounds.forEach(function (o) {
  25787. o.play();
  25788. o.autoplay = true;
  25789. _this.scene.mainSoundTrack.AddSound(o);
  25790. });
  25791. };
  25792. /**
  25793. * Removes all the assets in the container from the scene
  25794. */
  25795. AssetContainer.prototype.removeAllFromScene = function () {
  25796. var _this = this;
  25797. this.cameras.forEach(function (o) {
  25798. _this.scene.removeCamera(o);
  25799. });
  25800. this.lights.forEach(function (o) {
  25801. _this.scene.removeLight(o);
  25802. });
  25803. this.meshes.forEach(function (o) {
  25804. _this.scene.removeMesh(o);
  25805. });
  25806. this.skeletons.forEach(function (o) {
  25807. _this.scene.removeSkeleton(o);
  25808. });
  25809. this.particleSystems.forEach(function (o) {
  25810. _this.scene.removeParticleSystem(o);
  25811. });
  25812. this.animations.forEach(function (o) {
  25813. _this.scene.removeAnimation(o);
  25814. });
  25815. this.multiMaterials.forEach(function (o) {
  25816. _this.scene.removeMultiMaterial(o);
  25817. });
  25818. this.materials.forEach(function (o) {
  25819. _this.scene.removeMaterial(o);
  25820. });
  25821. this.morphTargetManagers.forEach(function (o) {
  25822. _this.scene.removeMorphTargetManager(o);
  25823. });
  25824. this.geometries.forEach(function (o) {
  25825. _this.scene.removeGeometry(o);
  25826. });
  25827. this.transformNodes.forEach(function (o) {
  25828. _this.scene.removeTransformNode(o);
  25829. });
  25830. this.lensFlareSystems.forEach(function (o) {
  25831. _this.scene.removeLensFlareSystem(o);
  25832. });
  25833. this.actionManagers.forEach(function (o) {
  25834. _this.scene.removeActionManager(o);
  25835. });
  25836. this.sounds.forEach(function (o) {
  25837. o.stop();
  25838. o.autoplay = false;
  25839. _this.scene.mainSoundTrack.RemoveSound(o);
  25840. });
  25841. };
  25842. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  25843. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  25844. var asset = sourceAssets_1[_i];
  25845. var move = true;
  25846. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  25847. var keepAsset = keepAssets_1[_a];
  25848. if (asset === keepAsset) {
  25849. move = false;
  25850. break;
  25851. }
  25852. }
  25853. if (move) {
  25854. targetAssets.push(asset);
  25855. }
  25856. }
  25857. };
  25858. /**
  25859. * Removes all the assets contained in the scene and adds them to the container.
  25860. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  25861. */
  25862. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  25863. if (keepAssets === undefined) {
  25864. keepAssets = new KeepAssets();
  25865. }
  25866. this._moveAssets(this.scene.cameras, this.cameras, keepAssets.cameras);
  25867. this._moveAssets(this.scene.meshes, this.meshes, keepAssets.meshes);
  25868. this._moveAssets(this.scene.getGeometries(), this.geometries, keepAssets.geometries);
  25869. this._moveAssets(this.scene.materials, this.materials, keepAssets.materials);
  25870. this._moveAssets(this.scene._actionManagers, this.actionManagers, keepAssets.actionManagers);
  25871. this._moveAssets(this.scene.animations, this.animations, keepAssets.animations);
  25872. this._moveAssets(this.scene.lensFlareSystems, this.lensFlareSystems, keepAssets.lensFlareSystems);
  25873. this._moveAssets(this.scene.lights, this.lights, keepAssets.lights);
  25874. this._moveAssets(this.scene.morphTargetManagers, this.morphTargetManagers, keepAssets.morphTargetManagers);
  25875. this._moveAssets(this.scene.multiMaterials, this.multiMaterials, keepAssets.multiMaterials);
  25876. this._moveAssets(this.scene.skeletons, this.skeletons, keepAssets.skeletons);
  25877. this._moveAssets(this.scene.particleSystems, this.particleSystems, keepAssets.particleSystems);
  25878. this._moveAssets(this.scene.mainSoundTrack.soundCollection, this.sounds, keepAssets.sounds);
  25879. this._moveAssets(this.scene.transformNodes, this.transformNodes, keepAssets.transformNodes);
  25880. this.removeAllFromScene();
  25881. };
  25882. return AssetContainer;
  25883. }());
  25884. BABYLON.AssetContainer = AssetContainer;
  25885. })(BABYLON || (BABYLON = {}));
  25886. //# sourceMappingURL=babylon.assetContainer.js.map
  25887. var BABYLON;
  25888. (function (BABYLON) {
  25889. var Buffer = /** @class */ (function () {
  25890. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  25891. if (instanced === void 0) { instanced = false; }
  25892. if (engine instanceof BABYLON.Mesh) {
  25893. this._engine = engine.getScene().getEngine();
  25894. }
  25895. else {
  25896. this._engine = engine;
  25897. }
  25898. this._updatable = updatable;
  25899. this._instanced = instanced;
  25900. this._data = data;
  25901. this._strideSize = stride;
  25902. if (!postponeInternalCreation) {
  25903. this.create();
  25904. }
  25905. }
  25906. /**
  25907. * Create a new {BABYLON.VertexBuffer} based on the current buffer
  25908. * @param kind defines the vertex buffer kind (position, normal, etc.)
  25909. * @param offset defines offset in the buffer (0 by default)
  25910. * @param size defines the size in floats of attributes (position is 3 for instance)
  25911. * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved)
  25912. * @param instanced defines if the vertex buffer contains indexed data
  25913. * @returns the new vertex buffer
  25914. */
  25915. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride, instanced) {
  25916. // a lot of these parameters are ignored as they are overriden by the buffer
  25917. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, instanced === undefined ? this._instanced : instanced, offset, size);
  25918. };
  25919. // Properties
  25920. Buffer.prototype.isUpdatable = function () {
  25921. return this._updatable;
  25922. };
  25923. Buffer.prototype.getData = function () {
  25924. return this._data;
  25925. };
  25926. Buffer.prototype.getBuffer = function () {
  25927. return this._buffer;
  25928. };
  25929. Buffer.prototype.getStrideSize = function () {
  25930. return this._strideSize;
  25931. };
  25932. // public getIsInstanced(): boolean {
  25933. // return this._instanced;
  25934. // }
  25935. // public get instanceDivisor(): number {
  25936. // return this._instanceDivisor;
  25937. // }
  25938. // public set instanceDivisor(value: number) {
  25939. // this._instanceDivisor = value;
  25940. // if (value == 0) {
  25941. // this._instanced = false;
  25942. // } else {
  25943. // this._instanced = true;
  25944. // }
  25945. // }
  25946. // Methods
  25947. Buffer.prototype.create = function (data) {
  25948. if (data === void 0) { data = null; }
  25949. if (!data && this._buffer) {
  25950. return; // nothing to do
  25951. }
  25952. data = data || this._data;
  25953. if (!data) {
  25954. return;
  25955. }
  25956. if (!this._buffer) {
  25957. if (this._updatable) {
  25958. this._buffer = this._engine.createDynamicVertexBuffer(data);
  25959. this._data = data;
  25960. }
  25961. else {
  25962. this._buffer = this._engine.createVertexBuffer(data);
  25963. }
  25964. }
  25965. else if (this._updatable) {
  25966. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  25967. this._data = data;
  25968. }
  25969. };
  25970. Buffer.prototype._rebuild = function () {
  25971. this._buffer = null;
  25972. this.create(this._data);
  25973. };
  25974. Buffer.prototype.update = function (data) {
  25975. this.create(data);
  25976. };
  25977. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  25978. if (!this._buffer) {
  25979. return;
  25980. }
  25981. if (this._updatable) {
  25982. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  25983. this._data = null;
  25984. }
  25985. };
  25986. Buffer.prototype.dispose = function () {
  25987. if (!this._buffer) {
  25988. return;
  25989. }
  25990. if (this._engine._releaseBuffer(this._buffer)) {
  25991. this._buffer = null;
  25992. }
  25993. };
  25994. return Buffer;
  25995. }());
  25996. BABYLON.Buffer = Buffer;
  25997. })(BABYLON || (BABYLON = {}));
  25998. //# sourceMappingURL=babylon.buffer.js.map
  25999. var BABYLON;
  26000. (function (BABYLON) {
  26001. var VertexBuffer = /** @class */ (function () {
  26002. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  26003. if (data instanceof BABYLON.Buffer) {
  26004. if (!stride) {
  26005. stride = data.getStrideSize();
  26006. }
  26007. this._buffer = data;
  26008. this._ownsBuffer = false;
  26009. }
  26010. else {
  26011. if (!stride) {
  26012. stride = VertexBuffer.DeduceStride(kind);
  26013. }
  26014. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  26015. this._ownsBuffer = true;
  26016. }
  26017. this._stride = stride;
  26018. this._instanced = instanced !== undefined ? instanced : false;
  26019. this._instanceDivisor = instanced ? 1 : 0;
  26020. this._offset = offset ? offset : 0;
  26021. this._size = size ? size : stride;
  26022. this._kind = kind;
  26023. }
  26024. Object.defineProperty(VertexBuffer.prototype, "instanceDivisor", {
  26025. /**
  26026. * Gets or sets the instance divisor when in instanced mode
  26027. */
  26028. get: function () {
  26029. return this._instanceDivisor;
  26030. },
  26031. set: function (value) {
  26032. this._instanceDivisor = value;
  26033. if (value == 0) {
  26034. this._instanced = false;
  26035. }
  26036. else {
  26037. this._instanced = true;
  26038. }
  26039. },
  26040. enumerable: true,
  26041. configurable: true
  26042. });
  26043. VertexBuffer.prototype._rebuild = function () {
  26044. if (!this._buffer) {
  26045. return;
  26046. }
  26047. this._buffer._rebuild();
  26048. };
  26049. /**
  26050. * Returns the kind of the VertexBuffer (string).
  26051. */
  26052. VertexBuffer.prototype.getKind = function () {
  26053. return this._kind;
  26054. };
  26055. // Properties
  26056. /**
  26057. * Boolean : is the VertexBuffer updatable ?
  26058. */
  26059. VertexBuffer.prototype.isUpdatable = function () {
  26060. return this._buffer.isUpdatable();
  26061. };
  26062. /**
  26063. * Returns an array of numbers or a Float32Array containing the VertexBuffer data.
  26064. */
  26065. VertexBuffer.prototype.getData = function () {
  26066. return this._buffer.getData();
  26067. };
  26068. /**
  26069. * Returns the WebGLBuffer associated to the VertexBuffer.
  26070. */
  26071. VertexBuffer.prototype.getBuffer = function () {
  26072. return this._buffer.getBuffer();
  26073. };
  26074. /**
  26075. * Returns the stride of the VertexBuffer (integer).
  26076. */
  26077. VertexBuffer.prototype.getStrideSize = function () {
  26078. return this._stride;
  26079. };
  26080. /**
  26081. * Returns the offset (integer).
  26082. */
  26083. VertexBuffer.prototype.getOffset = function () {
  26084. return this._offset;
  26085. };
  26086. /**
  26087. * Returns the VertexBuffer total size (integer).
  26088. */
  26089. VertexBuffer.prototype.getSize = function () {
  26090. return this._size;
  26091. };
  26092. /**
  26093. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  26094. */
  26095. VertexBuffer.prototype.getIsInstanced = function () {
  26096. return this._instanced;
  26097. };
  26098. /**
  26099. * Returns the instancing divisor, zero for non-instanced (integer).
  26100. */
  26101. VertexBuffer.prototype.getInstanceDivisor = function () {
  26102. return this._instanceDivisor;
  26103. };
  26104. // Methods
  26105. /**
  26106. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  26107. * Returns the created WebGLBuffer.
  26108. */
  26109. VertexBuffer.prototype.create = function (data) {
  26110. return this._buffer.create(data);
  26111. };
  26112. /**
  26113. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  26114. * This function will create a new buffer if the current one is not updatable
  26115. * Returns the updated WebGLBuffer.
  26116. */
  26117. VertexBuffer.prototype.update = function (data) {
  26118. return this._buffer.update(data);
  26119. };
  26120. /**
  26121. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  26122. * Returns the directly updated WebGLBuffer.
  26123. */
  26124. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  26125. return this._buffer.updateDirectly(data, offset);
  26126. };
  26127. /**
  26128. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  26129. */
  26130. VertexBuffer.prototype.dispose = function () {
  26131. if (this._ownsBuffer) {
  26132. this._buffer.dispose();
  26133. }
  26134. };
  26135. Object.defineProperty(VertexBuffer, "PositionKind", {
  26136. get: function () {
  26137. return VertexBuffer._PositionKind;
  26138. },
  26139. enumerable: true,
  26140. configurable: true
  26141. });
  26142. Object.defineProperty(VertexBuffer, "NormalKind", {
  26143. get: function () {
  26144. return VertexBuffer._NormalKind;
  26145. },
  26146. enumerable: true,
  26147. configurable: true
  26148. });
  26149. Object.defineProperty(VertexBuffer, "TangentKind", {
  26150. get: function () {
  26151. return VertexBuffer._TangentKind;
  26152. },
  26153. enumerable: true,
  26154. configurable: true
  26155. });
  26156. Object.defineProperty(VertexBuffer, "UVKind", {
  26157. get: function () {
  26158. return VertexBuffer._UVKind;
  26159. },
  26160. enumerable: true,
  26161. configurable: true
  26162. });
  26163. Object.defineProperty(VertexBuffer, "UV2Kind", {
  26164. get: function () {
  26165. return VertexBuffer._UV2Kind;
  26166. },
  26167. enumerable: true,
  26168. configurable: true
  26169. });
  26170. Object.defineProperty(VertexBuffer, "UV3Kind", {
  26171. get: function () {
  26172. return VertexBuffer._UV3Kind;
  26173. },
  26174. enumerable: true,
  26175. configurable: true
  26176. });
  26177. Object.defineProperty(VertexBuffer, "UV4Kind", {
  26178. get: function () {
  26179. return VertexBuffer._UV4Kind;
  26180. },
  26181. enumerable: true,
  26182. configurable: true
  26183. });
  26184. Object.defineProperty(VertexBuffer, "UV5Kind", {
  26185. get: function () {
  26186. return VertexBuffer._UV5Kind;
  26187. },
  26188. enumerable: true,
  26189. configurable: true
  26190. });
  26191. Object.defineProperty(VertexBuffer, "UV6Kind", {
  26192. get: function () {
  26193. return VertexBuffer._UV6Kind;
  26194. },
  26195. enumerable: true,
  26196. configurable: true
  26197. });
  26198. Object.defineProperty(VertexBuffer, "ColorKind", {
  26199. get: function () {
  26200. return VertexBuffer._ColorKind;
  26201. },
  26202. enumerable: true,
  26203. configurable: true
  26204. });
  26205. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  26206. get: function () {
  26207. return VertexBuffer._MatricesIndicesKind;
  26208. },
  26209. enumerable: true,
  26210. configurable: true
  26211. });
  26212. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  26213. get: function () {
  26214. return VertexBuffer._MatricesWeightsKind;
  26215. },
  26216. enumerable: true,
  26217. configurable: true
  26218. });
  26219. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  26220. get: function () {
  26221. return VertexBuffer._MatricesIndicesExtraKind;
  26222. },
  26223. enumerable: true,
  26224. configurable: true
  26225. });
  26226. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  26227. get: function () {
  26228. return VertexBuffer._MatricesWeightsExtraKind;
  26229. },
  26230. enumerable: true,
  26231. configurable: true
  26232. });
  26233. /**
  26234. * Deduces the stride given a kind.
  26235. * @param kind The kind string to deduce
  26236. * @returns The deduced stride
  26237. */
  26238. VertexBuffer.DeduceStride = function (kind) {
  26239. switch (kind) {
  26240. case VertexBuffer.UVKind:
  26241. case VertexBuffer.UV2Kind:
  26242. case VertexBuffer.UV3Kind:
  26243. case VertexBuffer.UV4Kind:
  26244. case VertexBuffer.UV5Kind:
  26245. case VertexBuffer.UV6Kind:
  26246. return 2;
  26247. case VertexBuffer.NormalKind:
  26248. case VertexBuffer.PositionKind:
  26249. return 3;
  26250. case VertexBuffer.ColorKind:
  26251. case VertexBuffer.MatricesIndicesKind:
  26252. case VertexBuffer.MatricesIndicesExtraKind:
  26253. case VertexBuffer.MatricesWeightsKind:
  26254. case VertexBuffer.MatricesWeightsExtraKind:
  26255. case VertexBuffer.TangentKind:
  26256. return 4;
  26257. default:
  26258. throw new Error("Invalid kind '" + kind + "'");
  26259. }
  26260. };
  26261. // Enums
  26262. VertexBuffer._PositionKind = "position";
  26263. VertexBuffer._NormalKind = "normal";
  26264. VertexBuffer._TangentKind = "tangent";
  26265. VertexBuffer._UVKind = "uv";
  26266. VertexBuffer._UV2Kind = "uv2";
  26267. VertexBuffer._UV3Kind = "uv3";
  26268. VertexBuffer._UV4Kind = "uv4";
  26269. VertexBuffer._UV5Kind = "uv5";
  26270. VertexBuffer._UV6Kind = "uv6";
  26271. VertexBuffer._ColorKind = "color";
  26272. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  26273. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  26274. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  26275. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  26276. return VertexBuffer;
  26277. }());
  26278. BABYLON.VertexBuffer = VertexBuffer;
  26279. })(BABYLON || (BABYLON = {}));
  26280. //# sourceMappingURL=babylon.vertexBuffer.js.map
  26281. var BABYLON;
  26282. (function (BABYLON) {
  26283. /**
  26284. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  26285. */
  26286. var DummyInternalTextureTracker = /** @class */ (function () {
  26287. function DummyInternalTextureTracker() {
  26288. /**
  26289. * Gets or set the previous tracker in the list
  26290. */
  26291. this.previous = null;
  26292. /**
  26293. * Gets or set the next tracker in the list
  26294. */
  26295. this.next = null;
  26296. }
  26297. return DummyInternalTextureTracker;
  26298. }());
  26299. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  26300. })(BABYLON || (BABYLON = {}));
  26301. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  26302. var BABYLON;
  26303. (function (BABYLON) {
  26304. /**
  26305. * Class used to store data associated with WebGL texture data for the engine
  26306. * This class should not be used directly
  26307. */
  26308. var InternalTexture = /** @class */ (function () {
  26309. /**
  26310. * Creates a new InternalTexture
  26311. * @param engine defines the engine to use
  26312. * @param dataSource defines the type of data that will be used
  26313. */
  26314. function InternalTexture(engine, dataSource) {
  26315. /**
  26316. * Observable called when the texture is loaded
  26317. */
  26318. this.onLoadedObservable = new BABYLON.Observable();
  26319. /**
  26320. * Gets or set the previous tracker in the list
  26321. */
  26322. this.previous = null;
  26323. /**
  26324. * Gets or set the next tracker in the list
  26325. */
  26326. this.next = null;
  26327. // Private
  26328. /** @ignore */
  26329. this._initialSlot = -1;
  26330. /** @ignore */
  26331. this._designatedSlot = -1;
  26332. /** @ignore */
  26333. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  26334. /** @ignore */
  26335. this._comparisonFunction = 0;
  26336. /** @ignore */
  26337. this._references = 1;
  26338. this._engine = engine;
  26339. this._dataSource = dataSource;
  26340. this._webGLTexture = engine._createTexture();
  26341. }
  26342. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  26343. /**
  26344. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  26345. */
  26346. get: function () {
  26347. return this._dataSource;
  26348. },
  26349. enumerable: true,
  26350. configurable: true
  26351. });
  26352. /**
  26353. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  26354. */
  26355. InternalTexture.prototype.incrementReferences = function () {
  26356. this._references++;
  26357. };
  26358. /**
  26359. * Change the size of the texture (not the size of the content)
  26360. * @param width defines the new width
  26361. * @param height defines the new height
  26362. * @param depth defines the new depth (1 by default)
  26363. */
  26364. InternalTexture.prototype.updateSize = function (width, height, depth) {
  26365. if (depth === void 0) { depth = 1; }
  26366. this.width = width;
  26367. this.height = height;
  26368. this.depth = depth;
  26369. this.baseWidth = width;
  26370. this.baseHeight = height;
  26371. this.baseDepth = depth;
  26372. this._size = width * height * depth;
  26373. };
  26374. /** @ignore */
  26375. InternalTexture.prototype._rebuild = function () {
  26376. var _this = this;
  26377. var proxy;
  26378. this.isReady = false;
  26379. this._cachedCoordinatesMode = null;
  26380. this._cachedWrapU = null;
  26381. this._cachedWrapV = null;
  26382. this._cachedAnisotropicFilteringLevel = null;
  26383. switch (this._dataSource) {
  26384. case InternalTexture.DATASOURCE_TEMP:
  26385. return;
  26386. case InternalTexture.DATASOURCE_URL:
  26387. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  26388. _this.isReady = true;
  26389. }, null, this._buffer, undefined, this.format);
  26390. proxy._swapAndDie(this);
  26391. return;
  26392. case InternalTexture.DATASOURCE_RAW:
  26393. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  26394. proxy._swapAndDie(this);
  26395. this.isReady = true;
  26396. return;
  26397. case InternalTexture.DATASOURCE_RAW3D:
  26398. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  26399. proxy._swapAndDie(this);
  26400. this.isReady = true;
  26401. return;
  26402. case InternalTexture.DATASOURCE_DYNAMIC:
  26403. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  26404. proxy._swapAndDie(this);
  26405. // The engine will make sure to update content so no need to flag it as isReady = true
  26406. return;
  26407. case InternalTexture.DATASOURCE_RENDERTARGET:
  26408. var options = new BABYLON.RenderTargetCreationOptions();
  26409. options.generateDepthBuffer = this._generateDepthBuffer;
  26410. options.generateMipMaps = this.generateMipMaps;
  26411. options.generateStencilBuffer = this._generateStencilBuffer;
  26412. options.samplingMode = this.samplingMode;
  26413. options.type = this.type;
  26414. if (this.isCube) {
  26415. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  26416. }
  26417. else {
  26418. var size = {
  26419. width: this.width,
  26420. height: this.height
  26421. };
  26422. proxy = this._engine.createRenderTargetTexture(size, options);
  26423. }
  26424. proxy._swapAndDie(this);
  26425. this.isReady = true;
  26426. return;
  26427. case InternalTexture.DATASOURCE_DEPTHTEXTURE:
  26428. var depthTextureOptions = {
  26429. bilinearFiltering: this.samplingMode !== BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  26430. comparisonFunction: this._comparisonFunction,
  26431. generateStencil: this._generateStencilBuffer,
  26432. };
  26433. if (this.isCube) {
  26434. proxy = this._engine.createDepthStencilTexture({ width: this.width, height: this.height }, depthTextureOptions);
  26435. }
  26436. else {
  26437. proxy = this._engine.createDepthStencilCubeTexture(this.width, depthTextureOptions);
  26438. }
  26439. proxy._swapAndDie(this);
  26440. this.isReady = true;
  26441. return;
  26442. case InternalTexture.DATASOURCE_CUBE:
  26443. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  26444. _this.isReady = true;
  26445. }, null, this.format, this._extension);
  26446. proxy._swapAndDie(this);
  26447. return;
  26448. case InternalTexture.DATASOURCE_CUBERAW:
  26449. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  26450. proxy._swapAndDie(this);
  26451. this.isReady = true;
  26452. return;
  26453. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  26454. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  26455. if (proxy) {
  26456. proxy._swapAndDie(_this);
  26457. }
  26458. _this.isReady = true;
  26459. }, null, this.format, this._extension);
  26460. return;
  26461. }
  26462. };
  26463. InternalTexture.prototype._swapAndDie = function (target) {
  26464. target._webGLTexture = this._webGLTexture;
  26465. if (this._framebuffer) {
  26466. target._framebuffer = this._framebuffer;
  26467. }
  26468. if (this._depthStencilBuffer) {
  26469. target._depthStencilBuffer = this._depthStencilBuffer;
  26470. }
  26471. if (this._lodTextureHigh) {
  26472. if (target._lodTextureHigh) {
  26473. target._lodTextureHigh.dispose();
  26474. }
  26475. target._lodTextureHigh = this._lodTextureHigh;
  26476. }
  26477. if (this._lodTextureMid) {
  26478. if (target._lodTextureMid) {
  26479. target._lodTextureMid.dispose();
  26480. }
  26481. target._lodTextureMid = this._lodTextureMid;
  26482. }
  26483. if (this._lodTextureLow) {
  26484. if (target._lodTextureLow) {
  26485. target._lodTextureLow.dispose();
  26486. }
  26487. target._lodTextureLow = this._lodTextureLow;
  26488. }
  26489. var cache = this._engine.getLoadedTexturesCache();
  26490. var index = cache.indexOf(this);
  26491. if (index !== -1) {
  26492. cache.splice(index, 1);
  26493. }
  26494. };
  26495. /**
  26496. * Dispose the current allocated resources
  26497. */
  26498. InternalTexture.prototype.dispose = function () {
  26499. if (!this._webGLTexture) {
  26500. return;
  26501. }
  26502. this._references--;
  26503. if (this._references === 0) {
  26504. this._engine._releaseTexture(this);
  26505. this._webGLTexture = null;
  26506. this.previous = null;
  26507. this.next = null;
  26508. }
  26509. };
  26510. /**
  26511. * The source of the texture data is unknown
  26512. */
  26513. InternalTexture.DATASOURCE_UNKNOWN = 0;
  26514. /**
  26515. * Texture data comes from an URL
  26516. */
  26517. InternalTexture.DATASOURCE_URL = 1;
  26518. /**
  26519. * Texture data is only used for temporary storage
  26520. */
  26521. InternalTexture.DATASOURCE_TEMP = 2;
  26522. /**
  26523. * Texture data comes from raw data (ArrayBuffer)
  26524. */
  26525. InternalTexture.DATASOURCE_RAW = 3;
  26526. /**
  26527. * Texture content is dynamic (video or dynamic texture)
  26528. */
  26529. InternalTexture.DATASOURCE_DYNAMIC = 4;
  26530. /**
  26531. * Texture content is generated by rendering to it
  26532. */
  26533. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  26534. /**
  26535. * Texture content is part of a multi render target process
  26536. */
  26537. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  26538. /**
  26539. * Texture data comes from a cube data file
  26540. */
  26541. InternalTexture.DATASOURCE_CUBE = 7;
  26542. /**
  26543. * Texture data comes from a raw cube data
  26544. */
  26545. InternalTexture.DATASOURCE_CUBERAW = 8;
  26546. /**
  26547. * Texture data come from a prefiltered cube data file
  26548. */
  26549. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  26550. /**
  26551. * Texture content is raw 3D data
  26552. */
  26553. InternalTexture.DATASOURCE_RAW3D = 10;
  26554. /**
  26555. * Texture content is a depth texture
  26556. */
  26557. InternalTexture.DATASOURCE_DEPTHTEXTURE = 11;
  26558. return InternalTexture;
  26559. }());
  26560. BABYLON.InternalTexture = InternalTexture;
  26561. })(BABYLON || (BABYLON = {}));
  26562. //# sourceMappingURL=babylon.internalTexture.js.map
  26563. var BABYLON;
  26564. (function (BABYLON) {
  26565. var BaseTexture = /** @class */ (function () {
  26566. function BaseTexture(scene) {
  26567. this._hasAlpha = false;
  26568. this.getAlphaFromRGB = false;
  26569. this.level = 1;
  26570. this.coordinatesIndex = 0;
  26571. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  26572. /**
  26573. * | Value | Type | Description |
  26574. * | ----- | ------------------ | ----------- |
  26575. * | 0 | CLAMP_ADDRESSMODE | |
  26576. * | 1 | WRAP_ADDRESSMODE | |
  26577. * | 2 | MIRROR_ADDRESSMODE | |
  26578. */
  26579. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  26580. /**
  26581. * | Value | Type | Description |
  26582. * | ----- | ------------------ | ----------- |
  26583. * | 0 | CLAMP_ADDRESSMODE | |
  26584. * | 1 | WRAP_ADDRESSMODE | |
  26585. * | 2 | MIRROR_ADDRESSMODE | |
  26586. */
  26587. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  26588. /**
  26589. * | Value | Type | Description |
  26590. * | ----- | ------------------ | ----------- |
  26591. * | 0 | CLAMP_ADDRESSMODE | |
  26592. * | 1 | WRAP_ADDRESSMODE | |
  26593. * | 2 | MIRROR_ADDRESSMODE | |
  26594. */
  26595. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  26596. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  26597. this.isCube = false;
  26598. this.is3D = false;
  26599. this.gammaSpace = true;
  26600. this.invertZ = false;
  26601. this.lodLevelInAlpha = false;
  26602. this.lodGenerationOffset = 0.0;
  26603. this.lodGenerationScale = 0.8;
  26604. this.isRenderTarget = false;
  26605. this.animations = new Array();
  26606. /**
  26607. * An event triggered when the texture is disposed.
  26608. * @type {BABYLON.Observable}
  26609. */
  26610. this.onDisposeObservable = new BABYLON.Observable();
  26611. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  26612. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  26613. if (this._scene) {
  26614. this._scene.textures.push(this);
  26615. }
  26616. this._uid = null;
  26617. }
  26618. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  26619. get: function () {
  26620. return this._hasAlpha;
  26621. },
  26622. set: function (value) {
  26623. if (this._hasAlpha === value) {
  26624. return;
  26625. }
  26626. this._hasAlpha = value;
  26627. if (this._scene) {
  26628. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  26629. }
  26630. },
  26631. enumerable: true,
  26632. configurable: true
  26633. });
  26634. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  26635. get: function () {
  26636. return this._coordinatesMode;
  26637. },
  26638. /**
  26639. * How a texture is mapped.
  26640. *
  26641. * | Value | Type | Description |
  26642. * | ----- | ----------------------------------- | ----------- |
  26643. * | 0 | EXPLICIT_MODE | |
  26644. * | 1 | SPHERICAL_MODE | |
  26645. * | 2 | PLANAR_MODE | |
  26646. * | 3 | CUBIC_MODE | |
  26647. * | 4 | PROJECTION_MODE | |
  26648. * | 5 | SKYBOX_MODE | |
  26649. * | 6 | INVCUBIC_MODE | |
  26650. * | 7 | EQUIRECTANGULAR_MODE | |
  26651. * | 8 | FIXED_EQUIRECTANGULAR_MODE | |
  26652. * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
  26653. */
  26654. set: function (value) {
  26655. if (this._coordinatesMode === value) {
  26656. return;
  26657. }
  26658. this._coordinatesMode = value;
  26659. if (this._scene) {
  26660. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  26661. }
  26662. },
  26663. enumerable: true,
  26664. configurable: true
  26665. });
  26666. Object.defineProperty(BaseTexture.prototype, "uid", {
  26667. get: function () {
  26668. if (!this._uid) {
  26669. this._uid = BABYLON.Tools.RandomId();
  26670. }
  26671. return this._uid;
  26672. },
  26673. enumerable: true,
  26674. configurable: true
  26675. });
  26676. BaseTexture.prototype.toString = function () {
  26677. return this.name;
  26678. };
  26679. BaseTexture.prototype.getClassName = function () {
  26680. return "BaseTexture";
  26681. };
  26682. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  26683. set: function (callback) {
  26684. if (this._onDisposeObserver) {
  26685. this.onDisposeObservable.remove(this._onDisposeObserver);
  26686. }
  26687. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  26688. },
  26689. enumerable: true,
  26690. configurable: true
  26691. });
  26692. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  26693. get: function () {
  26694. return true;
  26695. },
  26696. enumerable: true,
  26697. configurable: true
  26698. });
  26699. BaseTexture.prototype.getScene = function () {
  26700. return this._scene;
  26701. };
  26702. BaseTexture.prototype.getTextureMatrix = function () {
  26703. return BABYLON.Matrix.IdentityReadOnly;
  26704. };
  26705. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  26706. return BABYLON.Matrix.IdentityReadOnly;
  26707. };
  26708. BaseTexture.prototype.getInternalTexture = function () {
  26709. return this._texture;
  26710. };
  26711. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  26712. return !this.isBlocking || this.isReady();
  26713. };
  26714. BaseTexture.prototype.isReady = function () {
  26715. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  26716. this.delayLoad();
  26717. return false;
  26718. }
  26719. if (this._texture) {
  26720. return this._texture.isReady;
  26721. }
  26722. return false;
  26723. };
  26724. BaseTexture.prototype.getSize = function () {
  26725. if (this._texture && this._texture.width) {
  26726. return new BABYLON.Size(this._texture.width, this._texture.height);
  26727. }
  26728. if (this._texture && this._texture._size) {
  26729. return new BABYLON.Size(this._texture._size, this._texture._size);
  26730. }
  26731. return BABYLON.Size.Zero();
  26732. };
  26733. BaseTexture.prototype.getBaseSize = function () {
  26734. if (!this.isReady() || !this._texture)
  26735. return BABYLON.Size.Zero();
  26736. if (this._texture._size) {
  26737. return new BABYLON.Size(this._texture._size, this._texture._size);
  26738. }
  26739. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  26740. };
  26741. BaseTexture.prototype.scale = function (ratio) {
  26742. };
  26743. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  26744. get: function () {
  26745. return false;
  26746. },
  26747. enumerable: true,
  26748. configurable: true
  26749. });
  26750. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  26751. if (!this._scene) {
  26752. return null;
  26753. }
  26754. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  26755. for (var index = 0; index < texturesCache.length; index++) {
  26756. var texturesCacheEntry = texturesCache[index];
  26757. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  26758. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  26759. texturesCacheEntry.incrementReferences();
  26760. return texturesCacheEntry;
  26761. }
  26762. }
  26763. }
  26764. return null;
  26765. };
  26766. BaseTexture.prototype._rebuild = function () {
  26767. };
  26768. BaseTexture.prototype.delayLoad = function () {
  26769. };
  26770. BaseTexture.prototype.clone = function () {
  26771. return null;
  26772. };
  26773. Object.defineProperty(BaseTexture.prototype, "textureType", {
  26774. get: function () {
  26775. if (!this._texture) {
  26776. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  26777. }
  26778. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  26779. },
  26780. enumerable: true,
  26781. configurable: true
  26782. });
  26783. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  26784. get: function () {
  26785. if (!this._texture) {
  26786. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  26787. }
  26788. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  26789. },
  26790. enumerable: true,
  26791. configurable: true
  26792. });
  26793. BaseTexture.prototype.readPixels = function (faceIndex) {
  26794. if (faceIndex === void 0) { faceIndex = 0; }
  26795. if (!this._texture) {
  26796. return null;
  26797. }
  26798. var size = this.getSize();
  26799. var scene = this.getScene();
  26800. if (!scene) {
  26801. return null;
  26802. }
  26803. var engine = scene.getEngine();
  26804. if (this._texture.isCube) {
  26805. return engine._readTexturePixels(this._texture, size.width, size.height, faceIndex);
  26806. }
  26807. return engine._readTexturePixels(this._texture, size.width, size.height, -1);
  26808. };
  26809. BaseTexture.prototype.releaseInternalTexture = function () {
  26810. if (this._texture) {
  26811. this._texture.dispose();
  26812. this._texture = null;
  26813. }
  26814. };
  26815. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  26816. get: function () {
  26817. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  26818. return null;
  26819. }
  26820. if (!this._texture._sphericalPolynomial) {
  26821. this._texture._sphericalPolynomial =
  26822. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  26823. }
  26824. return this._texture._sphericalPolynomial;
  26825. },
  26826. set: function (value) {
  26827. if (this._texture) {
  26828. this._texture._sphericalPolynomial = value;
  26829. }
  26830. },
  26831. enumerable: true,
  26832. configurable: true
  26833. });
  26834. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  26835. get: function () {
  26836. if (this._texture) {
  26837. return this._texture._lodTextureHigh;
  26838. }
  26839. return null;
  26840. },
  26841. enumerable: true,
  26842. configurable: true
  26843. });
  26844. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  26845. get: function () {
  26846. if (this._texture) {
  26847. return this._texture._lodTextureMid;
  26848. }
  26849. return null;
  26850. },
  26851. enumerable: true,
  26852. configurable: true
  26853. });
  26854. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  26855. get: function () {
  26856. if (this._texture) {
  26857. return this._texture._lodTextureLow;
  26858. }
  26859. return null;
  26860. },
  26861. enumerable: true,
  26862. configurable: true
  26863. });
  26864. BaseTexture.prototype.dispose = function () {
  26865. if (!this._scene) {
  26866. return;
  26867. }
  26868. // Animations
  26869. this._scene.stopAnimation(this);
  26870. // Remove from scene
  26871. this._scene._removePendingData(this);
  26872. var index = this._scene.textures.indexOf(this);
  26873. if (index >= 0) {
  26874. this._scene.textures.splice(index, 1);
  26875. }
  26876. if (this._texture === undefined) {
  26877. return;
  26878. }
  26879. // Release
  26880. this.releaseInternalTexture();
  26881. // Callback
  26882. this.onDisposeObservable.notifyObservers(this);
  26883. this.onDisposeObservable.clear();
  26884. };
  26885. BaseTexture.prototype.serialize = function () {
  26886. if (!this.name) {
  26887. return null;
  26888. }
  26889. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  26890. // Animations
  26891. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  26892. return serializationObject;
  26893. };
  26894. BaseTexture.WhenAllReady = function (textures, callback) {
  26895. var numRemaining = textures.length;
  26896. if (numRemaining === 0) {
  26897. callback();
  26898. return;
  26899. }
  26900. var _loop_1 = function () {
  26901. texture = textures[i];
  26902. if (texture.isReady()) {
  26903. if (--numRemaining === 0) {
  26904. callback();
  26905. }
  26906. }
  26907. else {
  26908. onLoadObservable = texture.onLoadObservable;
  26909. var onLoadCallback_1 = function () {
  26910. onLoadObservable.removeCallback(onLoadCallback_1);
  26911. if (--numRemaining === 0) {
  26912. callback();
  26913. }
  26914. };
  26915. onLoadObservable.add(onLoadCallback_1);
  26916. }
  26917. };
  26918. var texture, onLoadObservable;
  26919. for (var i = 0; i < textures.length; i++) {
  26920. _loop_1();
  26921. }
  26922. };
  26923. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  26924. __decorate([
  26925. BABYLON.serialize()
  26926. ], BaseTexture.prototype, "name", void 0);
  26927. __decorate([
  26928. BABYLON.serialize("hasAlpha")
  26929. ], BaseTexture.prototype, "_hasAlpha", void 0);
  26930. __decorate([
  26931. BABYLON.serialize()
  26932. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  26933. __decorate([
  26934. BABYLON.serialize()
  26935. ], BaseTexture.prototype, "level", void 0);
  26936. __decorate([
  26937. BABYLON.serialize()
  26938. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  26939. __decorate([
  26940. BABYLON.serialize("coordinatesMode")
  26941. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  26942. __decorate([
  26943. BABYLON.serialize()
  26944. ], BaseTexture.prototype, "wrapU", void 0);
  26945. __decorate([
  26946. BABYLON.serialize()
  26947. ], BaseTexture.prototype, "wrapV", void 0);
  26948. __decorate([
  26949. BABYLON.serialize()
  26950. ], BaseTexture.prototype, "wrapR", void 0);
  26951. __decorate([
  26952. BABYLON.serialize()
  26953. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  26954. __decorate([
  26955. BABYLON.serialize()
  26956. ], BaseTexture.prototype, "isCube", void 0);
  26957. __decorate([
  26958. BABYLON.serialize()
  26959. ], BaseTexture.prototype, "is3D", void 0);
  26960. __decorate([
  26961. BABYLON.serialize()
  26962. ], BaseTexture.prototype, "gammaSpace", void 0);
  26963. __decorate([
  26964. BABYLON.serialize()
  26965. ], BaseTexture.prototype, "invertZ", void 0);
  26966. __decorate([
  26967. BABYLON.serialize()
  26968. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  26969. __decorate([
  26970. BABYLON.serialize()
  26971. ], BaseTexture.prototype, "lodGenerationOffset", void 0);
  26972. __decorate([
  26973. BABYLON.serialize()
  26974. ], BaseTexture.prototype, "lodGenerationScale", void 0);
  26975. __decorate([
  26976. BABYLON.serialize()
  26977. ], BaseTexture.prototype, "isRenderTarget", void 0);
  26978. return BaseTexture;
  26979. }());
  26980. BABYLON.BaseTexture = BaseTexture;
  26981. })(BABYLON || (BABYLON = {}));
  26982. //# sourceMappingURL=babylon.baseTexture.js.map
  26983. var BABYLON;
  26984. (function (BABYLON) {
  26985. var Texture = /** @class */ (function (_super) {
  26986. __extends(Texture, _super);
  26987. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  26988. if (noMipmap === void 0) { noMipmap = false; }
  26989. if (invertY === void 0) { invertY = true; }
  26990. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  26991. if (onLoad === void 0) { onLoad = null; }
  26992. if (onError === void 0) { onError = null; }
  26993. if (buffer === void 0) { buffer = null; }
  26994. if (deleteBuffer === void 0) { deleteBuffer = false; }
  26995. var _this = _super.call(this, scene) || this;
  26996. _this.uOffset = 0;
  26997. _this.vOffset = 0;
  26998. _this.uScale = 1.0;
  26999. _this.vScale = 1.0;
  27000. _this.uAng = 0;
  27001. _this.vAng = 0;
  27002. _this.wAng = 0;
  27003. _this._isBlocking = true;
  27004. _this.name = url || "";
  27005. _this.url = url;
  27006. _this._noMipmap = noMipmap;
  27007. _this._invertY = invertY;
  27008. _this._samplingMode = samplingMode;
  27009. _this._buffer = buffer;
  27010. _this._deleteBuffer = deleteBuffer;
  27011. if (format) {
  27012. _this._format = format;
  27013. }
  27014. scene = _this.getScene();
  27015. if (!scene) {
  27016. return _this;
  27017. }
  27018. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  27019. var load = function () {
  27020. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  27021. _this.onLoadObservable.notifyObservers(_this);
  27022. }
  27023. if (onLoad) {
  27024. onLoad();
  27025. }
  27026. if (!_this.isBlocking && scene) {
  27027. scene.resetCachedMaterial();
  27028. }
  27029. };
  27030. if (!_this.url) {
  27031. _this._delayedOnLoad = load;
  27032. _this._delayedOnError = onError;
  27033. return _this;
  27034. }
  27035. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  27036. if (!_this._texture) {
  27037. if (!scene.useDelayedTextureLoading) {
  27038. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  27039. if (deleteBuffer) {
  27040. delete _this._buffer;
  27041. }
  27042. }
  27043. else {
  27044. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  27045. _this._delayedOnLoad = load;
  27046. _this._delayedOnError = onError;
  27047. }
  27048. }
  27049. else {
  27050. if (_this._texture.isReady) {
  27051. BABYLON.Tools.SetImmediate(function () { return load(); });
  27052. }
  27053. else {
  27054. _this._texture.onLoadedObservable.add(load);
  27055. }
  27056. }
  27057. return _this;
  27058. }
  27059. Object.defineProperty(Texture.prototype, "noMipmap", {
  27060. get: function () {
  27061. return this._noMipmap;
  27062. },
  27063. enumerable: true,
  27064. configurable: true
  27065. });
  27066. Object.defineProperty(Texture.prototype, "isBlocking", {
  27067. get: function () {
  27068. return this._isBlocking;
  27069. },
  27070. set: function (value) {
  27071. this._isBlocking = value;
  27072. },
  27073. enumerable: true,
  27074. configurable: true
  27075. });
  27076. Object.defineProperty(Texture.prototype, "samplingMode", {
  27077. get: function () {
  27078. return this._samplingMode;
  27079. },
  27080. enumerable: true,
  27081. configurable: true
  27082. });
  27083. Texture.prototype.updateURL = function (url) {
  27084. this.url = url;
  27085. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  27086. this.delayLoad();
  27087. };
  27088. Texture.prototype.delayLoad = function () {
  27089. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  27090. return;
  27091. }
  27092. var scene = this.getScene();
  27093. if (!scene) {
  27094. return;
  27095. }
  27096. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  27097. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  27098. if (!this._texture) {
  27099. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  27100. if (this._deleteBuffer) {
  27101. delete this._buffer;
  27102. }
  27103. }
  27104. else {
  27105. if (this._delayedOnLoad) {
  27106. if (this._texture.isReady) {
  27107. BABYLON.Tools.SetImmediate(this._delayedOnLoad);
  27108. }
  27109. else {
  27110. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  27111. }
  27112. }
  27113. }
  27114. this._delayedOnLoad = null;
  27115. this._delayedOnError = null;
  27116. };
  27117. Texture.prototype.updateSamplingMode = function (samplingMode) {
  27118. if (!this._texture) {
  27119. return;
  27120. }
  27121. var scene = this.getScene();
  27122. if (!scene) {
  27123. return;
  27124. }
  27125. this._samplingMode = samplingMode;
  27126. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  27127. };
  27128. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  27129. x *= this.uScale;
  27130. y *= this.vScale;
  27131. x -= 0.5 * this.uScale;
  27132. y -= 0.5 * this.vScale;
  27133. z -= 0.5;
  27134. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  27135. t.x += 0.5 * this.uScale + this.uOffset;
  27136. t.y += 0.5 * this.vScale + this.vOffset;
  27137. t.z += 0.5;
  27138. };
  27139. Texture.prototype.getTextureMatrix = function () {
  27140. var _this = this;
  27141. if (this.uOffset === this._cachedUOffset &&
  27142. this.vOffset === this._cachedVOffset &&
  27143. this.uScale === this._cachedUScale &&
  27144. this.vScale === this._cachedVScale &&
  27145. this.uAng === this._cachedUAng &&
  27146. this.vAng === this._cachedVAng &&
  27147. this.wAng === this._cachedWAng) {
  27148. return this._cachedTextureMatrix;
  27149. }
  27150. this._cachedUOffset = this.uOffset;
  27151. this._cachedVOffset = this.vOffset;
  27152. this._cachedUScale = this.uScale;
  27153. this._cachedVScale = this.vScale;
  27154. this._cachedUAng = this.uAng;
  27155. this._cachedVAng = this.vAng;
  27156. this._cachedWAng = this.wAng;
  27157. if (!this._cachedTextureMatrix) {
  27158. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  27159. this._rowGenerationMatrix = new BABYLON.Matrix();
  27160. this._t0 = BABYLON.Vector3.Zero();
  27161. this._t1 = BABYLON.Vector3.Zero();
  27162. this._t2 = BABYLON.Vector3.Zero();
  27163. }
  27164. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  27165. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  27166. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  27167. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  27168. this._t1.subtractInPlace(this._t0);
  27169. this._t2.subtractInPlace(this._t0);
  27170. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  27171. this._cachedTextureMatrix.m[0] = this._t1.x;
  27172. this._cachedTextureMatrix.m[1] = this._t1.y;
  27173. this._cachedTextureMatrix.m[2] = this._t1.z;
  27174. this._cachedTextureMatrix.m[4] = this._t2.x;
  27175. this._cachedTextureMatrix.m[5] = this._t2.y;
  27176. this._cachedTextureMatrix.m[6] = this._t2.z;
  27177. this._cachedTextureMatrix.m[8] = this._t0.x;
  27178. this._cachedTextureMatrix.m[9] = this._t0.y;
  27179. this._cachedTextureMatrix.m[10] = this._t0.z;
  27180. var scene = this.getScene();
  27181. if (!scene) {
  27182. return this._cachedTextureMatrix;
  27183. }
  27184. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  27185. return mat.hasTexture(_this);
  27186. });
  27187. return this._cachedTextureMatrix;
  27188. };
  27189. Texture.prototype.getReflectionTextureMatrix = function () {
  27190. var _this = this;
  27191. var scene = this.getScene();
  27192. if (!scene) {
  27193. return this._cachedTextureMatrix;
  27194. }
  27195. if (this.uOffset === this._cachedUOffset &&
  27196. this.vOffset === this._cachedVOffset &&
  27197. this.uScale === this._cachedUScale &&
  27198. this.vScale === this._cachedVScale &&
  27199. this.coordinatesMode === this._cachedCoordinatesMode) {
  27200. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  27201. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  27202. return this._cachedTextureMatrix;
  27203. }
  27204. }
  27205. else {
  27206. return this._cachedTextureMatrix;
  27207. }
  27208. }
  27209. if (!this._cachedTextureMatrix) {
  27210. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  27211. }
  27212. if (!this._projectionModeMatrix) {
  27213. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  27214. }
  27215. this._cachedUOffset = this.uOffset;
  27216. this._cachedVOffset = this.vOffset;
  27217. this._cachedUScale = this.uScale;
  27218. this._cachedVScale = this.vScale;
  27219. this._cachedCoordinatesMode = this.coordinatesMode;
  27220. switch (this.coordinatesMode) {
  27221. case Texture.PLANAR_MODE:
  27222. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  27223. this._cachedTextureMatrix[0] = this.uScale;
  27224. this._cachedTextureMatrix[5] = this.vScale;
  27225. this._cachedTextureMatrix[12] = this.uOffset;
  27226. this._cachedTextureMatrix[13] = this.vOffset;
  27227. break;
  27228. case Texture.PROJECTION_MODE:
  27229. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  27230. this._projectionModeMatrix.m[0] = 0.5;
  27231. this._projectionModeMatrix.m[5] = -0.5;
  27232. this._projectionModeMatrix.m[10] = 0.0;
  27233. this._projectionModeMatrix.m[12] = 0.5;
  27234. this._projectionModeMatrix.m[13] = 0.5;
  27235. this._projectionModeMatrix.m[14] = 1.0;
  27236. this._projectionModeMatrix.m[15] = 1.0;
  27237. var projectionMatrix = scene.getProjectionMatrix();
  27238. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  27239. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  27240. break;
  27241. default:
  27242. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  27243. break;
  27244. }
  27245. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  27246. return (mat.getActiveTextures().indexOf(_this) !== -1);
  27247. });
  27248. return this._cachedTextureMatrix;
  27249. };
  27250. Texture.prototype.clone = function () {
  27251. var _this = this;
  27252. return BABYLON.SerializationHelper.Clone(function () {
  27253. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  27254. }, this);
  27255. };
  27256. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  27257. get: function () {
  27258. if (!this._onLoadObservable) {
  27259. this._onLoadObservable = new BABYLON.Observable();
  27260. }
  27261. return this._onLoadObservable;
  27262. },
  27263. enumerable: true,
  27264. configurable: true
  27265. });
  27266. Texture.prototype.serialize = function () {
  27267. var serializationObject = _super.prototype.serialize.call(this);
  27268. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  27269. serializationObject.base64String = this._buffer;
  27270. serializationObject.name = serializationObject.name.replace("data:", "");
  27271. }
  27272. return serializationObject;
  27273. };
  27274. Texture.prototype.getClassName = function () {
  27275. return "Texture";
  27276. };
  27277. Texture.prototype.dispose = function () {
  27278. _super.prototype.dispose.call(this);
  27279. if (this.onLoadObservable) {
  27280. this.onLoadObservable.clear();
  27281. this._onLoadObservable = null;
  27282. }
  27283. this._delayedOnLoad = null;
  27284. this._delayedOnError = null;
  27285. };
  27286. // Statics
  27287. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  27288. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  27289. if (onLoad === void 0) { onLoad = null; }
  27290. if (onError === void 0) { onError = null; }
  27291. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  27292. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  27293. };
  27294. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  27295. if (parsedTexture.customType) {
  27296. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  27297. // Update Sampling Mode
  27298. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  27299. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  27300. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  27301. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  27302. }
  27303. }
  27304. return parsedCustomTexture;
  27305. }
  27306. if (parsedTexture.isCube) {
  27307. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  27308. }
  27309. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  27310. return null;
  27311. }
  27312. var texture = BABYLON.SerializationHelper.Parse(function () {
  27313. var generateMipMaps = true;
  27314. if (parsedTexture.noMipmap) {
  27315. generateMipMaps = false;
  27316. }
  27317. if (parsedTexture.mirrorPlane) {
  27318. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  27319. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  27320. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  27321. return mirrorTexture;
  27322. }
  27323. else if (parsedTexture.isRenderTarget) {
  27324. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  27325. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  27326. return renderTargetTexture;
  27327. }
  27328. else {
  27329. var texture;
  27330. if (parsedTexture.base64String) {
  27331. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  27332. }
  27333. else {
  27334. var url = rootUrl + parsedTexture.name;
  27335. if (Texture.UseSerializedUrlIfAny && parsedTexture.url) {
  27336. url = parsedTexture.url;
  27337. }
  27338. texture = new Texture(url, scene, !generateMipMaps);
  27339. }
  27340. return texture;
  27341. }
  27342. }, parsedTexture, scene);
  27343. // Update Sampling Mode
  27344. if (parsedTexture.samplingMode) {
  27345. var sampling = parsedTexture.samplingMode;
  27346. if (texture._samplingMode !== sampling) {
  27347. texture.updateSamplingMode(sampling);
  27348. }
  27349. }
  27350. // Animations
  27351. if (parsedTexture.animations) {
  27352. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  27353. var parsedAnimation = parsedTexture.animations[animationIndex];
  27354. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  27355. }
  27356. }
  27357. return texture;
  27358. };
  27359. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  27360. if (deleteBuffer === void 0) { deleteBuffer = false; }
  27361. if (noMipmap === void 0) { noMipmap = false; }
  27362. if (invertY === void 0) { invertY = true; }
  27363. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  27364. if (onLoad === void 0) { onLoad = null; }
  27365. if (onError === void 0) { onError = null; }
  27366. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  27367. if (name.substr(0, 5) !== "data:") {
  27368. name = "data:" + name;
  27369. }
  27370. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  27371. };
  27372. // Constants
  27373. Texture.NEAREST_SAMPLINGMODE = 1;
  27374. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  27375. Texture.BILINEAR_SAMPLINGMODE = 2;
  27376. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  27377. Texture.TRILINEAR_SAMPLINGMODE = 3;
  27378. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  27379. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  27380. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  27381. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  27382. Texture.NEAREST_LINEAR = 7;
  27383. Texture.NEAREST_NEAREST = 8;
  27384. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  27385. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  27386. Texture.LINEAR_LINEAR = 11;
  27387. Texture.LINEAR_NEAREST = 12;
  27388. Texture.EXPLICIT_MODE = 0;
  27389. Texture.SPHERICAL_MODE = 1;
  27390. Texture.PLANAR_MODE = 2;
  27391. Texture.CUBIC_MODE = 3;
  27392. Texture.PROJECTION_MODE = 4;
  27393. Texture.SKYBOX_MODE = 5;
  27394. Texture.INVCUBIC_MODE = 6;
  27395. Texture.EQUIRECTANGULAR_MODE = 7;
  27396. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  27397. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  27398. Texture.CLAMP_ADDRESSMODE = 0;
  27399. Texture.WRAP_ADDRESSMODE = 1;
  27400. Texture.MIRROR_ADDRESSMODE = 2;
  27401. /**
  27402. * 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
  27403. */
  27404. Texture.UseSerializedUrlIfAny = false;
  27405. __decorate([
  27406. BABYLON.serialize()
  27407. ], Texture.prototype, "url", void 0);
  27408. __decorate([
  27409. BABYLON.serialize()
  27410. ], Texture.prototype, "uOffset", void 0);
  27411. __decorate([
  27412. BABYLON.serialize()
  27413. ], Texture.prototype, "vOffset", void 0);
  27414. __decorate([
  27415. BABYLON.serialize()
  27416. ], Texture.prototype, "uScale", void 0);
  27417. __decorate([
  27418. BABYLON.serialize()
  27419. ], Texture.prototype, "vScale", void 0);
  27420. __decorate([
  27421. BABYLON.serialize()
  27422. ], Texture.prototype, "uAng", void 0);
  27423. __decorate([
  27424. BABYLON.serialize()
  27425. ], Texture.prototype, "vAng", void 0);
  27426. __decorate([
  27427. BABYLON.serialize()
  27428. ], Texture.prototype, "wAng", void 0);
  27429. __decorate([
  27430. BABYLON.serialize()
  27431. ], Texture.prototype, "isBlocking", null);
  27432. return Texture;
  27433. }(BABYLON.BaseTexture));
  27434. BABYLON.Texture = Texture;
  27435. })(BABYLON || (BABYLON = {}));
  27436. //# sourceMappingURL=babylon.texture.js.map
  27437. var BABYLON;
  27438. (function (BABYLON) {
  27439. var _InstancesBatch = /** @class */ (function () {
  27440. function _InstancesBatch() {
  27441. this.mustReturn = false;
  27442. this.visibleInstances = new Array();
  27443. this.renderSelf = new Array();
  27444. }
  27445. return _InstancesBatch;
  27446. }());
  27447. BABYLON._InstancesBatch = _InstancesBatch;
  27448. var Mesh = /** @class */ (function (_super) {
  27449. __extends(Mesh, _super);
  27450. /**
  27451. * @constructor
  27452. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  27453. * @param {Scene} scene The scene to add this mesh to.
  27454. * @param {Node} parent The parent of this mesh, if it has one
  27455. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  27456. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  27457. * When false, achieved by calling a clone(), also passing False.
  27458. * This will make creation of children, recursive.
  27459. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  27460. */
  27461. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  27462. if (scene === void 0) { scene = null; }
  27463. if (parent === void 0) { parent = null; }
  27464. if (source === void 0) { source = null; }
  27465. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  27466. var _this = _super.call(this, name, scene) || this;
  27467. // Events
  27468. /**
  27469. * An event triggered before rendering the mesh
  27470. * @type {BABYLON.Observable}
  27471. */
  27472. _this.onBeforeRenderObservable = new BABYLON.Observable();
  27473. /**
  27474. * An event triggered after rendering the mesh
  27475. * @type {BABYLON.Observable}
  27476. */
  27477. _this.onAfterRenderObservable = new BABYLON.Observable();
  27478. /**
  27479. * An event triggered before drawing the mesh
  27480. * @type {BABYLON.Observable}
  27481. */
  27482. _this.onBeforeDrawObservable = new BABYLON.Observable();
  27483. // Members
  27484. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  27485. _this.instances = new Array();
  27486. _this._LODLevels = new Array();
  27487. _this._visibleInstances = {};
  27488. _this._renderIdForInstances = new Array();
  27489. _this._batchCache = new _InstancesBatch();
  27490. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  27491. // Use by builder only to know what orientation were the mesh build in.
  27492. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  27493. _this.overrideMaterialSideOrientation = null;
  27494. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  27495. // Will be used to save a source mesh reference, If any
  27496. _this._source = null;
  27497. scene = _this.getScene();
  27498. if (source) {
  27499. // Source mesh
  27500. _this._source = source;
  27501. // Geometry
  27502. if (source._geometry) {
  27503. source._geometry.applyToMesh(_this);
  27504. }
  27505. // Deep copy
  27506. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId", "source", "metadata"], ["_poseMatrix", "_source"]);
  27507. // Metadata
  27508. if (source.metadata && source.metadata.clone) {
  27509. _this.metadata = source.metadata.clone();
  27510. }
  27511. else {
  27512. _this.metadata = source.metadata;
  27513. }
  27514. // Tags
  27515. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  27516. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  27517. }
  27518. // Parent
  27519. _this.parent = source.parent;
  27520. // Pivot
  27521. _this.setPivotMatrix(source.getPivotMatrix());
  27522. _this.id = name + "." + source.id;
  27523. // Material
  27524. _this.material = source.material;
  27525. var index;
  27526. if (!doNotCloneChildren) {
  27527. // Children
  27528. var directDescendants = source.getDescendants(true);
  27529. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  27530. var child = directDescendants[index_1];
  27531. if (child.clone) {
  27532. child.clone(name + "." + child.name, _this);
  27533. }
  27534. }
  27535. }
  27536. // Physics clone
  27537. var physicsEngine = _this.getScene().getPhysicsEngine();
  27538. if (clonePhysicsImpostor && physicsEngine) {
  27539. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  27540. if (impostor) {
  27541. _this.physicsImpostor = impostor.clone(_this);
  27542. }
  27543. }
  27544. // Particles
  27545. for (index = 0; index < scene.particleSystems.length; index++) {
  27546. var system = scene.particleSystems[index];
  27547. if (system.emitter === source) {
  27548. system.clone(system.name, _this);
  27549. }
  27550. }
  27551. _this.computeWorldMatrix(true);
  27552. }
  27553. // Parent
  27554. if (parent !== null) {
  27555. _this.parent = parent;
  27556. }
  27557. return _this;
  27558. }
  27559. Object.defineProperty(Mesh, "FRONTSIDE", {
  27560. /**
  27561. * Mesh side orientation : usually the external or front surface
  27562. */
  27563. get: function () {
  27564. return Mesh._FRONTSIDE;
  27565. },
  27566. enumerable: true,
  27567. configurable: true
  27568. });
  27569. Object.defineProperty(Mesh, "BACKSIDE", {
  27570. /**
  27571. * Mesh side orientation : usually the internal or back surface
  27572. */
  27573. get: function () {
  27574. return Mesh._BACKSIDE;
  27575. },
  27576. enumerable: true,
  27577. configurable: true
  27578. });
  27579. Object.defineProperty(Mesh, "DOUBLESIDE", {
  27580. /**
  27581. * Mesh side orientation : both internal and external or front and back surfaces
  27582. */
  27583. get: function () {
  27584. return Mesh._DOUBLESIDE;
  27585. },
  27586. enumerable: true,
  27587. configurable: true
  27588. });
  27589. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  27590. /**
  27591. * Mesh side orientation : by default, `FRONTSIDE`
  27592. */
  27593. get: function () {
  27594. return Mesh._DEFAULTSIDE;
  27595. },
  27596. enumerable: true,
  27597. configurable: true
  27598. });
  27599. Object.defineProperty(Mesh, "NO_CAP", {
  27600. /**
  27601. * Mesh cap setting : no cap
  27602. */
  27603. get: function () {
  27604. return Mesh._NO_CAP;
  27605. },
  27606. enumerable: true,
  27607. configurable: true
  27608. });
  27609. Object.defineProperty(Mesh, "CAP_START", {
  27610. /**
  27611. * Mesh cap setting : one cap at the beginning of the mesh
  27612. */
  27613. get: function () {
  27614. return Mesh._CAP_START;
  27615. },
  27616. enumerable: true,
  27617. configurable: true
  27618. });
  27619. Object.defineProperty(Mesh, "CAP_END", {
  27620. /**
  27621. * Mesh cap setting : one cap at the end of the mesh
  27622. */
  27623. get: function () {
  27624. return Mesh._CAP_END;
  27625. },
  27626. enumerable: true,
  27627. configurable: true
  27628. });
  27629. Object.defineProperty(Mesh, "CAP_ALL", {
  27630. /**
  27631. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  27632. */
  27633. get: function () {
  27634. return Mesh._CAP_ALL;
  27635. },
  27636. enumerable: true,
  27637. configurable: true
  27638. });
  27639. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  27640. set: function (callback) {
  27641. if (this._onBeforeDrawObserver) {
  27642. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  27643. }
  27644. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  27645. },
  27646. enumerable: true,
  27647. configurable: true
  27648. });
  27649. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  27650. get: function () {
  27651. return this._morphTargetManager;
  27652. },
  27653. set: function (value) {
  27654. if (this._morphTargetManager === value) {
  27655. return;
  27656. }
  27657. this._morphTargetManager = value;
  27658. this._syncGeometryWithMorphTargetManager();
  27659. },
  27660. enumerable: true,
  27661. configurable: true
  27662. });
  27663. Object.defineProperty(Mesh.prototype, "source", {
  27664. get: function () {
  27665. return this._source;
  27666. },
  27667. enumerable: true,
  27668. configurable: true
  27669. });
  27670. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  27671. get: function () {
  27672. return this._unIndexed;
  27673. },
  27674. set: function (value) {
  27675. if (this._unIndexed !== value) {
  27676. this._unIndexed = value;
  27677. this._markSubMeshesAsAttributesDirty();
  27678. }
  27679. },
  27680. enumerable: true,
  27681. configurable: true
  27682. });
  27683. // Methods
  27684. /**
  27685. * Returns the string "Mesh".
  27686. */
  27687. Mesh.prototype.getClassName = function () {
  27688. return "Mesh";
  27689. };
  27690. /**
  27691. * Returns a string.
  27692. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  27693. */
  27694. Mesh.prototype.toString = function (fullDetails) {
  27695. var ret = _super.prototype.toString.call(this, fullDetails);
  27696. ret += ", n vertices: " + this.getTotalVertices();
  27697. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  27698. if (this.animations) {
  27699. for (var i = 0; i < this.animations.length; i++) {
  27700. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  27701. }
  27702. }
  27703. if (fullDetails) {
  27704. if (this._geometry) {
  27705. var ib = this.getIndices();
  27706. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27707. if (vb && ib) {
  27708. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  27709. }
  27710. }
  27711. else {
  27712. ret += ", flat shading: UNKNOWN";
  27713. }
  27714. }
  27715. return ret;
  27716. };
  27717. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  27718. /**
  27719. * True if the mesh has some Levels Of Details (LOD).
  27720. * Returns a boolean.
  27721. */
  27722. get: function () {
  27723. return this._LODLevels.length > 0;
  27724. },
  27725. enumerable: true,
  27726. configurable: true
  27727. });
  27728. /**
  27729. * Gets the list of {BABYLON.MeshLODLevel} associated with the current mesh
  27730. * @returns an array of {BABYLON.MeshLODLevel}
  27731. */
  27732. Mesh.prototype.getLODLevels = function () {
  27733. return this._LODLevels;
  27734. };
  27735. Mesh.prototype._sortLODLevels = function () {
  27736. this._LODLevels.sort(function (a, b) {
  27737. if (a.distance < b.distance) {
  27738. return 1;
  27739. }
  27740. if (a.distance > b.distance) {
  27741. return -1;
  27742. }
  27743. return 0;
  27744. });
  27745. };
  27746. /**
  27747. * Add a mesh as LOD level triggered at the given distance.
  27748. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  27749. * @param {number} distance The distance from the center of the object to show this level
  27750. * @param {Mesh} mesh The mesh to be added as LOD level
  27751. * @return {Mesh} This mesh (for chaining)
  27752. */
  27753. Mesh.prototype.addLODLevel = function (distance, mesh) {
  27754. if (mesh && mesh._masterMesh) {
  27755. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  27756. return this;
  27757. }
  27758. var level = new BABYLON.MeshLODLevel(distance, mesh);
  27759. this._LODLevels.push(level);
  27760. if (mesh) {
  27761. mesh._masterMesh = this;
  27762. }
  27763. this._sortLODLevels();
  27764. return this;
  27765. };
  27766. /**
  27767. * Returns the LOD level mesh at the passed distance or null if not found.
  27768. * It is related to the method `addLODLevel(distance, mesh)`.
  27769. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  27770. * Returns an object Mesh or `null`.
  27771. */
  27772. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  27773. for (var index = 0; index < this._LODLevels.length; index++) {
  27774. var level = this._LODLevels[index];
  27775. if (level.distance === distance) {
  27776. return level.mesh;
  27777. }
  27778. }
  27779. return null;
  27780. };
  27781. /**
  27782. * Remove a mesh from the LOD array
  27783. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  27784. * @param {Mesh} mesh The mesh to be removed.
  27785. * @return {Mesh} This mesh (for chaining)
  27786. */
  27787. Mesh.prototype.removeLODLevel = function (mesh) {
  27788. for (var index = 0; index < this._LODLevels.length; index++) {
  27789. if (this._LODLevels[index].mesh === mesh) {
  27790. this._LODLevels.splice(index, 1);
  27791. if (mesh) {
  27792. mesh._masterMesh = null;
  27793. }
  27794. }
  27795. }
  27796. this._sortLODLevels();
  27797. return this;
  27798. };
  27799. /**
  27800. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  27801. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  27802. */
  27803. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  27804. if (!this._LODLevels || this._LODLevels.length === 0) {
  27805. return this;
  27806. }
  27807. var bSphere;
  27808. if (boundingSphere) {
  27809. bSphere = boundingSphere;
  27810. }
  27811. else {
  27812. var boundingInfo = this.getBoundingInfo();
  27813. bSphere = boundingInfo.boundingSphere;
  27814. }
  27815. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  27816. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  27817. if (this.onLODLevelSelection) {
  27818. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  27819. }
  27820. return this;
  27821. }
  27822. for (var index = 0; index < this._LODLevels.length; index++) {
  27823. var level = this._LODLevels[index];
  27824. if (level.distance < distanceToCamera) {
  27825. if (level.mesh) {
  27826. level.mesh._preActivate();
  27827. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  27828. }
  27829. if (this.onLODLevelSelection) {
  27830. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  27831. }
  27832. return level.mesh;
  27833. }
  27834. }
  27835. if (this.onLODLevelSelection) {
  27836. this.onLODLevelSelection(distanceToCamera, this, this);
  27837. }
  27838. return this;
  27839. };
  27840. Object.defineProperty(Mesh.prototype, "geometry", {
  27841. /**
  27842. * Returns the mesh internal Geometry object.
  27843. */
  27844. get: function () {
  27845. return this._geometry;
  27846. },
  27847. enumerable: true,
  27848. configurable: true
  27849. });
  27850. /**
  27851. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  27852. */
  27853. Mesh.prototype.getTotalVertices = function () {
  27854. if (this._geometry === null || this._geometry === undefined) {
  27855. return 0;
  27856. }
  27857. return this._geometry.getTotalVertices();
  27858. };
  27859. /**
  27860. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  27861. * 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.
  27862. * You can force the copy with forceCopy === true
  27863. * Returns null if the mesh has no geometry or no vertex buffer.
  27864. * Possible `kind` values :
  27865. * - BABYLON.VertexBuffer.PositionKind
  27866. * - BABYLON.VertexBuffer.UVKind
  27867. * - BABYLON.VertexBuffer.UV2Kind
  27868. * - BABYLON.VertexBuffer.UV3Kind
  27869. * - BABYLON.VertexBuffer.UV4Kind
  27870. * - BABYLON.VertexBuffer.UV5Kind
  27871. * - BABYLON.VertexBuffer.UV6Kind
  27872. * - BABYLON.VertexBuffer.ColorKind
  27873. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27874. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27875. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27876. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27877. */
  27878. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  27879. if (!this._geometry) {
  27880. return null;
  27881. }
  27882. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  27883. };
  27884. /**
  27885. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  27886. * Returns `null` if the mesh has no geometry.
  27887. * Possible `kind` values :
  27888. * - BABYLON.VertexBuffer.PositionKind
  27889. * - BABYLON.VertexBuffer.UVKind
  27890. * - BABYLON.VertexBuffer.UV2Kind
  27891. * - BABYLON.VertexBuffer.UV3Kind
  27892. * - BABYLON.VertexBuffer.UV4Kind
  27893. * - BABYLON.VertexBuffer.UV5Kind
  27894. * - BABYLON.VertexBuffer.UV6Kind
  27895. * - BABYLON.VertexBuffer.ColorKind
  27896. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27897. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27898. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27899. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27900. */
  27901. Mesh.prototype.getVertexBuffer = function (kind) {
  27902. if (!this._geometry) {
  27903. return null;
  27904. }
  27905. return this._geometry.getVertexBuffer(kind);
  27906. };
  27907. /**
  27908. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  27909. * Possible `kind` values :
  27910. * - BABYLON.VertexBuffer.PositionKind
  27911. * - BABYLON.VertexBuffer.UVKind
  27912. * - BABYLON.VertexBuffer.UV2Kind
  27913. * - BABYLON.VertexBuffer.UV3Kind
  27914. * - BABYLON.VertexBuffer.UV4Kind
  27915. * - BABYLON.VertexBuffer.UV5Kind
  27916. * - BABYLON.VertexBuffer.UV6Kind
  27917. * - BABYLON.VertexBuffer.ColorKind
  27918. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27919. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27920. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27921. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27922. */
  27923. Mesh.prototype.isVerticesDataPresent = function (kind) {
  27924. if (!this._geometry) {
  27925. if (this._delayInfo) {
  27926. return this._delayInfo.indexOf(kind) !== -1;
  27927. }
  27928. return false;
  27929. }
  27930. return this._geometry.isVerticesDataPresent(kind);
  27931. };
  27932. /**
  27933. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  27934. * Possible `kind` values :
  27935. * - BABYLON.VertexBuffer.PositionKind
  27936. * - BABYLON.VertexBuffer.UVKind
  27937. * - BABYLON.VertexBuffer.UV2Kind
  27938. * - BABYLON.VertexBuffer.UV3Kind
  27939. * - BABYLON.VertexBuffer.UV4Kind
  27940. * - BABYLON.VertexBuffer.UV5Kind
  27941. * - BABYLON.VertexBuffer.UV6Kind
  27942. * - BABYLON.VertexBuffer.ColorKind
  27943. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27944. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27945. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27946. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27947. */
  27948. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  27949. if (!this._geometry) {
  27950. if (this._delayInfo) {
  27951. return this._delayInfo.indexOf(kind) !== -1;
  27952. }
  27953. return false;
  27954. }
  27955. return this._geometry.isVertexBufferUpdatable(kind);
  27956. };
  27957. /**
  27958. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  27959. * Possible `kind` values :
  27960. * - BABYLON.VertexBuffer.PositionKind
  27961. * - BABYLON.VertexBuffer.UVKind
  27962. * - BABYLON.VertexBuffer.UV2Kind
  27963. * - BABYLON.VertexBuffer.UV3Kind
  27964. * - BABYLON.VertexBuffer.UV4Kind
  27965. * - BABYLON.VertexBuffer.UV5Kind
  27966. * - BABYLON.VertexBuffer.UV6Kind
  27967. * - BABYLON.VertexBuffer.ColorKind
  27968. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27969. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27970. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27971. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27972. */
  27973. Mesh.prototype.getVerticesDataKinds = function () {
  27974. if (!this._geometry) {
  27975. var result = new Array();
  27976. if (this._delayInfo) {
  27977. this._delayInfo.forEach(function (kind, index, array) {
  27978. result.push(kind);
  27979. });
  27980. }
  27981. return result;
  27982. }
  27983. return this._geometry.getVerticesDataKinds();
  27984. };
  27985. /**
  27986. * Returns a positive integer : the total number of indices in this mesh geometry.
  27987. * Returns zero if the mesh has no geometry.
  27988. */
  27989. Mesh.prototype.getTotalIndices = function () {
  27990. if (!this._geometry) {
  27991. return 0;
  27992. }
  27993. return this._geometry.getTotalIndices();
  27994. };
  27995. /**
  27996. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  27997. * 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.
  27998. * Returns an empty array if the mesh has no geometry.
  27999. */
  28000. Mesh.prototype.getIndices = function (copyWhenShared) {
  28001. if (!this._geometry) {
  28002. return [];
  28003. }
  28004. return this._geometry.getIndices(copyWhenShared);
  28005. };
  28006. Object.defineProperty(Mesh.prototype, "isBlocked", {
  28007. get: function () {
  28008. return this._masterMesh !== null && this._masterMesh !== undefined;
  28009. },
  28010. enumerable: true,
  28011. configurable: true
  28012. });
  28013. /**
  28014. * Determine if the current mesh is ready to be rendered
  28015. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  28016. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  28017. * @returns true if all associated assets are ready (material, textures, shaders)
  28018. */
  28019. Mesh.prototype.isReady = function (completeCheck, forceInstanceSupport) {
  28020. if (completeCheck === void 0) { completeCheck = false; }
  28021. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  28022. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  28023. return false;
  28024. }
  28025. if (!_super.prototype.isReady.call(this, completeCheck)) {
  28026. return false;
  28027. }
  28028. if (!this.subMeshes || this.subMeshes.length === 0) {
  28029. return true;
  28030. }
  28031. if (!completeCheck) {
  28032. return true;
  28033. }
  28034. var engine = this.getEngine();
  28035. var scene = this.getScene();
  28036. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  28037. this.computeWorldMatrix();
  28038. var mat = this.material || scene.defaultMaterial;
  28039. if (mat) {
  28040. if (mat.storeEffectOnSubMeshes) {
  28041. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  28042. var subMesh = _a[_i];
  28043. var effectiveMaterial = subMesh.getMaterial();
  28044. if (effectiveMaterial) {
  28045. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  28046. return false;
  28047. }
  28048. }
  28049. }
  28050. }
  28051. else {
  28052. if (!mat.isReady(this, hardwareInstancedRendering)) {
  28053. return false;
  28054. }
  28055. }
  28056. }
  28057. // Shadows
  28058. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  28059. var light = _c[_b];
  28060. var generator = light.getShadowGenerator();
  28061. if (generator) {
  28062. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  28063. var subMesh = _e[_d];
  28064. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  28065. return false;
  28066. }
  28067. }
  28068. }
  28069. }
  28070. // LOD
  28071. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  28072. var lod = _g[_f];
  28073. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  28074. return false;
  28075. }
  28076. }
  28077. return true;
  28078. };
  28079. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  28080. /**
  28081. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  28082. * This property is pertinent only for updatable parametric shapes.
  28083. */
  28084. get: function () {
  28085. return this._areNormalsFrozen;
  28086. },
  28087. enumerable: true,
  28088. configurable: true
  28089. });
  28090. /**
  28091. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  28092. * It has no effect at all on other shapes.
  28093. * It prevents the mesh normals from being recomputed on next `positions` array update.
  28094. * Returns the Mesh.
  28095. */
  28096. Mesh.prototype.freezeNormals = function () {
  28097. this._areNormalsFrozen = true;
  28098. return this;
  28099. };
  28100. /**
  28101. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  28102. * It has no effect at all on other shapes.
  28103. * It reactivates the mesh normals computation if it was previously frozen.
  28104. * Returns the Mesh.
  28105. */
  28106. Mesh.prototype.unfreezeNormals = function () {
  28107. this._areNormalsFrozen = false;
  28108. return this;
  28109. };
  28110. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  28111. /**
  28112. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  28113. */
  28114. set: function (count) {
  28115. this._overridenInstanceCount = count;
  28116. },
  28117. enumerable: true,
  28118. configurable: true
  28119. });
  28120. // Methods
  28121. Mesh.prototype._preActivate = function () {
  28122. var sceneRenderId = this.getScene().getRenderId();
  28123. if (this._preActivateId === sceneRenderId) {
  28124. return this;
  28125. }
  28126. this._preActivateId = sceneRenderId;
  28127. this._visibleInstances = null;
  28128. return this;
  28129. };
  28130. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  28131. if (this._visibleInstances) {
  28132. this._visibleInstances.intermediateDefaultRenderId = renderId;
  28133. }
  28134. return this;
  28135. };
  28136. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  28137. if (!this._visibleInstances) {
  28138. this._visibleInstances = {};
  28139. this._visibleInstances.defaultRenderId = renderId;
  28140. this._visibleInstances.selfDefaultRenderId = this._renderId;
  28141. }
  28142. if (!this._visibleInstances[renderId]) {
  28143. this._visibleInstances[renderId] = new Array();
  28144. }
  28145. this._visibleInstances[renderId].push(instance);
  28146. return this;
  28147. };
  28148. /**
  28149. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  28150. * This means the mesh underlying bounding box and sphere are recomputed.
  28151. * Returns the Mesh.
  28152. */
  28153. Mesh.prototype.refreshBoundingInfo = function () {
  28154. return this._refreshBoundingInfo(false);
  28155. };
  28156. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  28157. if (this._boundingInfo && this._boundingInfo.isLocked) {
  28158. return this;
  28159. }
  28160. var data = this._getPositionData(applySkeleton);
  28161. if (data) {
  28162. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  28163. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  28164. }
  28165. if (this.subMeshes) {
  28166. for (var index = 0; index < this.subMeshes.length; index++) {
  28167. this.subMeshes[index].refreshBoundingInfo();
  28168. }
  28169. }
  28170. this._updateBoundingInfo();
  28171. return this;
  28172. };
  28173. Mesh.prototype._getPositionData = function (applySkeleton) {
  28174. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28175. if (data && applySkeleton && this.skeleton) {
  28176. data = BABYLON.Tools.Slice(data);
  28177. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  28178. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  28179. if (matricesWeightsData && matricesIndicesData) {
  28180. var needExtras = this.numBoneInfluencers > 4;
  28181. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  28182. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  28183. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  28184. var tempVector = BABYLON.Tmp.Vector3[0];
  28185. var finalMatrix = BABYLON.Tmp.Matrix[0];
  28186. var tempMatrix = BABYLON.Tmp.Matrix[1];
  28187. var matWeightIdx = 0;
  28188. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  28189. finalMatrix.reset();
  28190. var inf;
  28191. var weight;
  28192. for (inf = 0; inf < 4; inf++) {
  28193. weight = matricesWeightsData[matWeightIdx + inf];
  28194. if (weight <= 0)
  28195. break;
  28196. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  28197. finalMatrix.addToSelf(tempMatrix);
  28198. }
  28199. if (needExtras) {
  28200. for (inf = 0; inf < 4; inf++) {
  28201. weight = matricesWeightsExtraData[matWeightIdx + inf];
  28202. if (weight <= 0)
  28203. break;
  28204. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  28205. finalMatrix.addToSelf(tempMatrix);
  28206. }
  28207. }
  28208. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  28209. tempVector.toArray(data, index);
  28210. }
  28211. }
  28212. }
  28213. return data;
  28214. };
  28215. Mesh.prototype._createGlobalSubMesh = function (force) {
  28216. var totalVertices = this.getTotalVertices();
  28217. if (!totalVertices || !this.getIndices()) {
  28218. return null;
  28219. }
  28220. // Check if we need to recreate the submeshes
  28221. if (this.subMeshes && this.subMeshes.length > 0) {
  28222. var ib = this.getIndices();
  28223. if (!ib) {
  28224. return null;
  28225. }
  28226. var totalIndices = ib.length;
  28227. var needToRecreate = false;
  28228. if (force) {
  28229. needToRecreate = true;
  28230. }
  28231. else {
  28232. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  28233. var submesh = _a[_i];
  28234. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  28235. needToRecreate = true;
  28236. break;
  28237. }
  28238. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  28239. needToRecreate = true;
  28240. break;
  28241. }
  28242. }
  28243. }
  28244. if (!needToRecreate) {
  28245. return this.subMeshes[0];
  28246. }
  28247. }
  28248. this.releaseSubMeshes();
  28249. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  28250. };
  28251. Mesh.prototype.subdivide = function (count) {
  28252. if (count < 1) {
  28253. return;
  28254. }
  28255. var totalIndices = this.getTotalIndices();
  28256. var subdivisionSize = (totalIndices / count) | 0;
  28257. var offset = 0;
  28258. // Ensure that subdivisionSize is a multiple of 3
  28259. while (subdivisionSize % 3 !== 0) {
  28260. subdivisionSize++;
  28261. }
  28262. this.releaseSubMeshes();
  28263. for (var index = 0; index < count; index++) {
  28264. if (offset >= totalIndices) {
  28265. break;
  28266. }
  28267. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  28268. offset += subdivisionSize;
  28269. }
  28270. this.synchronizeInstances();
  28271. };
  28272. /**
  28273. * Sets the vertex data of the mesh geometry for the requested `kind`.
  28274. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  28275. * The `data` are either a numeric array either a Float32Array.
  28276. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  28277. * 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).
  28278. * Note that a new underlying VertexBuffer object is created each call.
  28279. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  28280. *
  28281. * Possible `kind` values :
  28282. * - BABYLON.VertexBuffer.PositionKind
  28283. * - BABYLON.VertexBuffer.UVKind
  28284. * - BABYLON.VertexBuffer.UV2Kind
  28285. * - BABYLON.VertexBuffer.UV3Kind
  28286. * - BABYLON.VertexBuffer.UV4Kind
  28287. * - BABYLON.VertexBuffer.UV5Kind
  28288. * - BABYLON.VertexBuffer.UV6Kind
  28289. * - BABYLON.VertexBuffer.ColorKind
  28290. * - BABYLON.VertexBuffer.MatricesIndicesKind
  28291. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  28292. * - BABYLON.VertexBuffer.MatricesWeightsKind
  28293. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  28294. *
  28295. * Returns the Mesh.
  28296. */
  28297. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  28298. if (updatable === void 0) { updatable = false; }
  28299. if (!this._geometry) {
  28300. var vertexData = new BABYLON.VertexData();
  28301. vertexData.set(data, kind);
  28302. var scene = this.getScene();
  28303. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  28304. }
  28305. else {
  28306. this._geometry.setVerticesData(kind, data, updatable, stride);
  28307. }
  28308. return this;
  28309. };
  28310. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  28311. if (updatable === void 0) { updatable = true; }
  28312. var vb = this.getVertexBuffer(kind);
  28313. if (!vb || vb.isUpdatable() === updatable) {
  28314. return;
  28315. }
  28316. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  28317. };
  28318. /**
  28319. * Sets the mesh VertexBuffer.
  28320. * Returns the Mesh.
  28321. */
  28322. Mesh.prototype.setVerticesBuffer = function (buffer) {
  28323. if (!this._geometry) {
  28324. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  28325. }
  28326. this._geometry.setVerticesBuffer(buffer);
  28327. return this;
  28328. };
  28329. /**
  28330. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  28331. * If the mesh has no geometry, it is simply returned as it is.
  28332. * The `data` are either a numeric array either a Float32Array.
  28333. * No new underlying VertexBuffer object is created.
  28334. * 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.
  28335. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  28336. *
  28337. * Possible `kind` values :
  28338. * - BABYLON.VertexBuffer.PositionKind
  28339. * - BABYLON.VertexBuffer.UVKind
  28340. * - BABYLON.VertexBuffer.UV2Kind
  28341. * - BABYLON.VertexBuffer.UV3Kind
  28342. * - BABYLON.VertexBuffer.UV4Kind
  28343. * - BABYLON.VertexBuffer.UV5Kind
  28344. * - BABYLON.VertexBuffer.UV6Kind
  28345. * - BABYLON.VertexBuffer.ColorKind
  28346. * - BABYLON.VertexBuffer.MatricesIndicesKind
  28347. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  28348. * - BABYLON.VertexBuffer.MatricesWeightsKind
  28349. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  28350. *
  28351. * Returns the Mesh.
  28352. */
  28353. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  28354. if (!this._geometry) {
  28355. return this;
  28356. }
  28357. if (!makeItUnique) {
  28358. this._geometry.updateVerticesData(kind, data, updateExtends);
  28359. }
  28360. else {
  28361. this.makeGeometryUnique();
  28362. this.updateVerticesData(kind, data, updateExtends, false);
  28363. }
  28364. return this;
  28365. };
  28366. /**
  28367. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  28368. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  28369. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  28370. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  28371. * Returns the Mesh.
  28372. */
  28373. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  28374. if (computeNormals === void 0) { computeNormals = true; }
  28375. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28376. if (!positions) {
  28377. return this;
  28378. }
  28379. positionFunction(positions);
  28380. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  28381. if (computeNormals) {
  28382. var indices = this.getIndices();
  28383. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  28384. if (!normals) {
  28385. return this;
  28386. }
  28387. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  28388. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  28389. }
  28390. return this;
  28391. };
  28392. /**
  28393. * Creates a un-shared specific occurence of the geometry for the mesh.
  28394. * Returns the Mesh.
  28395. */
  28396. Mesh.prototype.makeGeometryUnique = function () {
  28397. if (!this._geometry) {
  28398. return this;
  28399. }
  28400. var oldGeometry = this._geometry;
  28401. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  28402. oldGeometry.releaseForMesh(this, true);
  28403. geometry.applyToMesh(this);
  28404. return this;
  28405. };
  28406. /**
  28407. * Sets the mesh indices.
  28408. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  28409. * Type is Uint16Array by default unless the mesh has more than 65536 vertices.
  28410. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  28411. * This method creates a new index buffer each call.
  28412. * Returns the Mesh.
  28413. */
  28414. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  28415. if (totalVertices === void 0) { totalVertices = null; }
  28416. if (updatable === void 0) { updatable = false; }
  28417. if (!this._geometry) {
  28418. var vertexData = new BABYLON.VertexData();
  28419. vertexData.indices = indices;
  28420. var scene = this.getScene();
  28421. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  28422. }
  28423. else {
  28424. this._geometry.setIndices(indices, totalVertices, updatable);
  28425. }
  28426. return this;
  28427. };
  28428. /**
  28429. * Update the current index buffer
  28430. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  28431. * Returns the Mesh.
  28432. */
  28433. Mesh.prototype.updateIndices = function (indices, offset) {
  28434. if (!this._geometry) {
  28435. return this;
  28436. }
  28437. this._geometry.updateIndices(indices, offset);
  28438. return this;
  28439. };
  28440. /**
  28441. * Invert the geometry to move from a right handed system to a left handed one.
  28442. * Returns the Mesh.
  28443. */
  28444. Mesh.prototype.toLeftHanded = function () {
  28445. if (!this._geometry) {
  28446. return this;
  28447. }
  28448. this._geometry.toLeftHanded();
  28449. return this;
  28450. };
  28451. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  28452. if (!this._geometry) {
  28453. return this;
  28454. }
  28455. var engine = this.getScene().getEngine();
  28456. // Wireframe
  28457. var indexToBind;
  28458. if (this._unIndexed) {
  28459. indexToBind = null;
  28460. }
  28461. else {
  28462. switch (fillMode) {
  28463. case BABYLON.Material.PointFillMode:
  28464. indexToBind = null;
  28465. break;
  28466. case BABYLON.Material.WireFrameFillMode:
  28467. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  28468. break;
  28469. default:
  28470. case BABYLON.Material.TriangleFillMode:
  28471. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  28472. break;
  28473. }
  28474. }
  28475. // VBOs
  28476. this._geometry._bind(effect, indexToBind);
  28477. return this;
  28478. };
  28479. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  28480. if (alternate === void 0) { alternate = false; }
  28481. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  28482. return this;
  28483. }
  28484. this.onBeforeDrawObservable.notifyObservers(this);
  28485. var scene = this.getScene();
  28486. var engine = scene.getEngine();
  28487. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  28488. // or triangles as points
  28489. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  28490. }
  28491. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  28492. // Triangles as wireframe
  28493. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  28494. }
  28495. else {
  28496. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  28497. }
  28498. if (scene._isAlternateRenderingEnabled && !alternate) {
  28499. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  28500. if (!effect || !scene.activeCamera) {
  28501. return this;
  28502. }
  28503. scene._switchToAlternateCameraConfiguration(true);
  28504. this._effectiveMaterial.bindView(effect);
  28505. this._effectiveMaterial.bindViewProjection(effect);
  28506. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  28507. this._draw(subMesh, fillMode, instancesCount, true);
  28508. engine.setViewport(scene.activeCamera.viewport);
  28509. scene._switchToAlternateCameraConfiguration(false);
  28510. this._effectiveMaterial.bindView(effect);
  28511. this._effectiveMaterial.bindViewProjection(effect);
  28512. }
  28513. return this;
  28514. };
  28515. /**
  28516. * Registers for this mesh a javascript function called just before the rendering process.
  28517. * This function is passed the current mesh.
  28518. * Return the Mesh.
  28519. */
  28520. Mesh.prototype.registerBeforeRender = function (func) {
  28521. this.onBeforeRenderObservable.add(func);
  28522. return this;
  28523. };
  28524. /**
  28525. * Disposes a previously registered javascript function called before the rendering.
  28526. * This function is passed the current mesh.
  28527. * Returns the Mesh.
  28528. */
  28529. Mesh.prototype.unregisterBeforeRender = function (func) {
  28530. this.onBeforeRenderObservable.removeCallback(func);
  28531. return this;
  28532. };
  28533. /**
  28534. * Registers for this mesh a javascript function called just after the rendering is complete.
  28535. * This function is passed the current mesh.
  28536. * Returns the Mesh.
  28537. */
  28538. Mesh.prototype.registerAfterRender = function (func) {
  28539. this.onAfterRenderObservable.add(func);
  28540. return this;
  28541. };
  28542. /**
  28543. * Disposes a previously registered javascript function called after the rendering.
  28544. * This function is passed the current mesh.
  28545. * Return the Mesh.
  28546. */
  28547. Mesh.prototype.unregisterAfterRender = function (func) {
  28548. this.onAfterRenderObservable.removeCallback(func);
  28549. return this;
  28550. };
  28551. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  28552. var scene = this.getScene();
  28553. this._batchCache.mustReturn = false;
  28554. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  28555. this._batchCache.visibleInstances[subMeshId] = null;
  28556. if (this._visibleInstances) {
  28557. var currentRenderId = scene.getRenderId();
  28558. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  28559. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  28560. var selfRenderId = this._renderId;
  28561. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  28562. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  28563. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  28564. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  28565. }
  28566. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  28567. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  28568. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  28569. this._batchCache.mustReturn = true;
  28570. return this._batchCache;
  28571. }
  28572. if (currentRenderId !== selfRenderId) {
  28573. this._batchCache.renderSelf[subMeshId] = false;
  28574. }
  28575. }
  28576. this._renderIdForInstances[subMeshId] = currentRenderId;
  28577. }
  28578. return this._batchCache;
  28579. };
  28580. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  28581. var visibleInstances = batch.visibleInstances[subMesh._id];
  28582. if (!visibleInstances) {
  28583. return this;
  28584. }
  28585. var matricesCount = visibleInstances.length + 1;
  28586. var bufferSize = matricesCount * 16 * 4;
  28587. var currentInstancesBufferSize = this._instancesBufferSize;
  28588. var instancesBuffer = this._instancesBuffer;
  28589. while (this._instancesBufferSize < bufferSize) {
  28590. this._instancesBufferSize *= 2;
  28591. }
  28592. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  28593. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  28594. }
  28595. var offset = 0;
  28596. var instancesCount = 0;
  28597. var world = this.getWorldMatrix();
  28598. if (batch.renderSelf[subMesh._id]) {
  28599. world.copyToArray(this._instancesData, offset);
  28600. offset += 16;
  28601. instancesCount++;
  28602. }
  28603. if (visibleInstances) {
  28604. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  28605. var instance = visibleInstances[instanceIndex];
  28606. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  28607. offset += 16;
  28608. instancesCount++;
  28609. }
  28610. }
  28611. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  28612. if (instancesBuffer) {
  28613. instancesBuffer.dispose();
  28614. }
  28615. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  28616. this._instancesBuffer = instancesBuffer;
  28617. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  28618. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  28619. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  28620. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  28621. }
  28622. else {
  28623. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  28624. }
  28625. this._bind(subMesh, effect, fillMode);
  28626. this._draw(subMesh, fillMode, instancesCount);
  28627. engine.unbindInstanceAttributes();
  28628. return this;
  28629. };
  28630. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  28631. var scene = this.getScene();
  28632. var engine = scene.getEngine();
  28633. if (hardwareInstancedRendering) {
  28634. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  28635. }
  28636. else {
  28637. if (batch.renderSelf[subMesh._id]) {
  28638. // Draw
  28639. if (onBeforeDraw) {
  28640. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  28641. }
  28642. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  28643. }
  28644. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  28645. if (visibleInstancesForSubMesh) {
  28646. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  28647. var instance = visibleInstancesForSubMesh[instanceIndex];
  28648. // World
  28649. var world = instance.getWorldMatrix();
  28650. if (onBeforeDraw) {
  28651. onBeforeDraw(true, world, effectiveMaterial);
  28652. }
  28653. // Draw
  28654. this._draw(subMesh, fillMode);
  28655. }
  28656. }
  28657. }
  28658. return this;
  28659. };
  28660. /**
  28661. * Triggers the draw call for the mesh.
  28662. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  28663. * Returns the Mesh.
  28664. */
  28665. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  28666. this.checkOcclusionQuery();
  28667. if (this._isOccluded) {
  28668. return this;
  28669. }
  28670. var scene = this.getScene();
  28671. // Managing instances
  28672. var batch = this._getInstancesRenderList(subMesh._id);
  28673. if (batch.mustReturn) {
  28674. return this;
  28675. }
  28676. // Checking geometry state
  28677. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  28678. return this;
  28679. }
  28680. this.onBeforeRenderObservable.notifyObservers(this);
  28681. var engine = scene.getEngine();
  28682. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  28683. // Material
  28684. var material = subMesh.getMaterial();
  28685. if (!material) {
  28686. return this;
  28687. }
  28688. this._effectiveMaterial = material;
  28689. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  28690. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  28691. return this;
  28692. }
  28693. }
  28694. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  28695. return this;
  28696. }
  28697. // Alpha mode
  28698. if (enableAlphaMode) {
  28699. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  28700. }
  28701. // Outline - step 1
  28702. var savedDepthWrite = engine.getDepthWrite();
  28703. if (this.renderOutline) {
  28704. engine.setDepthWrite(false);
  28705. scene.getOutlineRenderer().render(subMesh, batch);
  28706. engine.setDepthWrite(savedDepthWrite);
  28707. }
  28708. var effect;
  28709. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  28710. effect = subMesh.effect;
  28711. }
  28712. else {
  28713. effect = this._effectiveMaterial.getEffect();
  28714. }
  28715. if (!effect) {
  28716. return this;
  28717. }
  28718. var sideOrientation = this.overrideMaterialSideOrientation;
  28719. if (sideOrientation == null) {
  28720. sideOrientation = this._effectiveMaterial.sideOrientation;
  28721. if (this._getWorldMatrixDeterminant() < 0) {
  28722. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  28723. }
  28724. }
  28725. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  28726. if (this._effectiveMaterial.forceDepthWrite) {
  28727. engine.setDepthWrite(true);
  28728. }
  28729. // Bind
  28730. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  28731. if (!hardwareInstancedRendering) {
  28732. this._bind(subMesh, effect, fillMode);
  28733. }
  28734. var world = this.getWorldMatrix();
  28735. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  28736. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  28737. }
  28738. else {
  28739. this._effectiveMaterial.bind(world, this);
  28740. }
  28741. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  28742. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  28743. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  28744. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  28745. }
  28746. // Draw
  28747. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  28748. // Unbind
  28749. this._effectiveMaterial.unbind();
  28750. // Outline - step 2
  28751. if (this.renderOutline && savedDepthWrite) {
  28752. engine.setDepthWrite(true);
  28753. engine.setColorWrite(false);
  28754. scene.getOutlineRenderer().render(subMesh, batch);
  28755. engine.setColorWrite(true);
  28756. }
  28757. // Overlay
  28758. if (this.renderOverlay) {
  28759. var currentMode = engine.getAlphaMode();
  28760. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  28761. scene.getOutlineRenderer().render(subMesh, batch, true);
  28762. engine.setAlphaMode(currentMode);
  28763. }
  28764. this.onAfterRenderObservable.notifyObservers(this);
  28765. return this;
  28766. };
  28767. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  28768. if (isInstance && effectiveMaterial) {
  28769. effectiveMaterial.bindOnlyWorldMatrix(world);
  28770. }
  28771. };
  28772. /**
  28773. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  28774. */
  28775. Mesh.prototype.getEmittedParticleSystems = function () {
  28776. var results = new Array();
  28777. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  28778. var particleSystem = this.getScene().particleSystems[index];
  28779. if (particleSystem.emitter === this) {
  28780. results.push(particleSystem);
  28781. }
  28782. }
  28783. return results;
  28784. };
  28785. /**
  28786. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  28787. */
  28788. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  28789. var results = new Array();
  28790. var descendants = this.getDescendants();
  28791. descendants.push(this);
  28792. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  28793. var particleSystem = this.getScene().particleSystems[index];
  28794. var emitter = particleSystem.emitter;
  28795. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  28796. results.push(particleSystem);
  28797. }
  28798. }
  28799. return results;
  28800. };
  28801. Mesh.prototype._checkDelayState = function () {
  28802. var scene = this.getScene();
  28803. if (this._geometry) {
  28804. this._geometry.load(scene);
  28805. }
  28806. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  28807. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  28808. this._queueLoad(scene);
  28809. }
  28810. return this;
  28811. };
  28812. Mesh.prototype._queueLoad = function (scene) {
  28813. var _this = this;
  28814. scene._addPendingData(this);
  28815. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  28816. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  28817. if (data instanceof ArrayBuffer) {
  28818. _this._delayLoadingFunction(data, _this);
  28819. }
  28820. else {
  28821. _this._delayLoadingFunction(JSON.parse(data), _this);
  28822. }
  28823. _this.instances.forEach(function (instance) {
  28824. instance._syncSubMeshes();
  28825. });
  28826. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  28827. scene._removePendingData(_this);
  28828. }, function () { }, scene.database, getBinaryData);
  28829. return this;
  28830. };
  28831. /**
  28832. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  28833. */
  28834. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  28835. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  28836. return false;
  28837. }
  28838. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  28839. return false;
  28840. }
  28841. this._checkDelayState();
  28842. return true;
  28843. };
  28844. /**
  28845. * Sets the mesh material by the material or multiMaterial `id` property.
  28846. * The material `id` is a string identifying the material or the multiMaterial.
  28847. * This method returns the Mesh.
  28848. */
  28849. Mesh.prototype.setMaterialByID = function (id) {
  28850. var materials = this.getScene().materials;
  28851. var index;
  28852. for (index = materials.length - 1; index > -1; index--) {
  28853. if (materials[index].id === id) {
  28854. this.material = materials[index];
  28855. return this;
  28856. }
  28857. }
  28858. // Multi
  28859. var multiMaterials = this.getScene().multiMaterials;
  28860. for (index = multiMaterials.length - 1; index > -1; index--) {
  28861. if (multiMaterials[index].id === id) {
  28862. this.material = multiMaterials[index];
  28863. return this;
  28864. }
  28865. }
  28866. return this;
  28867. };
  28868. /**
  28869. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  28870. */
  28871. Mesh.prototype.getAnimatables = function () {
  28872. var results = new Array();
  28873. if (this.material) {
  28874. results.push(this.material);
  28875. }
  28876. if (this.skeleton) {
  28877. results.push(this.skeleton);
  28878. }
  28879. return results;
  28880. };
  28881. /**
  28882. * Modifies the mesh geometry according to the passed transformation matrix.
  28883. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  28884. * The mesh normals are modified accordingly the same transformation.
  28885. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  28886. * Note that, under the hood, this method sets a new VertexBuffer each call.
  28887. * Returns the Mesh.
  28888. */
  28889. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  28890. // Position
  28891. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  28892. return this;
  28893. }
  28894. var submeshes = this.subMeshes.splice(0);
  28895. this._resetPointsArrayCache();
  28896. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28897. var temp = new Array();
  28898. var index;
  28899. for (index = 0; index < data.length; index += 3) {
  28900. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  28901. }
  28902. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  28903. // Normals
  28904. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  28905. return this;
  28906. }
  28907. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  28908. temp = [];
  28909. for (index = 0; index < data.length; index += 3) {
  28910. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  28911. }
  28912. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  28913. // flip faces?
  28914. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  28915. this.flipFaces();
  28916. }
  28917. // Restore submeshes
  28918. this.releaseSubMeshes();
  28919. this.subMeshes = submeshes;
  28920. return this;
  28921. };
  28922. /**
  28923. * Modifies the mesh geometry according to its own current World Matrix.
  28924. * The mesh World Matrix is then reset.
  28925. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  28926. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  28927. * Note that, under the hood, this method sets a new VertexBuffer each call.
  28928. * Returns the Mesh.
  28929. */
  28930. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  28931. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  28932. this.scaling.copyFromFloats(1, 1, 1);
  28933. this.position.copyFromFloats(0, 0, 0);
  28934. this.rotation.copyFromFloats(0, 0, 0);
  28935. //only if quaternion is already set
  28936. if (this.rotationQuaternion) {
  28937. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  28938. }
  28939. this._worldMatrix = BABYLON.Matrix.Identity();
  28940. return this;
  28941. };
  28942. Object.defineProperty(Mesh.prototype, "_positions", {
  28943. // Cache
  28944. get: function () {
  28945. if (this._geometry) {
  28946. return this._geometry._positions;
  28947. }
  28948. return null;
  28949. },
  28950. enumerable: true,
  28951. configurable: true
  28952. });
  28953. Mesh.prototype._resetPointsArrayCache = function () {
  28954. if (this._geometry) {
  28955. this._geometry._resetPointsArrayCache();
  28956. }
  28957. return this;
  28958. };
  28959. Mesh.prototype._generatePointsArray = function () {
  28960. if (this._geometry) {
  28961. return this._geometry._generatePointsArray();
  28962. }
  28963. return false;
  28964. };
  28965. /**
  28966. * Returns a new Mesh object generated from the current mesh properties.
  28967. * This method must not get confused with createInstance().
  28968. * The parameter `name` is a string, the name given to the new mesh.
  28969. * The optional parameter `newParent` can be any Node object (default `null`).
  28970. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  28971. * 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.
  28972. */
  28973. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  28974. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  28975. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  28976. };
  28977. /**
  28978. * Releases resources associated with this mesh.
  28979. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  28980. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  28981. */
  28982. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  28983. var _this = this;
  28984. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  28985. this.morphTargetManager = null;
  28986. if (this._geometry) {
  28987. this._geometry.releaseForMesh(this, true);
  28988. }
  28989. // Sources
  28990. var meshes = this.getScene().meshes;
  28991. meshes.forEach(function (abstractMesh) {
  28992. var mesh = abstractMesh;
  28993. if (mesh._source && mesh._source === _this) {
  28994. mesh._source = null;
  28995. }
  28996. });
  28997. this._source = null;
  28998. // Instances
  28999. if (this._instancesBuffer) {
  29000. this._instancesBuffer.dispose();
  29001. this._instancesBuffer = null;
  29002. }
  29003. while (this.instances.length) {
  29004. this.instances[0].dispose();
  29005. }
  29006. // Effect layers.
  29007. var effectLayers = this.getScene().effectLayers;
  29008. for (var i = 0; i < effectLayers.length; i++) {
  29009. var effectLayer = effectLayers[i];
  29010. if (effectLayer) {
  29011. effectLayer._disposeMesh(this);
  29012. }
  29013. }
  29014. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  29015. };
  29016. /**
  29017. * Modifies the mesh geometry according to a displacement map.
  29018. * 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.
  29019. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  29020. * This method returns nothing.
  29021. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  29022. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  29023. * 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.
  29024. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  29025. * The parameter `uvScale` is an optional vector2 used to scale UV.
  29026. *
  29027. * Returns the Mesh.
  29028. */
  29029. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  29030. var _this = this;
  29031. var scene = this.getScene();
  29032. var onload = function (img) {
  29033. // Getting height map data
  29034. var canvas = document.createElement("canvas");
  29035. var context = canvas.getContext("2d");
  29036. var heightMapWidth = img.width;
  29037. var heightMapHeight = img.height;
  29038. canvas.width = heightMapWidth;
  29039. canvas.height = heightMapHeight;
  29040. context.drawImage(img, 0, 0);
  29041. // Create VertexData from map data
  29042. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  29043. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  29044. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  29045. //execute success callback, if set
  29046. if (onSuccess) {
  29047. onSuccess(_this);
  29048. }
  29049. };
  29050. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  29051. return this;
  29052. };
  29053. /**
  29054. * Modifies the mesh geometry according to a displacementMap buffer.
  29055. * 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.
  29056. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  29057. * This method returns nothing.
  29058. * 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.
  29059. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  29060. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  29061. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  29062. * The parameter `uvScale` is an optional vector2 used to scale UV.
  29063. *
  29064. * Returns the Mesh.
  29065. */
  29066. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  29067. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  29068. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  29069. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  29070. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  29071. return this;
  29072. }
  29073. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29074. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  29075. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  29076. var position = BABYLON.Vector3.Zero();
  29077. var normal = BABYLON.Vector3.Zero();
  29078. var uv = BABYLON.Vector2.Zero();
  29079. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  29080. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  29081. for (var index = 0; index < positions.length; index += 3) {
  29082. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  29083. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  29084. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  29085. // Compute height
  29086. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  29087. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  29088. var pos = (u + v * heightMapWidth) * 4;
  29089. var r = buffer[pos] / 255.0;
  29090. var g = buffer[pos + 1] / 255.0;
  29091. var b = buffer[pos + 2] / 255.0;
  29092. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  29093. normal.normalize();
  29094. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  29095. position = position.add(normal);
  29096. position.toArray(positions, index);
  29097. }
  29098. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  29099. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  29100. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  29101. return this;
  29102. };
  29103. /**
  29104. * Modify the mesh to get a flat shading rendering.
  29105. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  29106. * This method returns the Mesh.
  29107. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  29108. */
  29109. Mesh.prototype.convertToFlatShadedMesh = function () {
  29110. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  29111. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  29112. var kinds = this.getVerticesDataKinds();
  29113. var vbs = {};
  29114. var data = {};
  29115. var newdata = {};
  29116. var updatableNormals = false;
  29117. var kindIndex;
  29118. var kind;
  29119. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  29120. kind = kinds[kindIndex];
  29121. var vertexBuffer = this.getVertexBuffer(kind);
  29122. if (kind === BABYLON.VertexBuffer.NormalKind) {
  29123. updatableNormals = vertexBuffer.isUpdatable();
  29124. kinds.splice(kindIndex, 1);
  29125. kindIndex--;
  29126. continue;
  29127. }
  29128. vbs[kind] = vertexBuffer;
  29129. data[kind] = vbs[kind].getData();
  29130. newdata[kind] = [];
  29131. }
  29132. // Save previous submeshes
  29133. var previousSubmeshes = this.subMeshes.slice(0);
  29134. var indices = this.getIndices();
  29135. var totalIndices = this.getTotalIndices();
  29136. // Generating unique vertices per face
  29137. var index;
  29138. for (index = 0; index < totalIndices; index++) {
  29139. var vertexIndex = indices[index];
  29140. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  29141. kind = kinds[kindIndex];
  29142. var stride = vbs[kind].getStrideSize();
  29143. for (var offset = 0; offset < stride; offset++) {
  29144. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  29145. }
  29146. }
  29147. }
  29148. // Updating faces & normal
  29149. var normals = [];
  29150. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  29151. for (index = 0; index < totalIndices; index += 3) {
  29152. indices[index] = index;
  29153. indices[index + 1] = index + 1;
  29154. indices[index + 2] = index + 2;
  29155. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  29156. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  29157. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  29158. var p1p2 = p1.subtract(p2);
  29159. var p3p2 = p3.subtract(p2);
  29160. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  29161. // Store same normals for every vertex
  29162. for (var localIndex = 0; localIndex < 3; localIndex++) {
  29163. normals.push(normal.x);
  29164. normals.push(normal.y);
  29165. normals.push(normal.z);
  29166. }
  29167. }
  29168. this.setIndices(indices);
  29169. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  29170. // Updating vertex buffers
  29171. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  29172. kind = kinds[kindIndex];
  29173. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  29174. }
  29175. // Updating submeshes
  29176. this.releaseSubMeshes();
  29177. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  29178. var previousOne = previousSubmeshes[submeshIndex];
  29179. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  29180. }
  29181. this.synchronizeInstances();
  29182. return this;
  29183. };
  29184. /**
  29185. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  29186. * In other words, more vertices, no more indices and a single bigger VBO.
  29187. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  29188. * Returns the Mesh.
  29189. */
  29190. Mesh.prototype.convertToUnIndexedMesh = function () {
  29191. /// <summary>Remove indices by unfolding faces into buffers</summary>
  29192. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  29193. var kinds = this.getVerticesDataKinds();
  29194. var vbs = {};
  29195. var data = {};
  29196. var newdata = {};
  29197. var kindIndex;
  29198. var kind;
  29199. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  29200. kind = kinds[kindIndex];
  29201. var vertexBuffer = this.getVertexBuffer(kind);
  29202. vbs[kind] = vertexBuffer;
  29203. data[kind] = vbs[kind].getData();
  29204. newdata[kind] = [];
  29205. }
  29206. // Save previous submeshes
  29207. var previousSubmeshes = this.subMeshes.slice(0);
  29208. var indices = this.getIndices();
  29209. var totalIndices = this.getTotalIndices();
  29210. // Generating unique vertices per face
  29211. var index;
  29212. for (index = 0; index < totalIndices; index++) {
  29213. var vertexIndex = indices[index];
  29214. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  29215. kind = kinds[kindIndex];
  29216. var stride = vbs[kind].getStrideSize();
  29217. for (var offset = 0; offset < stride; offset++) {
  29218. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  29219. }
  29220. }
  29221. }
  29222. // Updating indices
  29223. for (index = 0; index < totalIndices; index += 3) {
  29224. indices[index] = index;
  29225. indices[index + 1] = index + 1;
  29226. indices[index + 2] = index + 2;
  29227. }
  29228. this.setIndices(indices);
  29229. // Updating vertex buffers
  29230. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  29231. kind = kinds[kindIndex];
  29232. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  29233. }
  29234. // Updating submeshes
  29235. this.releaseSubMeshes();
  29236. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  29237. var previousOne = previousSubmeshes[submeshIndex];
  29238. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  29239. }
  29240. this._unIndexed = true;
  29241. this.synchronizeInstances();
  29242. return this;
  29243. };
  29244. /**
  29245. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  29246. * This method returns the Mesh.
  29247. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  29248. */
  29249. Mesh.prototype.flipFaces = function (flipNormals) {
  29250. if (flipNormals === void 0) { flipNormals = false; }
  29251. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  29252. var i;
  29253. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  29254. for (i = 0; i < vertex_data.normals.length; i++) {
  29255. vertex_data.normals[i] *= -1;
  29256. }
  29257. }
  29258. if (vertex_data.indices) {
  29259. var temp;
  29260. for (i = 0; i < vertex_data.indices.length; i += 3) {
  29261. // reassign indices
  29262. temp = vertex_data.indices[i + 1];
  29263. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  29264. vertex_data.indices[i + 2] = temp;
  29265. }
  29266. }
  29267. vertex_data.applyToMesh(this);
  29268. return this;
  29269. };
  29270. // Instances
  29271. /**
  29272. * Creates a new InstancedMesh object from the mesh model.
  29273. * An instance shares the same properties and the same material than its model.
  29274. * Only these properties of each instance can then be set individually :
  29275. * - position
  29276. * - rotation
  29277. * - rotationQuaternion
  29278. * - setPivotMatrix
  29279. * - scaling
  29280. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  29281. * Warning : this method is not supported for Line mesh and LineSystem
  29282. */
  29283. Mesh.prototype.createInstance = function (name) {
  29284. return new BABYLON.InstancedMesh(name, this);
  29285. };
  29286. /**
  29287. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  29288. * After this call, all the mesh instances have the same submeshes than the current mesh.
  29289. * This method returns the Mesh.
  29290. */
  29291. Mesh.prototype.synchronizeInstances = function () {
  29292. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  29293. var instance = this.instances[instanceIndex];
  29294. instance._syncSubMeshes();
  29295. }
  29296. return this;
  29297. };
  29298. /**
  29299. * Simplify the mesh according to the given array of settings.
  29300. * Function will return immediately and will simplify async. It returns the Mesh.
  29301. * @param settings a collection of simplification settings.
  29302. * @param parallelProcessing should all levels calculate parallel or one after the other.
  29303. * @param type the type of simplification to run.
  29304. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  29305. */
  29306. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  29307. if (parallelProcessing === void 0) { parallelProcessing = true; }
  29308. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  29309. this.getScene().simplificationQueue.addTask({
  29310. settings: settings,
  29311. parallelProcessing: parallelProcessing,
  29312. mesh: this,
  29313. simplificationType: simplificationType,
  29314. successCallback: successCallback
  29315. });
  29316. return this;
  29317. };
  29318. /**
  29319. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  29320. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  29321. * This should be used together with the simplification to avoid disappearing triangles.
  29322. * Returns the Mesh.
  29323. * @param successCallback an optional success callback to be called after the optimization finished.
  29324. */
  29325. Mesh.prototype.optimizeIndices = function (successCallback) {
  29326. var _this = this;
  29327. var indices = this.getIndices();
  29328. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29329. if (!positions || !indices) {
  29330. return this;
  29331. }
  29332. var vectorPositions = new Array();
  29333. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  29334. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  29335. }
  29336. var dupes = new Array();
  29337. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  29338. var realPos = vectorPositions.length - 1 - iteration;
  29339. var testedPosition = vectorPositions[realPos];
  29340. for (var j = 0; j < realPos; ++j) {
  29341. var againstPosition = vectorPositions[j];
  29342. if (testedPosition.equals(againstPosition)) {
  29343. dupes[realPos] = j;
  29344. break;
  29345. }
  29346. }
  29347. }, function () {
  29348. for (var i = 0; i < indices.length; ++i) {
  29349. indices[i] = dupes[indices[i]] || indices[i];
  29350. }
  29351. //indices are now reordered
  29352. var originalSubMeshes = _this.subMeshes.slice(0);
  29353. _this.setIndices(indices);
  29354. _this.subMeshes = originalSubMeshes;
  29355. if (successCallback) {
  29356. successCallback(_this);
  29357. }
  29358. });
  29359. return this;
  29360. };
  29361. Mesh.prototype.serialize = function (serializationObject) {
  29362. serializationObject.name = this.name;
  29363. serializationObject.id = this.id;
  29364. serializationObject.type = this.getClassName();
  29365. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  29366. serializationObject.tags = BABYLON.Tags.GetTags(this);
  29367. }
  29368. serializationObject.position = this.position.asArray();
  29369. if (this.rotationQuaternion) {
  29370. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  29371. }
  29372. else if (this.rotation) {
  29373. serializationObject.rotation = this.rotation.asArray();
  29374. }
  29375. serializationObject.scaling = this.scaling.asArray();
  29376. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  29377. serializationObject.isEnabled = this.isEnabled(false);
  29378. serializationObject.isVisible = this.isVisible;
  29379. serializationObject.infiniteDistance = this.infiniteDistance;
  29380. serializationObject.pickable = this.isPickable;
  29381. serializationObject.receiveShadows = this.receiveShadows;
  29382. serializationObject.billboardMode = this.billboardMode;
  29383. serializationObject.visibility = this.visibility;
  29384. serializationObject.checkCollisions = this.checkCollisions;
  29385. serializationObject.isBlocker = this.isBlocker;
  29386. // Parent
  29387. if (this.parent) {
  29388. serializationObject.parentId = this.parent.id;
  29389. }
  29390. // Geometry
  29391. serializationObject.isUnIndexed = this.isUnIndexed;
  29392. var geometry = this._geometry;
  29393. if (geometry) {
  29394. var geometryId = geometry.id;
  29395. serializationObject.geometryId = geometryId;
  29396. // SubMeshes
  29397. serializationObject.subMeshes = [];
  29398. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  29399. var subMesh = this.subMeshes[subIndex];
  29400. serializationObject.subMeshes.push({
  29401. materialIndex: subMesh.materialIndex,
  29402. verticesStart: subMesh.verticesStart,
  29403. verticesCount: subMesh.verticesCount,
  29404. indexStart: subMesh.indexStart,
  29405. indexCount: subMesh.indexCount
  29406. });
  29407. }
  29408. }
  29409. // Material
  29410. if (this.material) {
  29411. serializationObject.materialId = this.material.id;
  29412. }
  29413. else {
  29414. this.material = null;
  29415. }
  29416. // Morph targets
  29417. if (this.morphTargetManager) {
  29418. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  29419. }
  29420. // Skeleton
  29421. if (this.skeleton) {
  29422. serializationObject.skeletonId = this.skeleton.id;
  29423. }
  29424. // Physics
  29425. //TODO implement correct serialization for physics impostors.
  29426. var impostor = this.getPhysicsImpostor();
  29427. if (impostor) {
  29428. serializationObject.physicsMass = impostor.getParam("mass");
  29429. serializationObject.physicsFriction = impostor.getParam("friction");
  29430. serializationObject.physicsRestitution = impostor.getParam("mass");
  29431. serializationObject.physicsImpostor = impostor.type;
  29432. }
  29433. // Metadata
  29434. if (this.metadata) {
  29435. serializationObject.metadata = this.metadata;
  29436. }
  29437. // Instances
  29438. serializationObject.instances = [];
  29439. for (var index = 0; index < this.instances.length; index++) {
  29440. var instance = this.instances[index];
  29441. var serializationInstance = {
  29442. name: instance.name,
  29443. id: instance.id,
  29444. position: instance.position.asArray(),
  29445. scaling: instance.scaling.asArray()
  29446. };
  29447. if (instance.rotationQuaternion) {
  29448. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  29449. }
  29450. else if (instance.rotation) {
  29451. serializationInstance.rotation = instance.rotation.asArray();
  29452. }
  29453. serializationObject.instances.push(serializationInstance);
  29454. // Animations
  29455. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  29456. serializationInstance.ranges = instance.serializeAnimationRanges();
  29457. }
  29458. //
  29459. // Animations
  29460. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  29461. serializationObject.ranges = this.serializeAnimationRanges();
  29462. // Layer mask
  29463. serializationObject.layerMask = this.layerMask;
  29464. // Alpha
  29465. serializationObject.alphaIndex = this.alphaIndex;
  29466. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  29467. // Overlay
  29468. serializationObject.overlayAlpha = this.overlayAlpha;
  29469. serializationObject.overlayColor = this.overlayColor.asArray();
  29470. serializationObject.renderOverlay = this.renderOverlay;
  29471. // Fog
  29472. serializationObject.applyFog = this.applyFog;
  29473. // Action Manager
  29474. if (this.actionManager) {
  29475. serializationObject.actions = this.actionManager.serialize(this.name);
  29476. }
  29477. };
  29478. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  29479. if (!this.geometry) {
  29480. return;
  29481. }
  29482. this._markSubMeshesAsAttributesDirty();
  29483. var morphTargetManager = this._morphTargetManager;
  29484. if (morphTargetManager && morphTargetManager.vertexCount) {
  29485. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  29486. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  29487. this.morphTargetManager = null;
  29488. return;
  29489. }
  29490. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  29491. var morphTarget = morphTargetManager.getActiveTarget(index);
  29492. var positions = morphTarget.getPositions();
  29493. if (!positions) {
  29494. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  29495. return;
  29496. }
  29497. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  29498. var normals = morphTarget.getNormals();
  29499. if (normals) {
  29500. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  29501. }
  29502. var tangents = morphTarget.getTangents();
  29503. if (tangents) {
  29504. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  29505. }
  29506. }
  29507. }
  29508. else {
  29509. var index = 0;
  29510. // Positions
  29511. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  29512. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  29513. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  29514. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  29515. }
  29516. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  29517. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  29518. }
  29519. index++;
  29520. }
  29521. }
  29522. };
  29523. // Statics
  29524. /**
  29525. * Returns a new Mesh object parsed from the source provided.
  29526. * The parameter `parsedMesh` is the source.
  29527. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  29528. */
  29529. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  29530. var mesh;
  29531. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  29532. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  29533. }
  29534. else {
  29535. mesh = new Mesh(parsedMesh.name, scene);
  29536. }
  29537. mesh.id = parsedMesh.id;
  29538. if (BABYLON.Tags) {
  29539. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  29540. }
  29541. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  29542. if (parsedMesh.metadata !== undefined) {
  29543. mesh.metadata = parsedMesh.metadata;
  29544. }
  29545. if (parsedMesh.rotationQuaternion) {
  29546. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  29547. }
  29548. else if (parsedMesh.rotation) {
  29549. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  29550. }
  29551. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  29552. if (parsedMesh.localMatrix) {
  29553. mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  29554. }
  29555. else if (parsedMesh.pivotMatrix) {
  29556. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  29557. }
  29558. mesh.setEnabled(parsedMesh.isEnabled);
  29559. mesh.isVisible = parsedMesh.isVisible;
  29560. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  29561. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  29562. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  29563. if (parsedMesh.applyFog !== undefined) {
  29564. mesh.applyFog = parsedMesh.applyFog;
  29565. }
  29566. if (parsedMesh.pickable !== undefined) {
  29567. mesh.isPickable = parsedMesh.pickable;
  29568. }
  29569. if (parsedMesh.alphaIndex !== undefined) {
  29570. mesh.alphaIndex = parsedMesh.alphaIndex;
  29571. }
  29572. mesh.receiveShadows = parsedMesh.receiveShadows;
  29573. mesh.billboardMode = parsedMesh.billboardMode;
  29574. if (parsedMesh.visibility !== undefined) {
  29575. mesh.visibility = parsedMesh.visibility;
  29576. }
  29577. mesh.checkCollisions = parsedMesh.checkCollisions;
  29578. if (parsedMesh.isBlocker !== undefined) {
  29579. mesh.isBlocker = parsedMesh.isBlocker;
  29580. }
  29581. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  29582. // freezeWorldMatrix
  29583. if (parsedMesh.freezeWorldMatrix) {
  29584. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  29585. }
  29586. // Parent
  29587. if (parsedMesh.parentId) {
  29588. mesh._waitingParentId = parsedMesh.parentId;
  29589. }
  29590. // Actions
  29591. if (parsedMesh.actions !== undefined) {
  29592. mesh._waitingActions = parsedMesh.actions;
  29593. }
  29594. // Overlay
  29595. if (parsedMesh.overlayAlpha !== undefined) {
  29596. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  29597. }
  29598. if (parsedMesh.overlayColor !== undefined) {
  29599. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  29600. }
  29601. if (parsedMesh.renderOverlay !== undefined) {
  29602. mesh.renderOverlay = parsedMesh.renderOverlay;
  29603. }
  29604. // Geometry
  29605. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  29606. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  29607. if (parsedMesh.delayLoadingFile) {
  29608. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  29609. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  29610. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  29611. if (parsedMesh._binaryInfo) {
  29612. mesh._binaryInfo = parsedMesh._binaryInfo;
  29613. }
  29614. mesh._delayInfo = [];
  29615. if (parsedMesh.hasUVs) {
  29616. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  29617. }
  29618. if (parsedMesh.hasUVs2) {
  29619. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  29620. }
  29621. if (parsedMesh.hasUVs3) {
  29622. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  29623. }
  29624. if (parsedMesh.hasUVs4) {
  29625. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  29626. }
  29627. if (parsedMesh.hasUVs5) {
  29628. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  29629. }
  29630. if (parsedMesh.hasUVs6) {
  29631. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  29632. }
  29633. if (parsedMesh.hasColors) {
  29634. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  29635. }
  29636. if (parsedMesh.hasMatricesIndices) {
  29637. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  29638. }
  29639. if (parsedMesh.hasMatricesWeights) {
  29640. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  29641. }
  29642. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  29643. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  29644. mesh._checkDelayState();
  29645. }
  29646. }
  29647. else {
  29648. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  29649. }
  29650. // Material
  29651. if (parsedMesh.materialId) {
  29652. mesh.setMaterialByID(parsedMesh.materialId);
  29653. }
  29654. else {
  29655. mesh.material = null;
  29656. }
  29657. // Morph targets
  29658. if (parsedMesh.morphTargetManagerId > -1) {
  29659. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  29660. }
  29661. // Skeleton
  29662. if (parsedMesh.skeletonId > -1) {
  29663. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  29664. if (parsedMesh.numBoneInfluencers) {
  29665. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  29666. }
  29667. }
  29668. // Animations
  29669. if (parsedMesh.animations) {
  29670. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  29671. var parsedAnimation = parsedMesh.animations[animationIndex];
  29672. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  29673. }
  29674. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  29675. }
  29676. if (parsedMesh.autoAnimate) {
  29677. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  29678. }
  29679. // Layer Mask
  29680. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  29681. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  29682. }
  29683. else {
  29684. mesh.layerMask = 0x0FFFFFFF;
  29685. }
  29686. // Physics
  29687. if (parsedMesh.physicsImpostor) {
  29688. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  29689. mass: parsedMesh.physicsMass,
  29690. friction: parsedMesh.physicsFriction,
  29691. restitution: parsedMesh.physicsRestitution
  29692. }, scene);
  29693. }
  29694. // Instances
  29695. if (parsedMesh.instances) {
  29696. for (var index = 0; index < parsedMesh.instances.length; index++) {
  29697. var parsedInstance = parsedMesh.instances[index];
  29698. var instance = mesh.createInstance(parsedInstance.name);
  29699. if (parsedInstance.id) {
  29700. instance.id = parsedInstance.id;
  29701. }
  29702. if (BABYLON.Tags) {
  29703. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  29704. }
  29705. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  29706. if (parsedInstance.parentId) {
  29707. instance._waitingParentId = parsedInstance.parentId;
  29708. }
  29709. if (parsedInstance.rotationQuaternion) {
  29710. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  29711. }
  29712. else if (parsedInstance.rotation) {
  29713. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  29714. }
  29715. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  29716. instance.checkCollisions = mesh.checkCollisions;
  29717. if (parsedMesh.animations) {
  29718. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  29719. parsedAnimation = parsedMesh.animations[animationIndex];
  29720. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  29721. }
  29722. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  29723. }
  29724. }
  29725. }
  29726. return mesh;
  29727. };
  29728. /**
  29729. * Creates a ribbon mesh.
  29730. * Please consider using the same method from the MeshBuilder class instead.
  29731. * 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.
  29732. *
  29733. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  29734. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  29735. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  29736. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  29737. * 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.
  29738. * 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.
  29739. * 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
  29740. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29741. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29742. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29743. */
  29744. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  29745. if (closeArray === void 0) { closeArray = false; }
  29746. if (updatable === void 0) { updatable = false; }
  29747. return BABYLON.MeshBuilder.CreateRibbon(name, {
  29748. pathArray: pathArray,
  29749. closeArray: closeArray,
  29750. closePath: closePath,
  29751. offset: offset,
  29752. updatable: updatable,
  29753. sideOrientation: sideOrientation,
  29754. instance: instance
  29755. }, scene);
  29756. };
  29757. /**
  29758. * Creates a plane polygonal mesh. By default, this is a disc.
  29759. * Please consider using the same method from the MeshBuilder class instead.
  29760. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  29761. * 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.
  29762. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29763. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29764. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29765. */
  29766. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  29767. if (scene === void 0) { scene = null; }
  29768. var options = {
  29769. radius: radius,
  29770. tessellation: tessellation,
  29771. sideOrientation: sideOrientation,
  29772. updatable: updatable
  29773. };
  29774. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  29775. };
  29776. /**
  29777. * Creates a box mesh.
  29778. * Please consider using the same method from the MeshBuilder class instead.
  29779. * The parameter `size` sets the size (float) of each box side (default 1).
  29780. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29781. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29782. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29783. */
  29784. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  29785. if (scene === void 0) { scene = null; }
  29786. var options = {
  29787. size: size,
  29788. sideOrientation: sideOrientation,
  29789. updatable: updatable
  29790. };
  29791. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  29792. };
  29793. /**
  29794. * Creates a sphere mesh.
  29795. * Please consider using the same method from the MeshBuilder class instead.
  29796. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  29797. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  29798. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29799. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29800. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29801. */
  29802. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  29803. var options = {
  29804. segments: segments,
  29805. diameterX: diameter,
  29806. diameterY: diameter,
  29807. diameterZ: diameter,
  29808. sideOrientation: sideOrientation,
  29809. updatable: updatable
  29810. };
  29811. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  29812. };
  29813. /**
  29814. * Creates a cylinder or a cone mesh.
  29815. * Please consider using the same method from the MeshBuilder class instead.
  29816. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  29817. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  29818. * 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.
  29819. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  29820. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  29821. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29822. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29823. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29824. */
  29825. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  29826. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  29827. if (scene !== undefined) {
  29828. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  29829. updatable = scene;
  29830. }
  29831. scene = subdivisions;
  29832. subdivisions = 1;
  29833. }
  29834. var options = {
  29835. height: height,
  29836. diameterTop: diameterTop,
  29837. diameterBottom: diameterBottom,
  29838. tessellation: tessellation,
  29839. subdivisions: subdivisions,
  29840. sideOrientation: sideOrientation,
  29841. updatable: updatable
  29842. };
  29843. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  29844. };
  29845. // Torus (Code from SharpDX.org)
  29846. /**
  29847. * Creates a torus mesh.
  29848. * Please consider using the same method from the MeshBuilder class instead.
  29849. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  29850. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  29851. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  29852. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29853. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29854. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29855. */
  29856. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  29857. var options = {
  29858. diameter: diameter,
  29859. thickness: thickness,
  29860. tessellation: tessellation,
  29861. sideOrientation: sideOrientation,
  29862. updatable: updatable
  29863. };
  29864. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  29865. };
  29866. /**
  29867. * Creates a torus knot mesh.
  29868. * Please consider using the same method from the MeshBuilder class instead.
  29869. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  29870. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  29871. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  29872. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  29873. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29874. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29875. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29876. */
  29877. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  29878. var options = {
  29879. radius: radius,
  29880. tube: tube,
  29881. radialSegments: radialSegments,
  29882. tubularSegments: tubularSegments,
  29883. p: p,
  29884. q: q,
  29885. sideOrientation: sideOrientation,
  29886. updatable: updatable
  29887. };
  29888. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  29889. };
  29890. /**
  29891. * Creates a line mesh.
  29892. * Please consider using the same method from the MeshBuilder class instead.
  29893. * 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.
  29894. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  29895. * The parameter `points` is an array successive Vector3.
  29896. * 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
  29897. * When updating an instance, remember that only point positions can change, not the number of points.
  29898. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29899. */
  29900. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  29901. if (scene === void 0) { scene = null; }
  29902. if (updatable === void 0) { updatable = false; }
  29903. if (instance === void 0) { instance = null; }
  29904. var options = {
  29905. points: points,
  29906. updatable: updatable,
  29907. instance: instance
  29908. };
  29909. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  29910. };
  29911. /**
  29912. * Creates a dashed line mesh.
  29913. * Please consider using the same method from the MeshBuilder class instead.
  29914. * 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.
  29915. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  29916. * The parameter `points` is an array successive Vector3.
  29917. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  29918. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  29919. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  29920. * 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
  29921. * When updating an instance, remember that only point positions can change, not the number of points.
  29922. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29923. */
  29924. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  29925. if (scene === void 0) { scene = null; }
  29926. var options = {
  29927. points: points,
  29928. dashSize: dashSize,
  29929. gapSize: gapSize,
  29930. dashNb: dashNb,
  29931. updatable: updatable,
  29932. instance: instance
  29933. };
  29934. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  29935. };
  29936. /**
  29937. * Creates a polygon mesh.
  29938. * Please consider using the same method from the MeshBuilder class instead.
  29939. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  29940. * 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.
  29941. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29942. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29943. * Remember you can only change the shape positions, not their number when updating a polygon.
  29944. */
  29945. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  29946. var options = {
  29947. shape: shape,
  29948. holes: holes,
  29949. updatable: updatable,
  29950. sideOrientation: sideOrientation
  29951. };
  29952. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  29953. };
  29954. /**
  29955. * Creates an extruded polygon mesh, with depth in the Y direction.
  29956. * Please consider using the same method from the MeshBuilder class instead.
  29957. */
  29958. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  29959. var options = {
  29960. shape: shape,
  29961. holes: holes,
  29962. depth: depth,
  29963. updatable: updatable,
  29964. sideOrientation: sideOrientation
  29965. };
  29966. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  29967. };
  29968. /**
  29969. * Creates an extruded shape mesh.
  29970. * 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.
  29971. * Please consider using the same method from the MeshBuilder class instead.
  29972. *
  29973. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  29974. * 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
  29975. * extruded along the Z axis.
  29976. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  29977. * 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.
  29978. * The parameter `scale` (float, default 1) is the value to scale the shape.
  29979. * 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
  29980. * 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
  29981. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  29982. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29983. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29984. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29985. */
  29986. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  29987. if (scene === void 0) { scene = null; }
  29988. var options = {
  29989. shape: shape,
  29990. path: path,
  29991. scale: scale,
  29992. rotation: rotation,
  29993. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  29994. sideOrientation: sideOrientation,
  29995. instance: instance,
  29996. updatable: updatable
  29997. };
  29998. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  29999. };
  30000. /**
  30001. * Creates an custom extruded shape mesh.
  30002. * 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.
  30003. * Please consider using the same method from the MeshBuilder class instead.
  30004. *
  30005. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  30006. * 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
  30007. * extruded along the Z axis.
  30008. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  30009. * 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
  30010. * and the distance of this point from the begining of the path :
  30011. * ```javascript
  30012. * var rotationFunction = function(i, distance) {
  30013. * // do things
  30014. * return rotationValue; }
  30015. * ```
  30016. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  30017. * 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
  30018. * and the distance of this point from the begining of the path :
  30019. * ```javascript
  30020. * var scaleFunction = function(i, distance) {
  30021. * // do things
  30022. * return scaleValue;}
  30023. * ```
  30024. * It must returns a float value that will be the scale value applied to the shape on each path point.
  30025. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  30026. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  30027. * 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
  30028. * 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
  30029. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  30030. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30031. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30032. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30033. */
  30034. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  30035. var options = {
  30036. shape: shape,
  30037. path: path,
  30038. scaleFunction: scaleFunction,
  30039. rotationFunction: rotationFunction,
  30040. ribbonCloseArray: ribbonCloseArray,
  30041. ribbonClosePath: ribbonClosePath,
  30042. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  30043. sideOrientation: sideOrientation,
  30044. instance: instance,
  30045. updatable: updatable
  30046. };
  30047. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  30048. };
  30049. /**
  30050. * Creates lathe mesh.
  30051. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  30052. * Please consider using the same method from the MeshBuilder class instead.
  30053. * 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
  30054. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  30055. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  30056. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  30057. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30058. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30059. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30060. */
  30061. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  30062. var options = {
  30063. shape: shape,
  30064. radius: radius,
  30065. tessellation: tessellation,
  30066. sideOrientation: sideOrientation,
  30067. updatable: updatable
  30068. };
  30069. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  30070. };
  30071. /**
  30072. * Creates a plane mesh.
  30073. * Please consider using the same method from the MeshBuilder class instead.
  30074. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  30075. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30076. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30077. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30078. */
  30079. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  30080. var options = {
  30081. size: size,
  30082. width: size,
  30083. height: size,
  30084. sideOrientation: sideOrientation,
  30085. updatable: updatable
  30086. };
  30087. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  30088. };
  30089. /**
  30090. * Creates a ground mesh.
  30091. * Please consider using the same method from the MeshBuilder class instead.
  30092. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  30093. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  30094. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30095. */
  30096. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  30097. var options = {
  30098. width: width,
  30099. height: height,
  30100. subdivisions: subdivisions,
  30101. updatable: updatable
  30102. };
  30103. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  30104. };
  30105. /**
  30106. * Creates a tiled ground mesh.
  30107. * Please consider using the same method from the MeshBuilder class instead.
  30108. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  30109. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  30110. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  30111. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  30112. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  30113. * numbers of subdivisions on the ground width and height of each tile.
  30114. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30115. */
  30116. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  30117. var options = {
  30118. xmin: xmin,
  30119. zmin: zmin,
  30120. xmax: xmax,
  30121. zmax: zmax,
  30122. subdivisions: subdivisions,
  30123. precision: precision,
  30124. updatable: updatable
  30125. };
  30126. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  30127. };
  30128. /**
  30129. * Creates a ground mesh from a height map.
  30130. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  30131. * Please consider using the same method from the MeshBuilder class instead.
  30132. * The parameter `url` sets the URL of the height map image resource.
  30133. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  30134. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  30135. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  30136. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  30137. * 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).
  30138. * This function is passed the newly built mesh :
  30139. * ```javascript
  30140. * function(mesh) { // do things
  30141. * return; }
  30142. * ```
  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.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  30146. var options = {
  30147. width: width,
  30148. height: height,
  30149. subdivisions: subdivisions,
  30150. minHeight: minHeight,
  30151. maxHeight: maxHeight,
  30152. updatable: updatable,
  30153. onReady: onReady
  30154. };
  30155. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  30156. };
  30157. /**
  30158. * Creates a tube mesh.
  30159. * 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.
  30160. * Please consider using the same method from the MeshBuilder class instead.
  30161. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  30162. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  30163. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  30164. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  30165. * 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.
  30166. * It must return a radius value (positive float) :
  30167. * ```javascript
  30168. * var radiusFunction = function(i, distance) {
  30169. * // do things
  30170. * return radius; }
  30171. * ```
  30172. * 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
  30173. * 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
  30174. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30175. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30176. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30177. */
  30178. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  30179. var options = {
  30180. path: path,
  30181. radius: radius,
  30182. tessellation: tessellation,
  30183. radiusFunction: radiusFunction,
  30184. arc: 1,
  30185. cap: cap,
  30186. updatable: updatable,
  30187. sideOrientation: sideOrientation,
  30188. instance: instance
  30189. };
  30190. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  30191. };
  30192. /**
  30193. * Creates a polyhedron mesh.
  30194. * Please consider using the same method from the MeshBuilder class instead.
  30195. * 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
  30196. * to choose the wanted type.
  30197. * The parameter `size` (positive float, default 1) sets the polygon size.
  30198. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  30199. * 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`.
  30200. * 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
  30201. * 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)`).
  30202. * 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
  30203. * 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.
  30204. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30205. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30206. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30207. */
  30208. Mesh.CreatePolyhedron = function (name, options, scene) {
  30209. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  30210. };
  30211. /**
  30212. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  30213. * Please consider using the same method from the MeshBuilder class instead.
  30214. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  30215. * 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`).
  30216. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  30217. * 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.
  30218. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30219. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30220. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30221. */
  30222. Mesh.CreateIcoSphere = function (name, options, scene) {
  30223. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  30224. };
  30225. /**
  30226. * Creates a decal mesh.
  30227. * Please consider using the same method from the MeshBuilder class instead.
  30228. * 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.
  30229. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  30230. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  30231. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  30232. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  30233. */
  30234. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  30235. var options = {
  30236. position: position,
  30237. normal: normal,
  30238. size: size,
  30239. angle: angle
  30240. };
  30241. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  30242. };
  30243. // Skeletons
  30244. /**
  30245. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  30246. */
  30247. Mesh.prototype.setPositionsForCPUSkinning = function () {
  30248. if (!this._sourcePositions) {
  30249. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30250. if (!source) {
  30251. return this._sourcePositions;
  30252. }
  30253. this._sourcePositions = new Float32Array(source);
  30254. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  30255. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  30256. }
  30257. }
  30258. return this._sourcePositions;
  30259. };
  30260. /**
  30261. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  30262. */
  30263. Mesh.prototype.setNormalsForCPUSkinning = function () {
  30264. if (!this._sourceNormals) {
  30265. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  30266. if (!source) {
  30267. return this._sourceNormals;
  30268. }
  30269. this._sourceNormals = new Float32Array(source);
  30270. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  30271. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  30272. }
  30273. }
  30274. return this._sourceNormals;
  30275. };
  30276. /**
  30277. * Updates the vertex buffer by applying transformation from the bones.
  30278. * Returns the Mesh.
  30279. *
  30280. * @param {skeleton} skeleton to apply
  30281. */
  30282. Mesh.prototype.applySkeleton = function (skeleton) {
  30283. if (!this.geometry) {
  30284. return this;
  30285. }
  30286. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  30287. return this;
  30288. }
  30289. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  30290. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  30291. return this;
  30292. }
  30293. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  30294. return this;
  30295. }
  30296. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  30297. return this;
  30298. }
  30299. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  30300. return this;
  30301. }
  30302. if (!this._sourcePositions) {
  30303. var submeshes = this.subMeshes.slice();
  30304. this.setPositionsForCPUSkinning();
  30305. this.subMeshes = submeshes;
  30306. }
  30307. if (!this._sourceNormals) {
  30308. this.setNormalsForCPUSkinning();
  30309. }
  30310. // positionsData checks for not being Float32Array will only pass at most once
  30311. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30312. if (!positionsData) {
  30313. return this;
  30314. }
  30315. if (!(positionsData instanceof Float32Array)) {
  30316. positionsData = new Float32Array(positionsData);
  30317. }
  30318. // normalsData checks for not being Float32Array will only pass at most once
  30319. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  30320. if (!normalsData) {
  30321. return this;
  30322. }
  30323. if (!(normalsData instanceof Float32Array)) {
  30324. normalsData = new Float32Array(normalsData);
  30325. }
  30326. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  30327. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  30328. if (!matricesWeightsData || !matricesIndicesData) {
  30329. return this;
  30330. }
  30331. var needExtras = this.numBoneInfluencers > 4;
  30332. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  30333. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  30334. var skeletonMatrices = skeleton.getTransformMatrices(this);
  30335. var tempVector3 = BABYLON.Vector3.Zero();
  30336. var finalMatrix = new BABYLON.Matrix();
  30337. var tempMatrix = new BABYLON.Matrix();
  30338. var matWeightIdx = 0;
  30339. var inf;
  30340. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  30341. var weight;
  30342. for (inf = 0; inf < 4; inf++) {
  30343. weight = matricesWeightsData[matWeightIdx + inf];
  30344. if (weight > 0) {
  30345. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  30346. finalMatrix.addToSelf(tempMatrix);
  30347. }
  30348. else
  30349. break;
  30350. }
  30351. if (needExtras) {
  30352. for (inf = 0; inf < 4; inf++) {
  30353. weight = matricesWeightsExtraData[matWeightIdx + inf];
  30354. if (weight > 0) {
  30355. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  30356. finalMatrix.addToSelf(tempMatrix);
  30357. }
  30358. else
  30359. break;
  30360. }
  30361. }
  30362. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  30363. tempVector3.toArray(positionsData, index);
  30364. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  30365. tempVector3.toArray(normalsData, index);
  30366. finalMatrix.reset();
  30367. }
  30368. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  30369. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  30370. return this;
  30371. };
  30372. // Tools
  30373. /**
  30374. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  30375. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  30376. */
  30377. Mesh.MinMax = function (meshes) {
  30378. var minVector = null;
  30379. var maxVector = null;
  30380. meshes.forEach(function (mesh, index, array) {
  30381. var boundingInfo = mesh.getBoundingInfo();
  30382. var boundingBox = boundingInfo.boundingBox;
  30383. if (!minVector || !maxVector) {
  30384. minVector = boundingBox.minimumWorld;
  30385. maxVector = boundingBox.maximumWorld;
  30386. }
  30387. else {
  30388. minVector.minimizeInPlace(boundingBox.minimumWorld);
  30389. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  30390. }
  30391. });
  30392. if (!minVector || !maxVector) {
  30393. return {
  30394. min: BABYLON.Vector3.Zero(),
  30395. max: BABYLON.Vector3.Zero()
  30396. };
  30397. }
  30398. return {
  30399. min: minVector,
  30400. max: maxVector
  30401. };
  30402. };
  30403. /**
  30404. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  30405. */
  30406. Mesh.Center = function (meshesOrMinMaxVector) {
  30407. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  30408. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  30409. };
  30410. /**
  30411. * Merge the array of meshes into a single mesh for performance reasons.
  30412. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  30413. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  30414. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  30415. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  30416. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  30417. */
  30418. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  30419. if (disposeSource === void 0) { disposeSource = true; }
  30420. var index;
  30421. if (!allow32BitsIndices) {
  30422. var totalVertices = 0;
  30423. // Counting vertices
  30424. for (index = 0; index < meshes.length; index++) {
  30425. if (meshes[index]) {
  30426. totalVertices += meshes[index].getTotalVertices();
  30427. if (totalVertices > 65536) {
  30428. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  30429. return null;
  30430. }
  30431. }
  30432. }
  30433. }
  30434. // Merge
  30435. var vertexData = null;
  30436. var otherVertexData;
  30437. var indiceArray = new Array();
  30438. var source = null;
  30439. for (index = 0; index < meshes.length; index++) {
  30440. if (meshes[index]) {
  30441. meshes[index].computeWorldMatrix(true);
  30442. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  30443. otherVertexData.transform(meshes[index].getWorldMatrix());
  30444. if (vertexData) {
  30445. vertexData.merge(otherVertexData);
  30446. }
  30447. else {
  30448. vertexData = otherVertexData;
  30449. source = meshes[index];
  30450. }
  30451. if (subdivideWithSubMeshes) {
  30452. indiceArray.push(meshes[index].getTotalIndices());
  30453. }
  30454. }
  30455. }
  30456. source = source;
  30457. if (!meshSubclass) {
  30458. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  30459. }
  30460. vertexData.applyToMesh(meshSubclass);
  30461. // Setting properties
  30462. meshSubclass.material = source.material;
  30463. meshSubclass.checkCollisions = source.checkCollisions;
  30464. // Cleaning
  30465. if (disposeSource) {
  30466. for (index = 0; index < meshes.length; index++) {
  30467. if (meshes[index]) {
  30468. meshes[index].dispose();
  30469. }
  30470. }
  30471. }
  30472. // Subdivide
  30473. if (subdivideWithSubMeshes) {
  30474. //-- Suppresions du submesh global
  30475. meshSubclass.releaseSubMeshes();
  30476. index = 0;
  30477. var offset = 0;
  30478. //-- aplique la subdivision en fonction du tableau d'indices
  30479. while (index < indiceArray.length) {
  30480. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  30481. offset += indiceArray[index];
  30482. index++;
  30483. }
  30484. }
  30485. return meshSubclass;
  30486. };
  30487. // Consts
  30488. Mesh._FRONTSIDE = 0;
  30489. Mesh._BACKSIDE = 1;
  30490. Mesh._DOUBLESIDE = 2;
  30491. Mesh._DEFAULTSIDE = 0;
  30492. Mesh._NO_CAP = 0;
  30493. Mesh._CAP_START = 1;
  30494. Mesh._CAP_END = 2;
  30495. Mesh._CAP_ALL = 3;
  30496. return Mesh;
  30497. }(BABYLON.AbstractMesh));
  30498. BABYLON.Mesh = Mesh;
  30499. })(BABYLON || (BABYLON = {}));
  30500. //# sourceMappingURL=babylon.mesh.js.map
  30501. var BABYLON;
  30502. (function (BABYLON) {
  30503. var BaseSubMesh = /** @class */ (function () {
  30504. function BaseSubMesh() {
  30505. }
  30506. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  30507. get: function () {
  30508. return this._materialEffect;
  30509. },
  30510. enumerable: true,
  30511. configurable: true
  30512. });
  30513. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  30514. if (defines === void 0) { defines = null; }
  30515. if (this._materialEffect === effect) {
  30516. if (!effect) {
  30517. this._materialDefines = null;
  30518. }
  30519. return;
  30520. }
  30521. this._materialDefines = defines;
  30522. this._materialEffect = effect;
  30523. };
  30524. return BaseSubMesh;
  30525. }());
  30526. BABYLON.BaseSubMesh = BaseSubMesh;
  30527. var SubMesh = /** @class */ (function (_super) {
  30528. __extends(SubMesh, _super);
  30529. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  30530. if (createBoundingBox === void 0) { createBoundingBox = true; }
  30531. var _this = _super.call(this) || this;
  30532. _this.materialIndex = materialIndex;
  30533. _this.verticesStart = verticesStart;
  30534. _this.verticesCount = verticesCount;
  30535. _this.indexStart = indexStart;
  30536. _this.indexCount = indexCount;
  30537. _this._renderId = 0;
  30538. _this._mesh = mesh;
  30539. _this._renderingMesh = renderingMesh || mesh;
  30540. mesh.subMeshes.push(_this);
  30541. _this._trianglePlanes = [];
  30542. _this._id = mesh.subMeshes.length - 1;
  30543. if (createBoundingBox) {
  30544. _this.refreshBoundingInfo();
  30545. mesh.computeWorldMatrix(true);
  30546. }
  30547. return _this;
  30548. }
  30549. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  30550. if (createBoundingBox === void 0) { createBoundingBox = true; }
  30551. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  30552. };
  30553. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  30554. get: function () {
  30555. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  30556. },
  30557. enumerable: true,
  30558. configurable: true
  30559. });
  30560. /**
  30561. * Returns the submesh BoudingInfo object.
  30562. */
  30563. SubMesh.prototype.getBoundingInfo = function () {
  30564. if (this.IsGlobal) {
  30565. return this._mesh.getBoundingInfo();
  30566. }
  30567. return this._boundingInfo;
  30568. };
  30569. /**
  30570. * Sets the submesh BoundingInfo.
  30571. * Return the SubMesh.
  30572. */
  30573. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  30574. this._boundingInfo = boundingInfo;
  30575. return this;
  30576. };
  30577. /**
  30578. * Returns the mesh of the current submesh.
  30579. */
  30580. SubMesh.prototype.getMesh = function () {
  30581. return this._mesh;
  30582. };
  30583. /**
  30584. * Returns the rendering mesh of the submesh.
  30585. */
  30586. SubMesh.prototype.getRenderingMesh = function () {
  30587. return this._renderingMesh;
  30588. };
  30589. /**
  30590. * Returns the submesh material.
  30591. */
  30592. SubMesh.prototype.getMaterial = function () {
  30593. var rootMaterial = this._renderingMesh.material;
  30594. if (rootMaterial === null || rootMaterial === undefined) {
  30595. return this._mesh.getScene().defaultMaterial;
  30596. }
  30597. else if (rootMaterial.getSubMaterial) {
  30598. var multiMaterial = rootMaterial;
  30599. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  30600. if (this._currentMaterial !== effectiveMaterial) {
  30601. this._currentMaterial = effectiveMaterial;
  30602. this._materialDefines = null;
  30603. }
  30604. return effectiveMaterial;
  30605. }
  30606. return rootMaterial;
  30607. };
  30608. // Methods
  30609. /**
  30610. * Sets a new updated BoundingInfo object to the submesh.
  30611. * Returns the SubMesh.
  30612. */
  30613. SubMesh.prototype.refreshBoundingInfo = function () {
  30614. this._lastColliderWorldVertices = null;
  30615. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  30616. return this;
  30617. }
  30618. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30619. if (!data) {
  30620. this._boundingInfo = this._mesh.getBoundingInfo();
  30621. return this;
  30622. }
  30623. var indices = this._renderingMesh.getIndices();
  30624. var extend;
  30625. //is this the only submesh?
  30626. if (this.indexStart === 0 && this.indexCount === indices.length) {
  30627. var boundingInfo = this._renderingMesh.getBoundingInfo();
  30628. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  30629. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  30630. }
  30631. else {
  30632. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  30633. }
  30634. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  30635. return this;
  30636. };
  30637. SubMesh.prototype._checkCollision = function (collider) {
  30638. var boundingInfo = this._renderingMesh.getBoundingInfo();
  30639. return boundingInfo._checkCollision(collider);
  30640. };
  30641. /**
  30642. * Updates the submesh BoundingInfo.
  30643. * Returns the Submesh.
  30644. */
  30645. SubMesh.prototype.updateBoundingInfo = function (world) {
  30646. var boundingInfo = this.getBoundingInfo();
  30647. if (!boundingInfo) {
  30648. this.refreshBoundingInfo();
  30649. boundingInfo = this.getBoundingInfo();
  30650. }
  30651. boundingInfo.update(world);
  30652. return this;
  30653. };
  30654. /**
  30655. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  30656. * Boolean returned.
  30657. */
  30658. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  30659. var boundingInfo = this.getBoundingInfo();
  30660. if (!boundingInfo) {
  30661. return false;
  30662. }
  30663. return boundingInfo.isInFrustum(frustumPlanes);
  30664. };
  30665. /**
  30666. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  30667. * Boolean returned.
  30668. */
  30669. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  30670. var boundingInfo = this.getBoundingInfo();
  30671. if (!boundingInfo) {
  30672. return false;
  30673. }
  30674. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  30675. };
  30676. /**
  30677. * Renders the submesh.
  30678. * Returns it.
  30679. */
  30680. SubMesh.prototype.render = function (enableAlphaMode) {
  30681. this._renderingMesh.render(this, enableAlphaMode);
  30682. return this;
  30683. };
  30684. /**
  30685. * Returns a new Index Buffer.
  30686. * Type returned : WebGLBuffer.
  30687. */
  30688. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  30689. if (!this._linesIndexBuffer) {
  30690. var linesIndices = [];
  30691. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  30692. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  30693. }
  30694. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  30695. this.linesIndexCount = linesIndices.length;
  30696. }
  30697. return this._linesIndexBuffer;
  30698. };
  30699. /**
  30700. * True is the passed Ray intersects the submesh bounding box.
  30701. * Boolean returned.
  30702. */
  30703. SubMesh.prototype.canIntersects = function (ray) {
  30704. var boundingInfo = this.getBoundingInfo();
  30705. if (!boundingInfo) {
  30706. return false;
  30707. }
  30708. return ray.intersectsBox(boundingInfo.boundingBox);
  30709. };
  30710. /**
  30711. * Returns an object IntersectionInfo.
  30712. */
  30713. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  30714. var intersectInfo = null;
  30715. // LineMesh first as it's also a Mesh...
  30716. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  30717. var lineMesh = this._mesh;
  30718. // Line test
  30719. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  30720. var p0 = positions[indices[index]];
  30721. var p1 = positions[indices[index + 1]];
  30722. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  30723. if (length < 0) {
  30724. continue;
  30725. }
  30726. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  30727. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  30728. if (fastCheck) {
  30729. break;
  30730. }
  30731. }
  30732. }
  30733. }
  30734. else {
  30735. // Triangles test
  30736. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  30737. var p0 = positions[indices[index]];
  30738. var p1 = positions[indices[index + 1]];
  30739. var p2 = positions[indices[index + 2]];
  30740. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  30741. if (currentIntersectInfo) {
  30742. if (currentIntersectInfo.distance < 0) {
  30743. continue;
  30744. }
  30745. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  30746. intersectInfo = currentIntersectInfo;
  30747. intersectInfo.faceId = index / 3;
  30748. if (fastCheck) {
  30749. break;
  30750. }
  30751. }
  30752. }
  30753. }
  30754. }
  30755. return intersectInfo;
  30756. };
  30757. SubMesh.prototype._rebuild = function () {
  30758. if (this._linesIndexBuffer) {
  30759. this._linesIndexBuffer = null;
  30760. }
  30761. };
  30762. // Clone
  30763. /**
  30764. * Creates a new Submesh from the passed Mesh.
  30765. */
  30766. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  30767. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  30768. if (!this.IsGlobal) {
  30769. var boundingInfo = this.getBoundingInfo();
  30770. if (!boundingInfo) {
  30771. return result;
  30772. }
  30773. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  30774. }
  30775. return result;
  30776. };
  30777. // Dispose
  30778. /**
  30779. * Disposes the Submesh.
  30780. * Returns nothing.
  30781. */
  30782. SubMesh.prototype.dispose = function () {
  30783. if (this._linesIndexBuffer) {
  30784. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  30785. this._linesIndexBuffer = null;
  30786. }
  30787. // Remove from mesh
  30788. var index = this._mesh.subMeshes.indexOf(this);
  30789. this._mesh.subMeshes.splice(index, 1);
  30790. };
  30791. // Statics
  30792. /**
  30793. * Creates a new Submesh from the passed parameters :
  30794. * - materialIndex (integer) : the index of the main mesh material.
  30795. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  30796. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  30797. * - mesh (Mesh) : the main mesh to create the submesh from.
  30798. * - renderingMesh (optional Mesh) : rendering mesh.
  30799. */
  30800. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  30801. var minVertexIndex = Number.MAX_VALUE;
  30802. var maxVertexIndex = -Number.MAX_VALUE;
  30803. renderingMesh = (renderingMesh || mesh);
  30804. var indices = renderingMesh.getIndices();
  30805. for (var index = startIndex; index < startIndex + indexCount; index++) {
  30806. var vertexIndex = indices[index];
  30807. if (vertexIndex < minVertexIndex)
  30808. minVertexIndex = vertexIndex;
  30809. if (vertexIndex > maxVertexIndex)
  30810. maxVertexIndex = vertexIndex;
  30811. }
  30812. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  30813. };
  30814. return SubMesh;
  30815. }(BaseSubMesh));
  30816. BABYLON.SubMesh = SubMesh;
  30817. })(BABYLON || (BABYLON = {}));
  30818. //# sourceMappingURL=babylon.subMesh.js.map
  30819. var __assign = (this && this.__assign) || Object.assign || function(t) {
  30820. for (var s, i = 1, n = arguments.length; i < n; i++) {
  30821. s = arguments[i];
  30822. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  30823. t[p] = s[p];
  30824. }
  30825. return t;
  30826. };
  30827. var BABYLON;
  30828. (function (BABYLON) {
  30829. /**
  30830. * Manages the defines for the Material.
  30831. */
  30832. var MaterialDefines = /** @class */ (function () {
  30833. function MaterialDefines() {
  30834. this._isDirty = true;
  30835. this._areLightsDirty = true;
  30836. this._areAttributesDirty = true;
  30837. this._areTexturesDirty = true;
  30838. this._areFresnelDirty = true;
  30839. this._areMiscDirty = true;
  30840. this._areImageProcessingDirty = true;
  30841. this._normals = false;
  30842. this._uvs = false;
  30843. this._needNormals = false;
  30844. this._needUVs = false;
  30845. }
  30846. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  30847. /**
  30848. * Specifies if the material needs to be re-calculated.
  30849. */
  30850. get: function () {
  30851. return this._isDirty;
  30852. },
  30853. enumerable: true,
  30854. configurable: true
  30855. });
  30856. /**
  30857. * Marks the material to indicate that it has been re-calculated.
  30858. */
  30859. MaterialDefines.prototype.markAsProcessed = function () {
  30860. this._isDirty = false;
  30861. this._areAttributesDirty = false;
  30862. this._areTexturesDirty = false;
  30863. this._areFresnelDirty = false;
  30864. this._areLightsDirty = false;
  30865. this._areMiscDirty = false;
  30866. this._areImageProcessingDirty = false;
  30867. };
  30868. /**
  30869. * Marks the material to indicate that it needs to be re-calculated.
  30870. */
  30871. MaterialDefines.prototype.markAsUnprocessed = function () {
  30872. this._isDirty = true;
  30873. };
  30874. /**
  30875. * Marks the material to indicate all of its defines need to be re-calculated.
  30876. */
  30877. MaterialDefines.prototype.markAllAsDirty = function () {
  30878. this._areTexturesDirty = true;
  30879. this._areAttributesDirty = true;
  30880. this._areLightsDirty = true;
  30881. this._areFresnelDirty = true;
  30882. this._areMiscDirty = true;
  30883. this._areImageProcessingDirty = true;
  30884. this._isDirty = true;
  30885. };
  30886. /**
  30887. * Marks the material to indicate that image processing needs to be re-calculated.
  30888. */
  30889. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  30890. this._areImageProcessingDirty = true;
  30891. this._isDirty = true;
  30892. };
  30893. /**
  30894. * Marks the material to indicate the lights need to be re-calculated.
  30895. */
  30896. MaterialDefines.prototype.markAsLightDirty = function () {
  30897. this._areLightsDirty = true;
  30898. this._isDirty = true;
  30899. };
  30900. /**
  30901. * Marks the attribute state as changed.
  30902. */
  30903. MaterialDefines.prototype.markAsAttributesDirty = function () {
  30904. this._areAttributesDirty = true;
  30905. this._isDirty = true;
  30906. };
  30907. /**
  30908. * Marks the texture state as changed.
  30909. */
  30910. MaterialDefines.prototype.markAsTexturesDirty = function () {
  30911. this._areTexturesDirty = true;
  30912. this._isDirty = true;
  30913. };
  30914. /**
  30915. * Marks the fresnel state as changed.
  30916. */
  30917. MaterialDefines.prototype.markAsFresnelDirty = function () {
  30918. this._areFresnelDirty = true;
  30919. this._isDirty = true;
  30920. };
  30921. /**
  30922. * Marks the misc state as changed.
  30923. */
  30924. MaterialDefines.prototype.markAsMiscDirty = function () {
  30925. this._areMiscDirty = true;
  30926. this._isDirty = true;
  30927. };
  30928. /**
  30929. * Rebuilds the material defines.
  30930. */
  30931. MaterialDefines.prototype.rebuild = function () {
  30932. if (this._keys) {
  30933. delete this._keys;
  30934. }
  30935. this._keys = [];
  30936. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  30937. var key = _a[_i];
  30938. if (key[0] === "_") {
  30939. continue;
  30940. }
  30941. this._keys.push(key);
  30942. }
  30943. };
  30944. /**
  30945. * Specifies if two material defines are equal.
  30946. * @param other - A material define instance to compare to.
  30947. * @returns - Boolean indicating if the material defines are equal (true) or not (false).
  30948. */
  30949. MaterialDefines.prototype.isEqual = function (other) {
  30950. if (this._keys.length !== other._keys.length) {
  30951. return false;
  30952. }
  30953. for (var index = 0; index < this._keys.length; index++) {
  30954. var prop = this._keys[index];
  30955. if (this[prop] !== other[prop]) {
  30956. return false;
  30957. }
  30958. }
  30959. return true;
  30960. };
  30961. /**
  30962. * Clones this instance's defines to another instance.
  30963. * @param other - material defines to clone values to.
  30964. */
  30965. MaterialDefines.prototype.cloneTo = function (other) {
  30966. if (this._keys.length !== other._keys.length) {
  30967. other._keys = this._keys.slice(0);
  30968. }
  30969. for (var index = 0; index < this._keys.length; index++) {
  30970. var prop = this._keys[index];
  30971. other[prop] = this[prop];
  30972. }
  30973. };
  30974. /**
  30975. * Resets the material define values.
  30976. */
  30977. MaterialDefines.prototype.reset = function () {
  30978. for (var index = 0; index < this._keys.length; index++) {
  30979. var prop = this._keys[index];
  30980. if (typeof (this[prop]) === "number") {
  30981. this[prop] = 0;
  30982. }
  30983. else {
  30984. this[prop] = false;
  30985. }
  30986. }
  30987. };
  30988. /**
  30989. * Converts the material define values to a string.
  30990. * @returns - String of material define information.
  30991. */
  30992. MaterialDefines.prototype.toString = function () {
  30993. var result = "";
  30994. for (var index = 0; index < this._keys.length; index++) {
  30995. var prop = this._keys[index];
  30996. var value = this[prop];
  30997. if (typeof (value) === "number") {
  30998. result += "#define " + prop + " " + this[prop] + "\n";
  30999. }
  31000. else if (value) {
  31001. result += "#define " + prop + "\n";
  31002. }
  31003. }
  31004. return result;
  31005. };
  31006. return MaterialDefines;
  31007. }());
  31008. BABYLON.MaterialDefines = MaterialDefines;
  31009. /**
  31010. * This offers the main features of a material in BJS.
  31011. */
  31012. var Material = /** @class */ (function () {
  31013. /**
  31014. * Creates a material instance.
  31015. * @param name - The name of the material.
  31016. * @param scene - The BJS scene to reference.
  31017. * @param doNotAdd - Specifies if the material should be added to the scene.
  31018. */
  31019. function Material(name, scene, doNotAdd) {
  31020. /**
  31021. * Specifies if the ready state should be checked on each call.
  31022. */
  31023. this.checkReadyOnEveryCall = false;
  31024. /**
  31025. * Specifies if the ready state should be checked once.
  31026. */
  31027. this.checkReadyOnlyOnce = false;
  31028. /**
  31029. * The state of the material.
  31030. */
  31031. this.state = "";
  31032. /**
  31033. * The alpha value of the material.
  31034. */
  31035. this._alpha = 1.0;
  31036. /**
  31037. * Specifies if back face culling is enabled.
  31038. */
  31039. this._backFaceCulling = true;
  31040. /**
  31041. * Specifies if the material should be serialized.
  31042. */
  31043. this.doNotSerialize = false;
  31044. /**
  31045. * Specifies if the effect should be stored on sub meshes.
  31046. */
  31047. this.storeEffectOnSubMeshes = false;
  31048. /**
  31049. * An event triggered when the material is disposed.
  31050. * @type {BABYLON.Observable}
  31051. */
  31052. this.onDisposeObservable = new BABYLON.Observable();
  31053. /**
  31054. * An event triggered when the material is bound.
  31055. * @type {BABYLON.Observable}
  31056. */
  31057. this.onBindObservable = new BABYLON.Observable();
  31058. /**
  31059. * An event triggered when the material is unbound.
  31060. * @type {BABYLON.Observable}
  31061. */
  31062. this.onUnBindObservable = new BABYLON.Observable();
  31063. /**
  31064. * Stores the value of the alpha mode.
  31065. */
  31066. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  31067. /**
  31068. * Stores the state of the need depth pre-pass value.
  31069. */
  31070. this._needDepthPrePass = false;
  31071. /**
  31072. * Specifies if depth writing should be disabled.
  31073. */
  31074. this.disableDepthWrite = false;
  31075. /**
  31076. * Specifies if depth writing should be forced.
  31077. */
  31078. this.forceDepthWrite = false;
  31079. /**
  31080. * Specifies if there should be a separate pass for culling.
  31081. */
  31082. this.separateCullingPass = false;
  31083. /**
  31084. * Stores the state specifing if fog should be enabled.
  31085. */
  31086. this._fogEnabled = true;
  31087. /**
  31088. * Stores the size of points.
  31089. */
  31090. this.pointSize = 1.0;
  31091. /**
  31092. * Stores the z offset value.
  31093. */
  31094. this.zOffset = 0;
  31095. /**
  31096. * Specifies if the material was previously ready.
  31097. */
  31098. this._wasPreviouslyReady = false;
  31099. /**
  31100. * Stores the fill mode state.
  31101. */
  31102. this._fillMode = Material.TriangleFillMode;
  31103. this.name = name;
  31104. this.id = name || BABYLON.Tools.RandomId();
  31105. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  31106. if (this._scene.useRightHandedSystem) {
  31107. this.sideOrientation = Material.ClockWiseSideOrientation;
  31108. }
  31109. else {
  31110. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  31111. }
  31112. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  31113. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  31114. if (!doNotAdd) {
  31115. this._scene.materials.push(this);
  31116. }
  31117. }
  31118. Object.defineProperty(Material, "TriangleFillMode", {
  31119. /**
  31120. * Returns the triangle fill mode.
  31121. */
  31122. get: function () {
  31123. return Material._TriangleFillMode;
  31124. },
  31125. enumerable: true,
  31126. configurable: true
  31127. });
  31128. Object.defineProperty(Material, "WireFrameFillMode", {
  31129. /**
  31130. * Returns the wireframe mode.
  31131. */
  31132. get: function () {
  31133. return Material._WireFrameFillMode;
  31134. },
  31135. enumerable: true,
  31136. configurable: true
  31137. });
  31138. Object.defineProperty(Material, "PointFillMode", {
  31139. /**
  31140. * Returns the point fill mode.
  31141. */
  31142. get: function () {
  31143. return Material._PointFillMode;
  31144. },
  31145. enumerable: true,
  31146. configurable: true
  31147. });
  31148. Object.defineProperty(Material, "PointListDrawMode", {
  31149. /**
  31150. * Returns the point list draw mode.
  31151. */
  31152. get: function () {
  31153. return Material._PointListDrawMode;
  31154. },
  31155. enumerable: true,
  31156. configurable: true
  31157. });
  31158. Object.defineProperty(Material, "LineListDrawMode", {
  31159. /**
  31160. * Returns the line list draw mode.
  31161. */
  31162. get: function () {
  31163. return Material._LineListDrawMode;
  31164. },
  31165. enumerable: true,
  31166. configurable: true
  31167. });
  31168. Object.defineProperty(Material, "LineLoopDrawMode", {
  31169. /**
  31170. * Returns the line loop draw mode.
  31171. */
  31172. get: function () {
  31173. return Material._LineLoopDrawMode;
  31174. },
  31175. enumerable: true,
  31176. configurable: true
  31177. });
  31178. Object.defineProperty(Material, "LineStripDrawMode", {
  31179. /**
  31180. * Returns the line strip draw mode.
  31181. */
  31182. get: function () {
  31183. return Material._LineStripDrawMode;
  31184. },
  31185. enumerable: true,
  31186. configurable: true
  31187. });
  31188. Object.defineProperty(Material, "TriangleStripDrawMode", {
  31189. /**
  31190. * Returns the triangle strip draw mode.
  31191. */
  31192. get: function () {
  31193. return Material._TriangleStripDrawMode;
  31194. },
  31195. enumerable: true,
  31196. configurable: true
  31197. });
  31198. Object.defineProperty(Material, "TriangleFanDrawMode", {
  31199. /**
  31200. * Returns the triangle fan draw mode.
  31201. */
  31202. get: function () {
  31203. return Material._TriangleFanDrawMode;
  31204. },
  31205. enumerable: true,
  31206. configurable: true
  31207. });
  31208. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  31209. /**
  31210. * Returns the clock-wise side orientation.
  31211. */
  31212. get: function () {
  31213. return Material._ClockWiseSideOrientation;
  31214. },
  31215. enumerable: true,
  31216. configurable: true
  31217. });
  31218. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  31219. /**
  31220. * Returns the counter clock-wise side orientation.
  31221. */
  31222. get: function () {
  31223. return Material._CounterClockWiseSideOrientation;
  31224. },
  31225. enumerable: true,
  31226. configurable: true
  31227. });
  31228. Object.defineProperty(Material, "TextureDirtyFlag", {
  31229. /**
  31230. * Returns the dirty texture flag value.
  31231. */
  31232. get: function () {
  31233. return Material._TextureDirtyFlag;
  31234. },
  31235. enumerable: true,
  31236. configurable: true
  31237. });
  31238. Object.defineProperty(Material, "LightDirtyFlag", {
  31239. /**
  31240. * Returns the dirty light flag value.
  31241. */
  31242. get: function () {
  31243. return Material._LightDirtyFlag;
  31244. },
  31245. enumerable: true,
  31246. configurable: true
  31247. });
  31248. Object.defineProperty(Material, "FresnelDirtyFlag", {
  31249. /**
  31250. * Returns the dirty fresnel flag value.
  31251. */
  31252. get: function () {
  31253. return Material._FresnelDirtyFlag;
  31254. },
  31255. enumerable: true,
  31256. configurable: true
  31257. });
  31258. Object.defineProperty(Material, "AttributesDirtyFlag", {
  31259. /**
  31260. * Returns the dirty attributes flag value.
  31261. */
  31262. get: function () {
  31263. return Material._AttributesDirtyFlag;
  31264. },
  31265. enumerable: true,
  31266. configurable: true
  31267. });
  31268. Object.defineProperty(Material, "MiscDirtyFlag", {
  31269. /**
  31270. * Returns the dirty misc flag value.
  31271. */
  31272. get: function () {
  31273. return Material._MiscDirtyFlag;
  31274. },
  31275. enumerable: true,
  31276. configurable: true
  31277. });
  31278. Object.defineProperty(Material.prototype, "alpha", {
  31279. /**
  31280. * Gets the alpha value of the material.
  31281. */
  31282. get: function () {
  31283. return this._alpha;
  31284. },
  31285. /**
  31286. * Sets the alpha value of the material.
  31287. */
  31288. set: function (value) {
  31289. if (this._alpha === value) {
  31290. return;
  31291. }
  31292. this._alpha = value;
  31293. this.markAsDirty(Material.MiscDirtyFlag);
  31294. },
  31295. enumerable: true,
  31296. configurable: true
  31297. });
  31298. Object.defineProperty(Material.prototype, "backFaceCulling", {
  31299. /**
  31300. * Gets the back-face culling state.
  31301. */
  31302. get: function () {
  31303. return this._backFaceCulling;
  31304. },
  31305. /**
  31306. * Sets the back-face culling state.
  31307. */
  31308. set: function (value) {
  31309. if (this._backFaceCulling === value) {
  31310. return;
  31311. }
  31312. this._backFaceCulling = value;
  31313. this.markAsDirty(Material.TextureDirtyFlag);
  31314. },
  31315. enumerable: true,
  31316. configurable: true
  31317. });
  31318. Object.defineProperty(Material.prototype, "onDispose", {
  31319. /**
  31320. * Called during a dispose event.
  31321. */
  31322. set: function (callback) {
  31323. if (this._onDisposeObserver) {
  31324. this.onDisposeObservable.remove(this._onDisposeObserver);
  31325. }
  31326. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  31327. },
  31328. enumerable: true,
  31329. configurable: true
  31330. });
  31331. Object.defineProperty(Material.prototype, "onBind", {
  31332. /**
  31333. * Called during a bind event.
  31334. */
  31335. set: function (callback) {
  31336. if (this._onBindObserver) {
  31337. this.onBindObservable.remove(this._onBindObserver);
  31338. }
  31339. this._onBindObserver = this.onBindObservable.add(callback);
  31340. },
  31341. enumerable: true,
  31342. configurable: true
  31343. });
  31344. Object.defineProperty(Material.prototype, "alphaMode", {
  31345. /**
  31346. * Gets the value of the alpha mode.
  31347. */
  31348. get: function () {
  31349. return this._alphaMode;
  31350. },
  31351. /**
  31352. * Sets the value of the alpha mode.
  31353. */
  31354. set: function (value) {
  31355. if (this._alphaMode === value) {
  31356. return;
  31357. }
  31358. this._alphaMode = value;
  31359. this.markAsDirty(Material.TextureDirtyFlag);
  31360. },
  31361. enumerable: true,
  31362. configurable: true
  31363. });
  31364. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  31365. /**
  31366. * Gets the depth pre-pass value.
  31367. */
  31368. get: function () {
  31369. return this._needDepthPrePass;
  31370. },
  31371. /**
  31372. * Sets the need depth pre-pass value.
  31373. */
  31374. set: function (value) {
  31375. if (this._needDepthPrePass === value) {
  31376. return;
  31377. }
  31378. this._needDepthPrePass = value;
  31379. if (this._needDepthPrePass) {
  31380. this.checkReadyOnEveryCall = true;
  31381. }
  31382. },
  31383. enumerable: true,
  31384. configurable: true
  31385. });
  31386. Object.defineProperty(Material.prototype, "fogEnabled", {
  31387. /**
  31388. * Gets the value of the fog enabled state.
  31389. */
  31390. get: function () {
  31391. return this._fogEnabled;
  31392. },
  31393. /**
  31394. * Sets the state for enabling fog.
  31395. */
  31396. set: function (value) {
  31397. if (this._fogEnabled === value) {
  31398. return;
  31399. }
  31400. this._fogEnabled = value;
  31401. this.markAsDirty(Material.MiscDirtyFlag);
  31402. },
  31403. enumerable: true,
  31404. configurable: true
  31405. });
  31406. Object.defineProperty(Material.prototype, "wireframe", {
  31407. /**
  31408. * Gets a value specifying if wireframe mode is enabled.
  31409. */
  31410. get: function () {
  31411. return this._fillMode === Material.WireFrameFillMode;
  31412. },
  31413. /**
  31414. * Sets the state of wireframe mode.
  31415. */
  31416. set: function (value) {
  31417. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  31418. },
  31419. enumerable: true,
  31420. configurable: true
  31421. });
  31422. Object.defineProperty(Material.prototype, "pointsCloud", {
  31423. /**
  31424. * Gets the value specifying if point clouds are enabled.
  31425. */
  31426. get: function () {
  31427. return this._fillMode === Material.PointFillMode;
  31428. },
  31429. /**
  31430. * Sets the state of point cloud mode.
  31431. */
  31432. set: function (value) {
  31433. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  31434. },
  31435. enumerable: true,
  31436. configurable: true
  31437. });
  31438. Object.defineProperty(Material.prototype, "fillMode", {
  31439. /**
  31440. * Gets the material fill mode.
  31441. */
  31442. get: function () {
  31443. return this._fillMode;
  31444. },
  31445. /**
  31446. * Sets the material fill mode.
  31447. */
  31448. set: function (value) {
  31449. if (this._fillMode === value) {
  31450. return;
  31451. }
  31452. this._fillMode = value;
  31453. this.markAsDirty(Material.MiscDirtyFlag);
  31454. },
  31455. enumerable: true,
  31456. configurable: true
  31457. });
  31458. /**
  31459. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  31460. * subclasses should override adding information pertainent to themselves.
  31461. * @returns - String with material information.
  31462. */
  31463. Material.prototype.toString = function (fullDetails) {
  31464. var ret = "Name: " + this.name;
  31465. if (fullDetails) {
  31466. }
  31467. return ret;
  31468. };
  31469. /**
  31470. * Gets the class name of the material.
  31471. * @returns - String with the class name of the material.
  31472. */
  31473. Material.prototype.getClassName = function () {
  31474. return "Material";
  31475. };
  31476. Object.defineProperty(Material.prototype, "isFrozen", {
  31477. /**
  31478. * Specifies if updates for the material been locked.
  31479. */
  31480. get: function () {
  31481. return this.checkReadyOnlyOnce;
  31482. },
  31483. enumerable: true,
  31484. configurable: true
  31485. });
  31486. /**
  31487. * Locks updates for the material.
  31488. */
  31489. Material.prototype.freeze = function () {
  31490. this.checkReadyOnlyOnce = true;
  31491. };
  31492. /**
  31493. * Unlocks updates for the material.
  31494. */
  31495. Material.prototype.unfreeze = function () {
  31496. this.checkReadyOnlyOnce = false;
  31497. };
  31498. /**
  31499. * Specifies if the material is ready to be used.
  31500. * @param mesh - BJS mesh.
  31501. * @param useInstances - Specifies if instances should be used.
  31502. * @returns - Boolean indicating if the material is ready to be used.
  31503. */
  31504. Material.prototype.isReady = function (mesh, useInstances) {
  31505. return true;
  31506. };
  31507. /**
  31508. * Specifies that the submesh is ready to be used.
  31509. * @param mesh - BJS mesh.
  31510. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  31511. * @param useInstances - Specifies that instances should be used.
  31512. * @returns - boolean indicating that the submesh is ready or not.
  31513. */
  31514. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  31515. return false;
  31516. };
  31517. /**
  31518. * Returns the material effect.
  31519. * @returns - Nullable material effect.
  31520. */
  31521. Material.prototype.getEffect = function () {
  31522. return this._effect;
  31523. };
  31524. /**
  31525. * Returns the BJS scene.
  31526. * @returns - BJS Scene.
  31527. */
  31528. Material.prototype.getScene = function () {
  31529. return this._scene;
  31530. };
  31531. /**
  31532. * Specifies if the material will require alpha blending
  31533. * @returns - Boolean specifying if alpha blending is needed.
  31534. */
  31535. Material.prototype.needAlphaBlending = function () {
  31536. return (this.alpha < 1.0);
  31537. };
  31538. /**
  31539. * Specifies if the mesh will require alpha blending.
  31540. * @param mesh - BJS mesh.
  31541. * @returns - Boolean specifying if alpha blending is needed for the mesh.
  31542. */
  31543. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  31544. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  31545. };
  31546. /**
  31547. * Specifies if this material should be rendered in alpha test mode.
  31548. * @returns - Boolean specifying if an alpha test is needed.
  31549. */
  31550. Material.prototype.needAlphaTesting = function () {
  31551. return false;
  31552. };
  31553. /**
  31554. * Gets the texture used for the alpha test.
  31555. * @returns - Nullable alpha test texture.
  31556. */
  31557. Material.prototype.getAlphaTestTexture = function () {
  31558. return null;
  31559. };
  31560. /**
  31561. * Marks the material to indicate that it needs to be re-calculated.
  31562. */
  31563. Material.prototype.markDirty = function () {
  31564. this._wasPreviouslyReady = false;
  31565. };
  31566. Material.prototype._preBind = function (effect, overrideOrientation) {
  31567. if (overrideOrientation === void 0) { overrideOrientation = null; }
  31568. var engine = this._scene.getEngine();
  31569. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  31570. var reverse = orientation === Material.ClockWiseSideOrientation;
  31571. engine.enableEffect(effect ? effect : this._effect);
  31572. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  31573. return reverse;
  31574. };
  31575. /**
  31576. * Binds the material to the mesh.
  31577. * @param world - World transformation matrix.
  31578. * @param mesh - Mesh to bind the material to.
  31579. */
  31580. Material.prototype.bind = function (world, mesh) {
  31581. };
  31582. /**
  31583. * Binds the submesh to the material.
  31584. * @param world - World transformation matrix.
  31585. * @param mesh - Mesh containing the submesh.
  31586. * @param subMesh - Submesh to bind the material to.
  31587. */
  31588. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  31589. };
  31590. /**
  31591. * Binds the world matrix to the material.
  31592. * @param world - World transformation matrix.
  31593. */
  31594. Material.prototype.bindOnlyWorldMatrix = function (world) {
  31595. };
  31596. /**
  31597. * Binds the scene's uniform buffer to the effect.
  31598. * @param effect - Effect to bind to the scene uniform buffer.
  31599. * @param sceneUbo - Scene uniform buffer.
  31600. */
  31601. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  31602. sceneUbo.bindToEffect(effect, "Scene");
  31603. };
  31604. /**
  31605. * Binds the view matrix to the effect.
  31606. * @param effect - Effect to bind the view matrix to.
  31607. */
  31608. Material.prototype.bindView = function (effect) {
  31609. if (!this._useUBO) {
  31610. effect.setMatrix("view", this.getScene().getViewMatrix());
  31611. }
  31612. else {
  31613. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  31614. }
  31615. };
  31616. /**
  31617. * Binds the view projection matrix to the effect.
  31618. * @param effect - Effect to bind the view projection matrix to.
  31619. */
  31620. Material.prototype.bindViewProjection = function (effect) {
  31621. if (!this._useUBO) {
  31622. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  31623. }
  31624. else {
  31625. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  31626. }
  31627. };
  31628. /**
  31629. * Specifies if material alpha testing should be turned on for the mesh.
  31630. * @param mesh - BJS mesh.
  31631. */
  31632. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  31633. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  31634. };
  31635. /**
  31636. * Processes to execute after binding the material to a mesh.
  31637. * @param mesh - BJS mesh.
  31638. */
  31639. Material.prototype._afterBind = function (mesh) {
  31640. this._scene._cachedMaterial = this;
  31641. if (mesh) {
  31642. this._scene._cachedVisibility = mesh.visibility;
  31643. }
  31644. else {
  31645. this._scene._cachedVisibility = 1;
  31646. }
  31647. if (mesh) {
  31648. this.onBindObservable.notifyObservers(mesh);
  31649. }
  31650. if (this.disableDepthWrite) {
  31651. var engine = this._scene.getEngine();
  31652. this._cachedDepthWriteState = engine.getDepthWrite();
  31653. engine.setDepthWrite(false);
  31654. }
  31655. };
  31656. /**
  31657. * Unbinds the material from the mesh.
  31658. */
  31659. Material.prototype.unbind = function () {
  31660. this.onUnBindObservable.notifyObservers(this);
  31661. if (this.disableDepthWrite) {
  31662. var engine = this._scene.getEngine();
  31663. engine.setDepthWrite(this._cachedDepthWriteState);
  31664. }
  31665. };
  31666. /**
  31667. * Gets the active textures from the material.
  31668. * @returns - Array of textures.
  31669. */
  31670. Material.prototype.getActiveTextures = function () {
  31671. return [];
  31672. };
  31673. /**
  31674. * Specifies if the material uses a texture.
  31675. * @param texture - Texture to check against the material.
  31676. * @returns - Boolean specifying if the material uses the texture.
  31677. */
  31678. Material.prototype.hasTexture = function (texture) {
  31679. return false;
  31680. };
  31681. /**
  31682. * Makes a duplicate of the material, and gives it a new name.
  31683. * @param name - Name to call the duplicated material.
  31684. * @returns - Nullable cloned material
  31685. */
  31686. Material.prototype.clone = function (name) {
  31687. return null;
  31688. };
  31689. /**
  31690. * Gets the meshes bound to the material.
  31691. * @returns - Array of meshes bound to the material.
  31692. */
  31693. Material.prototype.getBindedMeshes = function () {
  31694. var result = new Array();
  31695. for (var index = 0; index < this._scene.meshes.length; index++) {
  31696. var mesh = this._scene.meshes[index];
  31697. if (mesh.material === this) {
  31698. result.push(mesh);
  31699. }
  31700. }
  31701. return result;
  31702. };
  31703. /**
  31704. * Force shader compilation
  31705. * @param mesh - BJS mesh.
  31706. * @param onCompiled - function to execute once the material is compiled.
  31707. * @param options - options to pass to this function.
  31708. */
  31709. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  31710. var _this = this;
  31711. var localOptions = __assign({ clipPlane: false }, options);
  31712. var subMesh = new BABYLON.BaseSubMesh();
  31713. var scene = this.getScene();
  31714. var checkReady = function () {
  31715. if (!_this._scene || !_this._scene.getEngine()) {
  31716. return;
  31717. }
  31718. if (subMesh._materialDefines) {
  31719. subMesh._materialDefines._renderId = -1;
  31720. }
  31721. var clipPlaneState = scene.clipPlane;
  31722. if (localOptions.clipPlane) {
  31723. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  31724. }
  31725. if (_this.storeEffectOnSubMeshes) {
  31726. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  31727. if (onCompiled) {
  31728. onCompiled(_this);
  31729. }
  31730. }
  31731. else {
  31732. setTimeout(checkReady, 16);
  31733. }
  31734. }
  31735. else {
  31736. if (_this.isReady(mesh)) {
  31737. if (onCompiled) {
  31738. onCompiled(_this);
  31739. }
  31740. }
  31741. else {
  31742. setTimeout(checkReady, 16);
  31743. }
  31744. }
  31745. if (localOptions.clipPlane) {
  31746. scene.clipPlane = clipPlaneState;
  31747. }
  31748. };
  31749. checkReady();
  31750. };
  31751. /**
  31752. * Force shader compilation.
  31753. * @param mesh The mesh that will use this material
  31754. * @param options Additional options for compiling the shaders
  31755. * @returns A promise that resolves when the compilation completes
  31756. */
  31757. Material.prototype.forceCompilationAsync = function (mesh, options) {
  31758. var _this = this;
  31759. return new Promise(function (resolve) {
  31760. _this.forceCompilation(mesh, function () {
  31761. resolve();
  31762. }, options);
  31763. });
  31764. };
  31765. /**
  31766. * Marks a define in the material to indicate that it needs to be re-computed.
  31767. * @param flag - Material define flag.
  31768. */
  31769. Material.prototype.markAsDirty = function (flag) {
  31770. if (flag & Material.TextureDirtyFlag) {
  31771. this._markAllSubMeshesAsTexturesDirty();
  31772. }
  31773. if (flag & Material.LightDirtyFlag) {
  31774. this._markAllSubMeshesAsLightsDirty();
  31775. }
  31776. if (flag & Material.FresnelDirtyFlag) {
  31777. this._markAllSubMeshesAsFresnelDirty();
  31778. }
  31779. if (flag & Material.AttributesDirtyFlag) {
  31780. this._markAllSubMeshesAsAttributesDirty();
  31781. }
  31782. if (flag & Material.MiscDirtyFlag) {
  31783. this._markAllSubMeshesAsMiscDirty();
  31784. }
  31785. this.getScene().resetCachedMaterial();
  31786. };
  31787. /**
  31788. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated.
  31789. * @param func - function which checks material defines against the submeshes.
  31790. */
  31791. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  31792. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  31793. var mesh = _a[_i];
  31794. if (!mesh.subMeshes) {
  31795. continue;
  31796. }
  31797. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  31798. var subMesh = _c[_b];
  31799. if (subMesh.getMaterial() !== this) {
  31800. continue;
  31801. }
  31802. if (!subMesh._materialDefines) {
  31803. continue;
  31804. }
  31805. func(subMesh._materialDefines);
  31806. }
  31807. }
  31808. };
  31809. /**
  31810. * Indicates that image processing needs to be re-calculated for all submeshes.
  31811. */
  31812. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  31813. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  31814. };
  31815. /**
  31816. * Indicates that textures need to be re-calculated for all submeshes.
  31817. */
  31818. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  31819. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  31820. };
  31821. /**
  31822. * Indicates that fresnel needs to be re-calculated for all submeshes.
  31823. */
  31824. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  31825. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  31826. };
  31827. /**
  31828. * Indicates that fresnel and misc need to be re-calculated for all submeshes.
  31829. */
  31830. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  31831. this._markAllSubMeshesAsDirty(function (defines) {
  31832. defines.markAsFresnelDirty();
  31833. defines.markAsMiscDirty();
  31834. });
  31835. };
  31836. /**
  31837. * Indicates that lights need to be re-calculated for all submeshes.
  31838. */
  31839. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  31840. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  31841. };
  31842. /**
  31843. * Indicates that attributes need to be re-calculated for all submeshes.
  31844. */
  31845. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  31846. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  31847. };
  31848. /**
  31849. * Indicates that misc needs to be re-calculated for all submeshes.
  31850. */
  31851. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  31852. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  31853. };
  31854. /**
  31855. * Indicates that textures and misc need to be re-calculated for all submeshes.
  31856. */
  31857. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  31858. this._markAllSubMeshesAsDirty(function (defines) {
  31859. defines.markAsTexturesDirty();
  31860. defines.markAsMiscDirty();
  31861. });
  31862. };
  31863. /**
  31864. * Disposes the material.
  31865. * @param forceDisposeEffect - Specifies if effects should be force disposed.
  31866. * @param forceDisposeTextures - Specifies if textures should be force disposed.
  31867. */
  31868. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  31869. // Animations
  31870. this.getScene().stopAnimation(this);
  31871. this.getScene().freeProcessedMaterials();
  31872. // Remove from scene
  31873. var index = this._scene.materials.indexOf(this);
  31874. if (index >= 0) {
  31875. this._scene.materials.splice(index, 1);
  31876. }
  31877. // Remove from meshes
  31878. for (index = 0; index < this._scene.meshes.length; index++) {
  31879. var mesh = this._scene.meshes[index];
  31880. if (mesh.material === this) {
  31881. mesh.material = null;
  31882. if (mesh.geometry) {
  31883. var geometry = (mesh.geometry);
  31884. if (this.storeEffectOnSubMeshes) {
  31885. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  31886. var subMesh = _a[_i];
  31887. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  31888. if (forceDisposeEffect && subMesh._materialEffect) {
  31889. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  31890. }
  31891. }
  31892. }
  31893. else {
  31894. geometry._releaseVertexArrayObject(this._effect);
  31895. }
  31896. }
  31897. }
  31898. }
  31899. this._uniformBuffer.dispose();
  31900. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  31901. if (forceDisposeEffect && this._effect) {
  31902. if (!this.storeEffectOnSubMeshes) {
  31903. this._scene.getEngine()._releaseEffect(this._effect);
  31904. }
  31905. this._effect = null;
  31906. }
  31907. // Callback
  31908. this.onDisposeObservable.notifyObservers(this);
  31909. this.onDisposeObservable.clear();
  31910. this.onBindObservable.clear();
  31911. this.onUnBindObservable.clear();
  31912. };
  31913. /**
  31914. * Serializes this material.
  31915. * @returns - serialized material object.
  31916. */
  31917. Material.prototype.serialize = function () {
  31918. return BABYLON.SerializationHelper.Serialize(this);
  31919. };
  31920. /**
  31921. * Creates a MultiMaterial from parse MultiMaterial data.
  31922. * @param parsedMultiMaterial - Parsed MultiMaterial data.
  31923. * @param scene - BJS scene.
  31924. * @returns - MultiMaterial.
  31925. */
  31926. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  31927. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  31928. multiMaterial.id = parsedMultiMaterial.id;
  31929. if (BABYLON.Tags) {
  31930. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  31931. }
  31932. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  31933. var subMatId = parsedMultiMaterial.materials[matIndex];
  31934. if (subMatId) {
  31935. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  31936. }
  31937. else {
  31938. multiMaterial.subMaterials.push(null);
  31939. }
  31940. }
  31941. return multiMaterial;
  31942. };
  31943. /**
  31944. * Creates a material from parsed material data.
  31945. * @param parsedMaterial - Parsed material data.
  31946. * @param scene - BJS scene.
  31947. * @param rootUrl - Root URL containing the material information.
  31948. * @returns - Parsed material.
  31949. */
  31950. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  31951. if (!parsedMaterial.customType || parsedMaterial.customType === "BABYLON.StandardMaterial") {
  31952. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  31953. }
  31954. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  31955. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  31956. if (!BABYLON.LegacyPBRMaterial) {
  31957. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  31958. return;
  31959. }
  31960. }
  31961. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  31962. return materialType.Parse(parsedMaterial, scene, rootUrl);
  31963. ;
  31964. };
  31965. // Triangle views
  31966. Material._TriangleFillMode = 0;
  31967. Material._WireFrameFillMode = 1;
  31968. Material._PointFillMode = 2;
  31969. // Draw modes
  31970. Material._PointListDrawMode = 3;
  31971. Material._LineListDrawMode = 4;
  31972. Material._LineLoopDrawMode = 5;
  31973. Material._LineStripDrawMode = 6;
  31974. Material._TriangleStripDrawMode = 7;
  31975. Material._TriangleFanDrawMode = 8;
  31976. /**
  31977. * Stores the clock-wise side orientation.
  31978. */
  31979. Material._ClockWiseSideOrientation = 0;
  31980. /**
  31981. * Stores the counter clock-wise side orientation.
  31982. */
  31983. Material._CounterClockWiseSideOrientation = 1;
  31984. /**
  31985. * The dirty texture flag value.
  31986. */
  31987. Material._TextureDirtyFlag = 1;
  31988. /**
  31989. * The dirty light flag value.
  31990. */
  31991. Material._LightDirtyFlag = 2;
  31992. /**
  31993. * The dirty fresnel flag value.
  31994. */
  31995. Material._FresnelDirtyFlag = 4;
  31996. /**
  31997. * The dirty attribute flag value.
  31998. */
  31999. Material._AttributesDirtyFlag = 8;
  32000. /**
  32001. * The dirty misc flag value.
  32002. */
  32003. Material._MiscDirtyFlag = 16;
  32004. __decorate([
  32005. BABYLON.serialize()
  32006. ], Material.prototype, "id", void 0);
  32007. __decorate([
  32008. BABYLON.serialize()
  32009. ], Material.prototype, "name", void 0);
  32010. __decorate([
  32011. BABYLON.serialize()
  32012. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  32013. __decorate([
  32014. BABYLON.serialize()
  32015. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  32016. __decorate([
  32017. BABYLON.serialize()
  32018. ], Material.prototype, "state", void 0);
  32019. __decorate([
  32020. BABYLON.serialize("alpha")
  32021. ], Material.prototype, "_alpha", void 0);
  32022. __decorate([
  32023. BABYLON.serialize("backFaceCulling")
  32024. ], Material.prototype, "_backFaceCulling", void 0);
  32025. __decorate([
  32026. BABYLON.serialize()
  32027. ], Material.prototype, "sideOrientation", void 0);
  32028. __decorate([
  32029. BABYLON.serialize("alphaMode")
  32030. ], Material.prototype, "_alphaMode", void 0);
  32031. __decorate([
  32032. BABYLON.serialize()
  32033. ], Material.prototype, "_needDepthPrePass", void 0);
  32034. __decorate([
  32035. BABYLON.serialize()
  32036. ], Material.prototype, "disableDepthWrite", void 0);
  32037. __decorate([
  32038. BABYLON.serialize()
  32039. ], Material.prototype, "forceDepthWrite", void 0);
  32040. __decorate([
  32041. BABYLON.serialize()
  32042. ], Material.prototype, "separateCullingPass", void 0);
  32043. __decorate([
  32044. BABYLON.serialize("fogEnabled")
  32045. ], Material.prototype, "_fogEnabled", void 0);
  32046. __decorate([
  32047. BABYLON.serialize()
  32048. ], Material.prototype, "pointSize", void 0);
  32049. __decorate([
  32050. BABYLON.serialize()
  32051. ], Material.prototype, "zOffset", void 0);
  32052. __decorate([
  32053. BABYLON.serialize()
  32054. ], Material.prototype, "wireframe", null);
  32055. __decorate([
  32056. BABYLON.serialize()
  32057. ], Material.prototype, "pointsCloud", null);
  32058. __decorate([
  32059. BABYLON.serialize()
  32060. ], Material.prototype, "fillMode", null);
  32061. return Material;
  32062. }());
  32063. BABYLON.Material = Material;
  32064. })(BABYLON || (BABYLON = {}));
  32065. //# sourceMappingURL=babylon.material.js.map
  32066. var BABYLON;
  32067. (function (BABYLON) {
  32068. var UniformBuffer = /** @class */ (function () {
  32069. /**
  32070. * Uniform buffer objects.
  32071. *
  32072. * Handles blocks of uniform on the GPU.
  32073. *
  32074. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  32075. *
  32076. * For more information, please refer to :
  32077. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  32078. */
  32079. function UniformBuffer(engine, data, dynamic) {
  32080. this._engine = engine;
  32081. this._noUBO = !engine.supportsUniformBuffers;
  32082. this._dynamic = dynamic;
  32083. this._data = data || [];
  32084. this._uniformLocations = {};
  32085. this._uniformSizes = {};
  32086. this._uniformLocationPointer = 0;
  32087. this._needSync = false;
  32088. if (this._noUBO) {
  32089. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  32090. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  32091. this.updateFloat = this._updateFloatForEffect;
  32092. this.updateFloat2 = this._updateFloat2ForEffect;
  32093. this.updateFloat3 = this._updateFloat3ForEffect;
  32094. this.updateFloat4 = this._updateFloat4ForEffect;
  32095. this.updateMatrix = this._updateMatrixForEffect;
  32096. this.updateVector3 = this._updateVector3ForEffect;
  32097. this.updateVector4 = this._updateVector4ForEffect;
  32098. this.updateColor3 = this._updateColor3ForEffect;
  32099. this.updateColor4 = this._updateColor4ForEffect;
  32100. }
  32101. else {
  32102. this._engine._uniformBuffers.push(this);
  32103. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  32104. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  32105. this.updateFloat = this._updateFloatForUniform;
  32106. this.updateFloat2 = this._updateFloat2ForUniform;
  32107. this.updateFloat3 = this._updateFloat3ForUniform;
  32108. this.updateFloat4 = this._updateFloat4ForUniform;
  32109. this.updateMatrix = this._updateMatrixForUniform;
  32110. this.updateVector3 = this._updateVector3ForUniform;
  32111. this.updateVector4 = this._updateVector4ForUniform;
  32112. this.updateColor3 = this._updateColor3ForUniform;
  32113. this.updateColor4 = this._updateColor4ForUniform;
  32114. }
  32115. }
  32116. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  32117. // Properties
  32118. /**
  32119. * Indicates if the buffer is using the WebGL2 UBO implementation,
  32120. * or just falling back on setUniformXXX calls.
  32121. */
  32122. get: function () {
  32123. return !this._noUBO;
  32124. },
  32125. enumerable: true,
  32126. configurable: true
  32127. });
  32128. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  32129. /**
  32130. * Indicates if the WebGL underlying uniform buffer is in sync
  32131. * with the javascript cache data.
  32132. */
  32133. get: function () {
  32134. return !this._needSync;
  32135. },
  32136. enumerable: true,
  32137. configurable: true
  32138. });
  32139. /**
  32140. * Indicates if the WebGL underlying uniform buffer is dynamic.
  32141. * Also, a dynamic UniformBuffer will disable cache verification and always
  32142. * update the underlying WebGL uniform buffer to the GPU.
  32143. */
  32144. UniformBuffer.prototype.isDynamic = function () {
  32145. return this._dynamic !== undefined;
  32146. };
  32147. /**
  32148. * The data cache on JS side.
  32149. */
  32150. UniformBuffer.prototype.getData = function () {
  32151. return this._bufferData;
  32152. };
  32153. /**
  32154. * The underlying WebGL Uniform buffer.
  32155. */
  32156. UniformBuffer.prototype.getBuffer = function () {
  32157. return this._buffer;
  32158. };
  32159. /**
  32160. * std140 layout specifies how to align data within an UBO structure.
  32161. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  32162. * for specs.
  32163. */
  32164. UniformBuffer.prototype._fillAlignment = function (size) {
  32165. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  32166. // and 4x4 matrices
  32167. // TODO : change if other types are used
  32168. var alignment;
  32169. if (size <= 2) {
  32170. alignment = size;
  32171. }
  32172. else {
  32173. alignment = 4;
  32174. }
  32175. if ((this._uniformLocationPointer % alignment) !== 0) {
  32176. var oldPointer = this._uniformLocationPointer;
  32177. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  32178. var diff = this._uniformLocationPointer - oldPointer;
  32179. for (var i = 0; i < diff; i++) {
  32180. this._data.push(0);
  32181. }
  32182. }
  32183. };
  32184. /**
  32185. * Adds an uniform in the buffer.
  32186. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  32187. * for the layout to be correct !
  32188. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32189. * @param {number|number[]} size Data size, or data directly.
  32190. */
  32191. UniformBuffer.prototype.addUniform = function (name, size) {
  32192. if (this._noUBO) {
  32193. return;
  32194. }
  32195. if (this._uniformLocations[name] !== undefined) {
  32196. // Already existing uniform
  32197. return;
  32198. }
  32199. // This function must be called in the order of the shader layout !
  32200. // size can be the size of the uniform, or data directly
  32201. var data;
  32202. if (size instanceof Array) {
  32203. data = size;
  32204. size = data.length;
  32205. }
  32206. else {
  32207. size = size;
  32208. data = [];
  32209. // Fill with zeros
  32210. for (var i = 0; i < size; i++) {
  32211. data.push(0);
  32212. }
  32213. }
  32214. this._fillAlignment(size);
  32215. this._uniformSizes[name] = size;
  32216. this._uniformLocations[name] = this._uniformLocationPointer;
  32217. this._uniformLocationPointer += size;
  32218. for (var i = 0; i < size; i++) {
  32219. this._data.push(data[i]);
  32220. }
  32221. this._needSync = true;
  32222. };
  32223. /**
  32224. * Wrapper for addUniform.
  32225. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32226. * @param {Matrix} mat A 4x4 matrix.
  32227. */
  32228. UniformBuffer.prototype.addMatrix = function (name, mat) {
  32229. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  32230. };
  32231. /**
  32232. * Wrapper for addUniform.
  32233. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32234. * @param {number} x
  32235. * @param {number} y
  32236. */
  32237. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  32238. var temp = [x, y];
  32239. this.addUniform(name, temp);
  32240. };
  32241. /**
  32242. * Wrapper for addUniform.
  32243. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32244. * @param {number} x
  32245. * @param {number} y
  32246. * @param {number} z
  32247. */
  32248. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  32249. var temp = [x, y, z];
  32250. this.addUniform(name, temp);
  32251. };
  32252. /**
  32253. * Wrapper for addUniform.
  32254. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32255. * @param {Color3} color
  32256. */
  32257. UniformBuffer.prototype.addColor3 = function (name, color) {
  32258. var temp = new Array();
  32259. color.toArray(temp);
  32260. this.addUniform(name, temp);
  32261. };
  32262. /**
  32263. * Wrapper for addUniform.
  32264. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32265. * @param {Color3} color
  32266. * @param {number} alpha
  32267. */
  32268. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  32269. var temp = new Array();
  32270. color.toArray(temp);
  32271. temp.push(alpha);
  32272. this.addUniform(name, temp);
  32273. };
  32274. /**
  32275. * Wrapper for addUniform.
  32276. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32277. * @param {Vector3} vector
  32278. */
  32279. UniformBuffer.prototype.addVector3 = function (name, vector) {
  32280. var temp = new Array();
  32281. vector.toArray(temp);
  32282. this.addUniform(name, temp);
  32283. };
  32284. /**
  32285. * Wrapper for addUniform.
  32286. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32287. */
  32288. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  32289. this.addUniform(name, 12);
  32290. };
  32291. /**
  32292. * Wrapper for addUniform.
  32293. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32294. */
  32295. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  32296. this.addUniform(name, 8);
  32297. };
  32298. /**
  32299. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  32300. */
  32301. UniformBuffer.prototype.create = function () {
  32302. if (this._noUBO) {
  32303. return;
  32304. }
  32305. if (this._buffer) {
  32306. return; // nothing to do
  32307. }
  32308. // See spec, alignment must be filled as a vec4
  32309. this._fillAlignment(4);
  32310. this._bufferData = new Float32Array(this._data);
  32311. this._rebuild();
  32312. this._needSync = true;
  32313. };
  32314. UniformBuffer.prototype._rebuild = function () {
  32315. if (this._noUBO) {
  32316. return;
  32317. }
  32318. if (this._dynamic) {
  32319. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  32320. }
  32321. else {
  32322. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  32323. }
  32324. };
  32325. /**
  32326. * Updates the WebGL Uniform Buffer on the GPU.
  32327. * If the `dynamic` flag is set to true, no cache comparison is done.
  32328. * Otherwise, the buffer will be updated only if the cache differs.
  32329. */
  32330. UniformBuffer.prototype.update = function () {
  32331. if (!this._buffer) {
  32332. this.create();
  32333. return;
  32334. }
  32335. if (!this._dynamic && !this._needSync) {
  32336. return;
  32337. }
  32338. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  32339. this._needSync = false;
  32340. };
  32341. /**
  32342. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  32343. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  32344. * @param {number[]|Float32Array} data Flattened data
  32345. * @param {number} size Size of the data.
  32346. */
  32347. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  32348. var location = this._uniformLocations[uniformName];
  32349. if (location === undefined) {
  32350. if (this._buffer) {
  32351. // Cannot add an uniform if the buffer is already created
  32352. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  32353. return;
  32354. }
  32355. this.addUniform(uniformName, size);
  32356. location = this._uniformLocations[uniformName];
  32357. }
  32358. if (!this._buffer) {
  32359. this.create();
  32360. }
  32361. if (!this._dynamic) {
  32362. // Cache for static uniform buffers
  32363. var changed = false;
  32364. for (var i = 0; i < size; i++) {
  32365. if (this._bufferData[location + i] !== data[i]) {
  32366. changed = true;
  32367. this._bufferData[location + i] = data[i];
  32368. }
  32369. }
  32370. this._needSync = this._needSync || changed;
  32371. }
  32372. else {
  32373. // No cache for dynamic
  32374. for (var i = 0; i < size; i++) {
  32375. this._bufferData[location + i] = data[i];
  32376. }
  32377. }
  32378. };
  32379. // Update methods
  32380. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  32381. // To match std140, matrix must be realigned
  32382. for (var i = 0; i < 3; i++) {
  32383. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  32384. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  32385. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  32386. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  32387. }
  32388. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  32389. };
  32390. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  32391. this._currentEffect.setMatrix3x3(name, matrix);
  32392. };
  32393. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  32394. this._currentEffect.setMatrix2x2(name, matrix);
  32395. };
  32396. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  32397. // To match std140, matrix must be realigned
  32398. for (var i = 0; i < 2; i++) {
  32399. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  32400. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  32401. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  32402. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  32403. }
  32404. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  32405. };
  32406. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  32407. this._currentEffect.setFloat(name, x);
  32408. };
  32409. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  32410. UniformBuffer._tempBuffer[0] = x;
  32411. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  32412. };
  32413. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  32414. if (suffix === void 0) { suffix = ""; }
  32415. this._currentEffect.setFloat2(name + suffix, x, y);
  32416. };
  32417. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  32418. if (suffix === void 0) { suffix = ""; }
  32419. UniformBuffer._tempBuffer[0] = x;
  32420. UniformBuffer._tempBuffer[1] = y;
  32421. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  32422. };
  32423. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  32424. if (suffix === void 0) { suffix = ""; }
  32425. this._currentEffect.setFloat3(name + suffix, x, y, z);
  32426. };
  32427. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  32428. if (suffix === void 0) { suffix = ""; }
  32429. UniformBuffer._tempBuffer[0] = x;
  32430. UniformBuffer._tempBuffer[1] = y;
  32431. UniformBuffer._tempBuffer[2] = z;
  32432. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  32433. };
  32434. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  32435. if (suffix === void 0) { suffix = ""; }
  32436. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  32437. };
  32438. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  32439. if (suffix === void 0) { suffix = ""; }
  32440. UniformBuffer._tempBuffer[0] = x;
  32441. UniformBuffer._tempBuffer[1] = y;
  32442. UniformBuffer._tempBuffer[2] = z;
  32443. UniformBuffer._tempBuffer[3] = w;
  32444. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  32445. };
  32446. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  32447. this._currentEffect.setMatrix(name, mat);
  32448. };
  32449. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  32450. this.updateUniform(name, mat.toArray(), 16);
  32451. };
  32452. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  32453. this._currentEffect.setVector3(name, vector);
  32454. };
  32455. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  32456. vector.toArray(UniformBuffer._tempBuffer);
  32457. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  32458. };
  32459. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  32460. this._currentEffect.setVector4(name, vector);
  32461. };
  32462. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  32463. vector.toArray(UniformBuffer._tempBuffer);
  32464. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  32465. };
  32466. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  32467. if (suffix === void 0) { suffix = ""; }
  32468. this._currentEffect.setColor3(name + suffix, color);
  32469. };
  32470. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  32471. if (suffix === void 0) { suffix = ""; }
  32472. color.toArray(UniformBuffer._tempBuffer);
  32473. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  32474. };
  32475. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  32476. if (suffix === void 0) { suffix = ""; }
  32477. this._currentEffect.setColor4(name + suffix, color, alpha);
  32478. };
  32479. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  32480. if (suffix === void 0) { suffix = ""; }
  32481. color.toArray(UniformBuffer._tempBuffer);
  32482. UniformBuffer._tempBuffer[3] = alpha;
  32483. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  32484. };
  32485. /**
  32486. * Sets a sampler uniform on the effect.
  32487. * @param {string} name Name of the sampler.
  32488. * @param {Texture} texture
  32489. */
  32490. UniformBuffer.prototype.setTexture = function (name, texture) {
  32491. this._currentEffect.setTexture(name, texture);
  32492. };
  32493. /**
  32494. * Directly updates the value of the uniform in the cache AND on the GPU.
  32495. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  32496. * @param {number[]|Float32Array} data Flattened data
  32497. */
  32498. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  32499. this.updateUniform(uniformName, data, data.length);
  32500. this.update();
  32501. };
  32502. /**
  32503. * Binds this uniform buffer to an effect.
  32504. * @param {Effect} effect
  32505. * @param {string} name Name of the uniform block in the shader.
  32506. */
  32507. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  32508. this._currentEffect = effect;
  32509. if (this._noUBO || !this._buffer) {
  32510. return;
  32511. }
  32512. effect.bindUniformBuffer(this._buffer, name);
  32513. };
  32514. /**
  32515. * Disposes the uniform buffer.
  32516. */
  32517. UniformBuffer.prototype.dispose = function () {
  32518. if (this._noUBO) {
  32519. return;
  32520. }
  32521. var index = this._engine._uniformBuffers.indexOf(this);
  32522. if (index !== -1) {
  32523. this._engine._uniformBuffers.splice(index, 1);
  32524. }
  32525. if (!this._buffer) {
  32526. return;
  32527. }
  32528. if (this._engine._releaseBuffer(this._buffer)) {
  32529. this._buffer = null;
  32530. }
  32531. };
  32532. // Pool for avoiding memory leaks
  32533. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  32534. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  32535. return UniformBuffer;
  32536. }());
  32537. BABYLON.UniformBuffer = UniformBuffer;
  32538. })(BABYLON || (BABYLON = {}));
  32539. //# sourceMappingURL=babylon.uniformBuffer.js.map
  32540. var BABYLON;
  32541. (function (BABYLON) {
  32542. var VertexData = /** @class */ (function () {
  32543. function VertexData() {
  32544. }
  32545. VertexData.prototype.set = function (data, kind) {
  32546. switch (kind) {
  32547. case BABYLON.VertexBuffer.PositionKind:
  32548. this.positions = data;
  32549. break;
  32550. case BABYLON.VertexBuffer.NormalKind:
  32551. this.normals = data;
  32552. break;
  32553. case BABYLON.VertexBuffer.TangentKind:
  32554. this.tangents = data;
  32555. break;
  32556. case BABYLON.VertexBuffer.UVKind:
  32557. this.uvs = data;
  32558. break;
  32559. case BABYLON.VertexBuffer.UV2Kind:
  32560. this.uvs2 = data;
  32561. break;
  32562. case BABYLON.VertexBuffer.UV3Kind:
  32563. this.uvs3 = data;
  32564. break;
  32565. case BABYLON.VertexBuffer.UV4Kind:
  32566. this.uvs4 = data;
  32567. break;
  32568. case BABYLON.VertexBuffer.UV5Kind:
  32569. this.uvs5 = data;
  32570. break;
  32571. case BABYLON.VertexBuffer.UV6Kind:
  32572. this.uvs6 = data;
  32573. break;
  32574. case BABYLON.VertexBuffer.ColorKind:
  32575. this.colors = data;
  32576. break;
  32577. case BABYLON.VertexBuffer.MatricesIndicesKind:
  32578. this.matricesIndices = data;
  32579. break;
  32580. case BABYLON.VertexBuffer.MatricesWeightsKind:
  32581. this.matricesWeights = data;
  32582. break;
  32583. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  32584. this.matricesIndicesExtra = data;
  32585. break;
  32586. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  32587. this.matricesWeightsExtra = data;
  32588. break;
  32589. }
  32590. };
  32591. /**
  32592. * Associates the vertexData to the passed Mesh.
  32593. * Sets it as updatable or not (default `false`).
  32594. * Returns the VertexData.
  32595. */
  32596. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  32597. this._applyTo(mesh, updatable);
  32598. return this;
  32599. };
  32600. /**
  32601. * Associates the vertexData to the passed Geometry.
  32602. * Sets it as updatable or not (default `false`).
  32603. * Returns the VertexData.
  32604. */
  32605. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  32606. this._applyTo(geometry, updatable);
  32607. return this;
  32608. };
  32609. /**
  32610. * Updates the associated mesh.
  32611. * Returns the VertexData.
  32612. */
  32613. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  32614. this._update(mesh);
  32615. return this;
  32616. };
  32617. /**
  32618. * Updates the associated geometry.
  32619. * Returns the VertexData.
  32620. */
  32621. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  32622. this._update(geometry);
  32623. return this;
  32624. };
  32625. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  32626. if (updatable === void 0) { updatable = false; }
  32627. if (this.positions) {
  32628. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  32629. }
  32630. if (this.normals) {
  32631. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  32632. }
  32633. if (this.tangents) {
  32634. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  32635. }
  32636. if (this.uvs) {
  32637. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  32638. }
  32639. if (this.uvs2) {
  32640. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  32641. }
  32642. if (this.uvs3) {
  32643. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  32644. }
  32645. if (this.uvs4) {
  32646. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  32647. }
  32648. if (this.uvs5) {
  32649. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  32650. }
  32651. if (this.uvs6) {
  32652. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  32653. }
  32654. if (this.colors) {
  32655. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  32656. }
  32657. if (this.matricesIndices) {
  32658. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  32659. }
  32660. if (this.matricesWeights) {
  32661. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  32662. }
  32663. if (this.matricesIndicesExtra) {
  32664. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  32665. }
  32666. if (this.matricesWeightsExtra) {
  32667. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  32668. }
  32669. if (this.indices) {
  32670. meshOrGeometry.setIndices(this.indices, null, updatable);
  32671. }
  32672. return this;
  32673. };
  32674. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  32675. if (this.positions) {
  32676. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  32677. }
  32678. if (this.normals) {
  32679. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  32680. }
  32681. if (this.tangents) {
  32682. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  32683. }
  32684. if (this.uvs) {
  32685. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  32686. }
  32687. if (this.uvs2) {
  32688. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  32689. }
  32690. if (this.uvs3) {
  32691. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  32692. }
  32693. if (this.uvs4) {
  32694. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  32695. }
  32696. if (this.uvs5) {
  32697. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  32698. }
  32699. if (this.uvs6) {
  32700. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  32701. }
  32702. if (this.colors) {
  32703. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  32704. }
  32705. if (this.matricesIndices) {
  32706. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  32707. }
  32708. if (this.matricesWeights) {
  32709. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  32710. }
  32711. if (this.matricesIndicesExtra) {
  32712. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  32713. }
  32714. if (this.matricesWeightsExtra) {
  32715. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  32716. }
  32717. if (this.indices) {
  32718. meshOrGeometry.setIndices(this.indices, null);
  32719. }
  32720. return this;
  32721. };
  32722. /**
  32723. * Transforms each position and each normal of the vertexData according to the passed Matrix.
  32724. * Returns the VertexData.
  32725. */
  32726. VertexData.prototype.transform = function (matrix) {
  32727. var transformed = BABYLON.Vector3.Zero();
  32728. var index;
  32729. if (this.positions) {
  32730. var position = BABYLON.Vector3.Zero();
  32731. for (index = 0; index < this.positions.length; index += 3) {
  32732. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  32733. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  32734. this.positions[index] = transformed.x;
  32735. this.positions[index + 1] = transformed.y;
  32736. this.positions[index + 2] = transformed.z;
  32737. }
  32738. }
  32739. if (this.normals) {
  32740. var normal = BABYLON.Vector3.Zero();
  32741. for (index = 0; index < this.normals.length; index += 3) {
  32742. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  32743. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  32744. this.normals[index] = transformed.x;
  32745. this.normals[index + 1] = transformed.y;
  32746. this.normals[index + 2] = transformed.z;
  32747. }
  32748. }
  32749. if (this.tangents) {
  32750. var tangent = BABYLON.Vector4.Zero();
  32751. var tangentTransformed = BABYLON.Vector4.Zero();
  32752. for (index = 0; index < this.tangents.length; index += 4) {
  32753. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  32754. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  32755. this.tangents[index] = tangentTransformed.x;
  32756. this.tangents[index + 1] = tangentTransformed.y;
  32757. this.tangents[index + 2] = tangentTransformed.z;
  32758. this.tangents[index + 3] = tangentTransformed.w;
  32759. }
  32760. }
  32761. return this;
  32762. };
  32763. /**
  32764. * Merges the passed VertexData into the current one.
  32765. * Returns the modified VertexData.
  32766. */
  32767. VertexData.prototype.merge = function (other) {
  32768. this._validate();
  32769. other._validate();
  32770. if (!this.normals !== !other.normals ||
  32771. !this.tangents !== !other.tangents ||
  32772. !this.uvs !== !other.uvs ||
  32773. !this.uvs2 !== !other.uvs2 ||
  32774. !this.uvs3 !== !other.uvs3 ||
  32775. !this.uvs4 !== !other.uvs4 ||
  32776. !this.uvs5 !== !other.uvs5 ||
  32777. !this.uvs6 !== !other.uvs6 ||
  32778. !this.colors !== !other.colors ||
  32779. !this.matricesIndices !== !other.matricesIndices ||
  32780. !this.matricesWeights !== !other.matricesWeights ||
  32781. !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||
  32782. !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
  32783. throw new Error("Cannot merge vertex data that do not have the same set of attributes");
  32784. }
  32785. if (other.indices) {
  32786. if (!this.indices) {
  32787. this.indices = [];
  32788. }
  32789. var offset = this.positions ? this.positions.length / 3 : 0;
  32790. for (var index = 0; index < other.indices.length; index++) {
  32791. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  32792. this.indices.push(other.indices[index] + offset);
  32793. }
  32794. }
  32795. this.positions = this._mergeElement(this.positions, other.positions);
  32796. this.normals = this._mergeElement(this.normals, other.normals);
  32797. this.tangents = this._mergeElement(this.tangents, other.tangents);
  32798. this.uvs = this._mergeElement(this.uvs, other.uvs);
  32799. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  32800. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  32801. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  32802. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  32803. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  32804. this.colors = this._mergeElement(this.colors, other.colors);
  32805. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  32806. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  32807. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  32808. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  32809. return this;
  32810. };
  32811. VertexData.prototype._mergeElement = function (source, other) {
  32812. if (!source) {
  32813. return other;
  32814. }
  32815. if (!other) {
  32816. return source;
  32817. }
  32818. var len = other.length + source.length;
  32819. var isSrcTypedArray = source instanceof Float32Array;
  32820. var isOthTypedArray = other instanceof Float32Array;
  32821. // use non-loop method when the source is Float32Array
  32822. if (isSrcTypedArray) {
  32823. var ret32 = new Float32Array(len);
  32824. ret32.set(source);
  32825. ret32.set(other, source.length);
  32826. return ret32;
  32827. // source is number[], when other is also use concat
  32828. }
  32829. else if (!isOthTypedArray) {
  32830. return source.concat(other);
  32831. // source is a number[], but other is a Float32Array, loop required
  32832. }
  32833. else {
  32834. var ret = source.slice(0); // copy source to a separate array
  32835. for (var i = 0, len = other.length; i < len; i++) {
  32836. ret.push(other[i]);
  32837. }
  32838. return ret;
  32839. }
  32840. };
  32841. VertexData.prototype._validate = function () {
  32842. if (!this.positions) {
  32843. throw new Error("Positions are required");
  32844. }
  32845. var getElementCount = function (kind, values) {
  32846. var stride = BABYLON.VertexBuffer.DeduceStride(kind);
  32847. if ((values.length % stride) !== 0) {
  32848. throw new Error("The " + kind + "s array count must be a multiple of " + stride);
  32849. }
  32850. return values.length / stride;
  32851. };
  32852. var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions);
  32853. var validateElementCount = function (kind, values) {
  32854. var elementCount = getElementCount(kind, values);
  32855. if (elementCount !== positionsElementCount) {
  32856. throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
  32857. }
  32858. };
  32859. if (this.normals)
  32860. validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals);
  32861. if (this.tangents)
  32862. validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents);
  32863. if (this.uvs)
  32864. validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs);
  32865. if (this.uvs2)
  32866. validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2);
  32867. if (this.uvs3)
  32868. validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3);
  32869. if (this.uvs4)
  32870. validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4);
  32871. if (this.uvs5)
  32872. validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5);
  32873. if (this.uvs6)
  32874. validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6);
  32875. if (this.colors)
  32876. validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors);
  32877. if (this.matricesIndices)
  32878. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices);
  32879. if (this.matricesWeights)
  32880. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights);
  32881. if (this.matricesIndicesExtra)
  32882. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
  32883. if (this.matricesWeightsExtra)
  32884. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
  32885. };
  32886. /**
  32887. * Serializes the VertexData.
  32888. * Returns a serialized object.
  32889. */
  32890. VertexData.prototype.serialize = function () {
  32891. var serializationObject = this.serialize();
  32892. if (this.positions) {
  32893. serializationObject.positions = this.positions;
  32894. }
  32895. if (this.normals) {
  32896. serializationObject.normals = this.normals;
  32897. }
  32898. if (this.tangents) {
  32899. serializationObject.tangents = this.tangents;
  32900. }
  32901. if (this.uvs) {
  32902. serializationObject.uvs = this.uvs;
  32903. }
  32904. if (this.uvs2) {
  32905. serializationObject.uvs2 = this.uvs2;
  32906. }
  32907. if (this.uvs3) {
  32908. serializationObject.uvs3 = this.uvs3;
  32909. }
  32910. if (this.uvs4) {
  32911. serializationObject.uvs4 = this.uvs4;
  32912. }
  32913. if (this.uvs5) {
  32914. serializationObject.uvs5 = this.uvs5;
  32915. }
  32916. if (this.uvs6) {
  32917. serializationObject.uvs6 = this.uvs6;
  32918. }
  32919. if (this.colors) {
  32920. serializationObject.colors = this.colors;
  32921. }
  32922. if (this.matricesIndices) {
  32923. serializationObject.matricesIndices = this.matricesIndices;
  32924. serializationObject.matricesIndices._isExpanded = true;
  32925. }
  32926. if (this.matricesWeights) {
  32927. serializationObject.matricesWeights = this.matricesWeights;
  32928. }
  32929. if (this.matricesIndicesExtra) {
  32930. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  32931. serializationObject.matricesIndicesExtra._isExpanded = true;
  32932. }
  32933. if (this.matricesWeightsExtra) {
  32934. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  32935. }
  32936. serializationObject.indices = this.indices;
  32937. return serializationObject;
  32938. };
  32939. // Statics
  32940. /**
  32941. * Returns the object VertexData associated to the passed mesh.
  32942. */
  32943. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  32944. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  32945. };
  32946. /**
  32947. * Returns the object VertexData associated to the passed geometry.
  32948. */
  32949. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  32950. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  32951. };
  32952. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  32953. var result = new VertexData();
  32954. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  32955. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  32956. }
  32957. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  32958. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  32959. }
  32960. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  32961. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  32962. }
  32963. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  32964. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  32965. }
  32966. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  32967. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  32968. }
  32969. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  32970. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  32971. }
  32972. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  32973. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  32974. }
  32975. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  32976. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  32977. }
  32978. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  32979. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  32980. }
  32981. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  32982. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  32983. }
  32984. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  32985. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  32986. }
  32987. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  32988. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  32989. }
  32990. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  32991. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  32992. }
  32993. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  32994. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  32995. }
  32996. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  32997. return result;
  32998. };
  32999. /**
  33000. * Creates the vertexData of the Ribbon.
  33001. */
  33002. VertexData.CreateRibbon = function (options) {
  33003. var pathArray = options.pathArray;
  33004. var closeArray = options.closeArray || false;
  33005. var closePath = options.closePath || false;
  33006. var invertUV = options.invertUV || false;
  33007. var defaultOffset = Math.floor(pathArray[0].length / 2);
  33008. var offset = options.offset || defaultOffset;
  33009. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  33010. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33011. var customUV = options.uvs;
  33012. var customColors = options.colors;
  33013. var positions = [];
  33014. var indices = [];
  33015. var normals = [];
  33016. var uvs = [];
  33017. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  33018. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  33019. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  33020. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  33021. var minlg; // minimal length among all paths from pathArray
  33022. var lg = []; // array of path lengths : nb of vertex per path
  33023. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  33024. var p; // path iterator
  33025. var i; // point iterator
  33026. var j; // point iterator
  33027. // if single path in pathArray
  33028. if (pathArray.length < 2) {
  33029. var ar1 = [];
  33030. var ar2 = [];
  33031. for (i = 0; i < pathArray[0].length - offset; i++) {
  33032. ar1.push(pathArray[0][i]);
  33033. ar2.push(pathArray[0][i + offset]);
  33034. }
  33035. pathArray = [ar1, ar2];
  33036. }
  33037. // positions and horizontal distances (u)
  33038. var idc = 0;
  33039. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  33040. var path;
  33041. var l;
  33042. minlg = pathArray[0].length;
  33043. var vectlg;
  33044. var dist;
  33045. for (p = 0; p < pathArray.length; p++) {
  33046. uTotalDistance[p] = 0;
  33047. us[p] = [0];
  33048. path = pathArray[p];
  33049. l = path.length;
  33050. minlg = (minlg < l) ? minlg : l;
  33051. j = 0;
  33052. while (j < l) {
  33053. positions.push(path[j].x, path[j].y, path[j].z);
  33054. if (j > 0) {
  33055. vectlg = path[j].subtract(path[j - 1]).length();
  33056. dist = vectlg + uTotalDistance[p];
  33057. us[p].push(dist);
  33058. uTotalDistance[p] = dist;
  33059. }
  33060. j++;
  33061. }
  33062. if (closePath) {
  33063. j--;
  33064. positions.push(path[0].x, path[0].y, path[0].z);
  33065. vectlg = path[j].subtract(path[0]).length();
  33066. dist = vectlg + uTotalDistance[p];
  33067. us[p].push(dist);
  33068. uTotalDistance[p] = dist;
  33069. }
  33070. lg[p] = l + closePathCorr;
  33071. idx[p] = idc;
  33072. idc += (l + closePathCorr);
  33073. }
  33074. // vertical distances (v)
  33075. var path1;
  33076. var path2;
  33077. var vertex1 = null;
  33078. var vertex2 = null;
  33079. for (i = 0; i < minlg + closePathCorr; i++) {
  33080. vTotalDistance[i] = 0;
  33081. vs[i] = [0];
  33082. for (p = 0; p < pathArray.length - 1; p++) {
  33083. path1 = pathArray[p];
  33084. path2 = pathArray[p + 1];
  33085. if (i === minlg) {
  33086. vertex1 = path1[0];
  33087. vertex2 = path2[0];
  33088. }
  33089. else {
  33090. vertex1 = path1[i];
  33091. vertex2 = path2[i];
  33092. }
  33093. vectlg = vertex2.subtract(vertex1).length();
  33094. dist = vectlg + vTotalDistance[i];
  33095. vs[i].push(dist);
  33096. vTotalDistance[i] = dist;
  33097. }
  33098. if (closeArray && vertex2 && vertex1) {
  33099. path1 = pathArray[p];
  33100. path2 = pathArray[0];
  33101. if (i === minlg) {
  33102. vertex2 = path2[0];
  33103. }
  33104. vectlg = vertex2.subtract(vertex1).length();
  33105. dist = vectlg + vTotalDistance[i];
  33106. vTotalDistance[i] = dist;
  33107. }
  33108. }
  33109. // uvs
  33110. var u;
  33111. var v;
  33112. if (customUV) {
  33113. for (p = 0; p < customUV.length; p++) {
  33114. uvs.push(customUV[p].x, customUV[p].y);
  33115. }
  33116. }
  33117. else {
  33118. for (p = 0; p < pathArray.length; p++) {
  33119. for (i = 0; i < minlg + closePathCorr; i++) {
  33120. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  33121. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  33122. if (invertUV) {
  33123. uvs.push(v, u);
  33124. }
  33125. else {
  33126. uvs.push(u, v);
  33127. }
  33128. }
  33129. }
  33130. }
  33131. // indices
  33132. p = 0; // path index
  33133. var pi = 0; // positions array index
  33134. var l1 = lg[p] - 1; // path1 length
  33135. var l2 = lg[p + 1] - 1; // path2 length
  33136. var min = (l1 < l2) ? l1 : l2; // current path stop index
  33137. var shft = idx[1] - idx[0]; // shift
  33138. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  33139. while (pi <= min && p < path1nb) {
  33140. // 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
  33141. indices.push(pi, pi + shft, pi + 1);
  33142. indices.push(pi + shft + 1, pi + 1, pi + shft);
  33143. pi += 1;
  33144. if (pi === min) {
  33145. p++;
  33146. if (p === lg.length - 1) {
  33147. shft = idx[0] - idx[p];
  33148. l1 = lg[p] - 1;
  33149. l2 = lg[0] - 1;
  33150. }
  33151. else {
  33152. shft = idx[p + 1] - idx[p];
  33153. l1 = lg[p] - 1;
  33154. l2 = lg[p + 1] - 1;
  33155. }
  33156. pi = idx[p];
  33157. min = (l1 < l2) ? l1 + pi : l2 + pi;
  33158. }
  33159. }
  33160. // normals
  33161. VertexData.ComputeNormals(positions, indices, normals);
  33162. if (closePath) {
  33163. var indexFirst = 0;
  33164. var indexLast = 0;
  33165. for (p = 0; p < pathArray.length; p++) {
  33166. indexFirst = idx[p] * 3;
  33167. if (p + 1 < pathArray.length) {
  33168. indexLast = (idx[p + 1] - 1) * 3;
  33169. }
  33170. else {
  33171. indexLast = normals.length - 3;
  33172. }
  33173. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  33174. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  33175. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  33176. normals[indexLast] = normals[indexFirst];
  33177. normals[indexLast + 1] = normals[indexFirst + 1];
  33178. normals[indexLast + 2] = normals[indexFirst + 2];
  33179. }
  33180. }
  33181. // sides
  33182. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33183. // Colors
  33184. var colors = null;
  33185. if (customColors) {
  33186. colors = new Float32Array(customColors.length * 4);
  33187. for (var c = 0; c < customColors.length; c++) {
  33188. colors[c * 4] = customColors[c].r;
  33189. colors[c * 4 + 1] = customColors[c].g;
  33190. colors[c * 4 + 2] = customColors[c].b;
  33191. colors[c * 4 + 3] = customColors[c].a;
  33192. }
  33193. }
  33194. // Result
  33195. var vertexData = new VertexData();
  33196. var positions32 = new Float32Array(positions);
  33197. var normals32 = new Float32Array(normals);
  33198. var uvs32 = new Float32Array(uvs);
  33199. vertexData.indices = indices;
  33200. vertexData.positions = positions32;
  33201. vertexData.normals = normals32;
  33202. vertexData.uvs = uvs32;
  33203. if (colors) {
  33204. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  33205. }
  33206. if (closePath) {
  33207. vertexData._idx = idx;
  33208. }
  33209. return vertexData;
  33210. };
  33211. /**
  33212. * Creates the VertexData of the Box.
  33213. */
  33214. VertexData.CreateBox = function (options) {
  33215. var normalsSource = [
  33216. new BABYLON.Vector3(0, 0, 1),
  33217. new BABYLON.Vector3(0, 0, -1),
  33218. new BABYLON.Vector3(1, 0, 0),
  33219. new BABYLON.Vector3(-1, 0, 0),
  33220. new BABYLON.Vector3(0, 1, 0),
  33221. new BABYLON.Vector3(0, -1, 0)
  33222. ];
  33223. var indices = [];
  33224. var positions = [];
  33225. var normals = [];
  33226. var uvs = [];
  33227. var width = options.width || options.size || 1;
  33228. var height = options.height || options.size || 1;
  33229. var depth = options.depth || options.size || 1;
  33230. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33231. var faceUV = options.faceUV || new Array(6);
  33232. var faceColors = options.faceColors;
  33233. var colors = [];
  33234. // default face colors and UV if undefined
  33235. for (var f = 0; f < 6; f++) {
  33236. if (faceUV[f] === undefined) {
  33237. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  33238. }
  33239. if (faceColors && faceColors[f] === undefined) {
  33240. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  33241. }
  33242. }
  33243. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  33244. // Create each face in turn.
  33245. for (var index = 0; index < normalsSource.length; index++) {
  33246. var normal = normalsSource[index];
  33247. // Get two vectors perpendicular to the face normal and to each other.
  33248. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  33249. var side2 = BABYLON.Vector3.Cross(normal, side1);
  33250. // Six indices (two triangles) per face.
  33251. var verticesLength = positions.length / 3;
  33252. indices.push(verticesLength);
  33253. indices.push(verticesLength + 1);
  33254. indices.push(verticesLength + 2);
  33255. indices.push(verticesLength);
  33256. indices.push(verticesLength + 2);
  33257. indices.push(verticesLength + 3);
  33258. // Four vertices per face.
  33259. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  33260. positions.push(vertex.x, vertex.y, vertex.z);
  33261. normals.push(normal.x, normal.y, normal.z);
  33262. uvs.push(faceUV[index].z, faceUV[index].w);
  33263. if (faceColors) {
  33264. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  33265. }
  33266. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  33267. positions.push(vertex.x, vertex.y, vertex.z);
  33268. normals.push(normal.x, normal.y, normal.z);
  33269. uvs.push(faceUV[index].x, faceUV[index].w);
  33270. if (faceColors) {
  33271. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  33272. }
  33273. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  33274. positions.push(vertex.x, vertex.y, vertex.z);
  33275. normals.push(normal.x, normal.y, normal.z);
  33276. uvs.push(faceUV[index].x, faceUV[index].y);
  33277. if (faceColors) {
  33278. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  33279. }
  33280. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  33281. positions.push(vertex.x, vertex.y, vertex.z);
  33282. normals.push(normal.x, normal.y, normal.z);
  33283. uvs.push(faceUV[index].z, faceUV[index].y);
  33284. if (faceColors) {
  33285. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  33286. }
  33287. }
  33288. // sides
  33289. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33290. // Result
  33291. var vertexData = new VertexData();
  33292. vertexData.indices = indices;
  33293. vertexData.positions = positions;
  33294. vertexData.normals = normals;
  33295. vertexData.uvs = uvs;
  33296. if (faceColors) {
  33297. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  33298. vertexData.colors = totalColors;
  33299. }
  33300. return vertexData;
  33301. };
  33302. /**
  33303. * Creates the VertexData of the Sphere.
  33304. */
  33305. VertexData.CreateSphere = function (options) {
  33306. var segments = options.segments || 32;
  33307. var diameterX = options.diameterX || options.diameter || 1;
  33308. var diameterY = options.diameterY || options.diameter || 1;
  33309. var diameterZ = options.diameterZ || options.diameter || 1;
  33310. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  33311. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  33312. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33313. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  33314. var totalZRotationSteps = 2 + segments;
  33315. var totalYRotationSteps = 2 * totalZRotationSteps;
  33316. var indices = [];
  33317. var positions = [];
  33318. var normals = [];
  33319. var uvs = [];
  33320. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  33321. var normalizedZ = zRotationStep / totalZRotationSteps;
  33322. var angleZ = normalizedZ * Math.PI * slice;
  33323. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  33324. var normalizedY = yRotationStep / totalYRotationSteps;
  33325. var angleY = normalizedY * Math.PI * 2 * arc;
  33326. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  33327. var rotationY = BABYLON.Matrix.RotationY(angleY);
  33328. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  33329. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  33330. var vertex = complete.multiply(radius);
  33331. var normal = complete.divide(radius).normalize();
  33332. positions.push(vertex.x, vertex.y, vertex.z);
  33333. normals.push(normal.x, normal.y, normal.z);
  33334. uvs.push(normalizedY, normalizedZ);
  33335. }
  33336. if (zRotationStep > 0) {
  33337. var verticesCount = positions.length / 3;
  33338. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  33339. indices.push((firstIndex));
  33340. indices.push((firstIndex + 1));
  33341. indices.push(firstIndex + totalYRotationSteps + 1);
  33342. indices.push((firstIndex + totalYRotationSteps + 1));
  33343. indices.push((firstIndex + 1));
  33344. indices.push((firstIndex + totalYRotationSteps + 2));
  33345. }
  33346. }
  33347. }
  33348. // Sides
  33349. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33350. // Result
  33351. var vertexData = new VertexData();
  33352. vertexData.indices = indices;
  33353. vertexData.positions = positions;
  33354. vertexData.normals = normals;
  33355. vertexData.uvs = uvs;
  33356. return vertexData;
  33357. };
  33358. /**
  33359. * Creates the VertexData of the Cylinder or Cone.
  33360. */
  33361. VertexData.CreateCylinder = function (options) {
  33362. var height = options.height || 2;
  33363. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  33364. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  33365. var tessellation = options.tessellation || 24;
  33366. var subdivisions = options.subdivisions || 1;
  33367. var hasRings = options.hasRings ? true : false;
  33368. var enclose = options.enclose ? true : false;
  33369. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  33370. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33371. var faceUV = options.faceUV || new Array(3);
  33372. var faceColors = options.faceColors;
  33373. // default face colors and UV if undefined
  33374. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  33375. var ringNb = (hasRings) ? subdivisions : 1;
  33376. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  33377. var f;
  33378. for (f = 0; f < surfaceNb; f++) {
  33379. if (faceColors && faceColors[f] === undefined) {
  33380. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  33381. }
  33382. }
  33383. for (f = 0; f < surfaceNb; f++) {
  33384. if (faceUV && faceUV[f] === undefined) {
  33385. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  33386. }
  33387. }
  33388. var indices = new Array();
  33389. var positions = new Array();
  33390. var normals = new Array();
  33391. var uvs = new Array();
  33392. var colors = new Array();
  33393. var angle_step = Math.PI * 2 * arc / tessellation;
  33394. var angle;
  33395. var h;
  33396. var radius;
  33397. var tan = (diameterBottom - diameterTop) / 2 / height;
  33398. var ringVertex = BABYLON.Vector3.Zero();
  33399. var ringNormal = BABYLON.Vector3.Zero();
  33400. var ringFirstVertex = BABYLON.Vector3.Zero();
  33401. var ringFirstNormal = BABYLON.Vector3.Zero();
  33402. var quadNormal = BABYLON.Vector3.Zero();
  33403. var Y = BABYLON.Axis.Y;
  33404. // positions, normals, uvs
  33405. var i;
  33406. var j;
  33407. var r;
  33408. var ringIdx = 1;
  33409. var s = 1; // surface index
  33410. var cs = 0;
  33411. var v = 0;
  33412. for (i = 0; i <= subdivisions; i++) {
  33413. h = i / subdivisions;
  33414. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  33415. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  33416. for (r = 0; r < ringIdx; r++) {
  33417. if (hasRings) {
  33418. s += r;
  33419. }
  33420. if (enclose) {
  33421. s += 2 * r;
  33422. }
  33423. for (j = 0; j <= tessellation; j++) {
  33424. angle = j * angle_step;
  33425. // position
  33426. ringVertex.x = Math.cos(-angle) * radius;
  33427. ringVertex.y = -height / 2 + h * height;
  33428. ringVertex.z = Math.sin(-angle) * radius;
  33429. // normal
  33430. if (diameterTop === 0 && i === subdivisions) {
  33431. // if no top cap, reuse former normals
  33432. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  33433. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  33434. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  33435. }
  33436. else {
  33437. ringNormal.x = ringVertex.x;
  33438. ringNormal.z = ringVertex.z;
  33439. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  33440. ringNormal.normalize();
  33441. }
  33442. // keep first ring vertex values for enclose
  33443. if (j === 0) {
  33444. ringFirstVertex.copyFrom(ringVertex);
  33445. ringFirstNormal.copyFrom(ringNormal);
  33446. }
  33447. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  33448. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  33449. if (hasRings) {
  33450. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  33451. }
  33452. else {
  33453. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  33454. }
  33455. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  33456. if (faceColors) {
  33457. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  33458. }
  33459. }
  33460. // if enclose, add four vertices and their dedicated normals
  33461. if (arc !== 1 && enclose) {
  33462. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  33463. positions.push(0, ringVertex.y, 0);
  33464. positions.push(0, ringVertex.y, 0);
  33465. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  33466. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  33467. quadNormal.normalize();
  33468. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  33469. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  33470. quadNormal.normalize();
  33471. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  33472. if (hasRings) {
  33473. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  33474. }
  33475. else {
  33476. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  33477. }
  33478. uvs.push(faceUV[s + 1].x, v);
  33479. uvs.push(faceUV[s + 1].z, v);
  33480. if (hasRings) {
  33481. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  33482. }
  33483. else {
  33484. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  33485. }
  33486. uvs.push(faceUV[s + 2].x, v);
  33487. uvs.push(faceUV[s + 2].z, v);
  33488. if (faceColors) {
  33489. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  33490. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  33491. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  33492. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  33493. }
  33494. }
  33495. if (cs !== s) {
  33496. cs = s;
  33497. }
  33498. }
  33499. }
  33500. // indices
  33501. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  33502. var s;
  33503. i = 0;
  33504. for (s = 0; s < subdivisions; s++) {
  33505. var i0 = 0;
  33506. var i1 = 0;
  33507. var i2 = 0;
  33508. var i3 = 0;
  33509. for (j = 0; j < tessellation; j++) {
  33510. i0 = i * (e + 1) + j;
  33511. i1 = (i + 1) * (e + 1) + j;
  33512. i2 = i * (e + 1) + (j + 1);
  33513. i3 = (i + 1) * (e + 1) + (j + 1);
  33514. indices.push(i0, i1, i2);
  33515. indices.push(i3, i2, i1);
  33516. }
  33517. if (arc !== 1 && enclose) {
  33518. indices.push(i0 + 2, i1 + 2, i2 + 2);
  33519. indices.push(i3 + 2, i2 + 2, i1 + 2);
  33520. indices.push(i0 + 4, i1 + 4, i2 + 4);
  33521. indices.push(i3 + 4, i2 + 4, i1 + 4);
  33522. }
  33523. i = (hasRings) ? (i + 2) : (i + 1);
  33524. }
  33525. // Caps
  33526. var createCylinderCap = function (isTop) {
  33527. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  33528. if (radius === 0) {
  33529. return;
  33530. }
  33531. // Cap positions, normals & uvs
  33532. var angle;
  33533. var circleVector;
  33534. var i;
  33535. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  33536. var c = null;
  33537. if (faceColors) {
  33538. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  33539. }
  33540. // cap center
  33541. var vbase = positions.length / 3;
  33542. var offset = isTop ? height / 2 : -height / 2;
  33543. var center = new BABYLON.Vector3(0, offset, 0);
  33544. positions.push(center.x, center.y, center.z);
  33545. normals.push(0, isTop ? 1 : -1, 0);
  33546. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  33547. if (c) {
  33548. colors.push(c.r, c.g, c.b, c.a);
  33549. }
  33550. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  33551. for (i = 0; i <= tessellation; i++) {
  33552. angle = Math.PI * 2 * i * arc / tessellation;
  33553. var cos = Math.cos(-angle);
  33554. var sin = Math.sin(-angle);
  33555. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  33556. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  33557. positions.push(circleVector.x, circleVector.y, circleVector.z);
  33558. normals.push(0, isTop ? 1 : -1, 0);
  33559. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  33560. if (c) {
  33561. colors.push(c.r, c.g, c.b, c.a);
  33562. }
  33563. }
  33564. // Cap indices
  33565. for (i = 0; i < tessellation; i++) {
  33566. if (!isTop) {
  33567. indices.push(vbase);
  33568. indices.push(vbase + (i + 1));
  33569. indices.push(vbase + (i + 2));
  33570. }
  33571. else {
  33572. indices.push(vbase);
  33573. indices.push(vbase + (i + 2));
  33574. indices.push(vbase + (i + 1));
  33575. }
  33576. }
  33577. };
  33578. // add caps to geometry
  33579. createCylinderCap(false);
  33580. createCylinderCap(true);
  33581. // Sides
  33582. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33583. var vertexData = new VertexData();
  33584. vertexData.indices = indices;
  33585. vertexData.positions = positions;
  33586. vertexData.normals = normals;
  33587. vertexData.uvs = uvs;
  33588. if (faceColors) {
  33589. vertexData.colors = colors;
  33590. }
  33591. return vertexData;
  33592. };
  33593. /**
  33594. * Creates the VertexData of the Torus.
  33595. */
  33596. VertexData.CreateTorus = function (options) {
  33597. var indices = [];
  33598. var positions = [];
  33599. var normals = [];
  33600. var uvs = [];
  33601. var diameter = options.diameter || 1;
  33602. var thickness = options.thickness || 0.5;
  33603. var tessellation = options.tessellation || 16;
  33604. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33605. var stride = tessellation + 1;
  33606. for (var i = 0; i <= tessellation; i++) {
  33607. var u = i / tessellation;
  33608. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  33609. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  33610. for (var j = 0; j <= tessellation; j++) {
  33611. var v = 1 - j / tessellation;
  33612. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  33613. var dx = Math.cos(innerAngle);
  33614. var dy = Math.sin(innerAngle);
  33615. // Create a vertex.
  33616. var normal = new BABYLON.Vector3(dx, dy, 0);
  33617. var position = normal.scale(thickness / 2);
  33618. var textureCoordinate = new BABYLON.Vector2(u, v);
  33619. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  33620. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  33621. positions.push(position.x, position.y, position.z);
  33622. normals.push(normal.x, normal.y, normal.z);
  33623. uvs.push(textureCoordinate.x, textureCoordinate.y);
  33624. // And create indices for two triangles.
  33625. var nextI = (i + 1) % stride;
  33626. var nextJ = (j + 1) % stride;
  33627. indices.push(i * stride + j);
  33628. indices.push(i * stride + nextJ);
  33629. indices.push(nextI * stride + j);
  33630. indices.push(i * stride + nextJ);
  33631. indices.push(nextI * stride + nextJ);
  33632. indices.push(nextI * stride + j);
  33633. }
  33634. }
  33635. // Sides
  33636. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33637. // Result
  33638. var vertexData = new VertexData();
  33639. vertexData.indices = indices;
  33640. vertexData.positions = positions;
  33641. vertexData.normals = normals;
  33642. vertexData.uvs = uvs;
  33643. return vertexData;
  33644. };
  33645. /**
  33646. * Creates the VertexData of the LineSystem.
  33647. */
  33648. VertexData.CreateLineSystem = function (options) {
  33649. var indices = [];
  33650. var positions = [];
  33651. var lines = options.lines;
  33652. var colors = options.colors;
  33653. var vertexColors = [];
  33654. var idx = 0;
  33655. for (var l = 0; l < lines.length; l++) {
  33656. var points = lines[l];
  33657. for (var index = 0; index < points.length; index++) {
  33658. positions.push(points[index].x, points[index].y, points[index].z);
  33659. if (colors) {
  33660. var color = colors[l];
  33661. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  33662. }
  33663. if (index > 0) {
  33664. indices.push(idx - 1);
  33665. indices.push(idx);
  33666. }
  33667. idx++;
  33668. }
  33669. }
  33670. var vertexData = new VertexData();
  33671. vertexData.indices = indices;
  33672. vertexData.positions = positions;
  33673. if (colors) {
  33674. vertexData.colors = vertexColors;
  33675. }
  33676. return vertexData;
  33677. };
  33678. /**
  33679. * Create the VertexData of the DashedLines.
  33680. */
  33681. VertexData.CreateDashedLines = function (options) {
  33682. var dashSize = options.dashSize || 3;
  33683. var gapSize = options.gapSize || 1;
  33684. var dashNb = options.dashNb || 200;
  33685. var points = options.points;
  33686. var positions = new Array();
  33687. var indices = new Array();
  33688. var curvect = BABYLON.Vector3.Zero();
  33689. var lg = 0;
  33690. var nb = 0;
  33691. var shft = 0;
  33692. var dashshft = 0;
  33693. var curshft = 0;
  33694. var idx = 0;
  33695. var i = 0;
  33696. for (i = 0; i < points.length - 1; i++) {
  33697. points[i + 1].subtractToRef(points[i], curvect);
  33698. lg += curvect.length();
  33699. }
  33700. shft = lg / dashNb;
  33701. dashshft = dashSize * shft / (dashSize + gapSize);
  33702. for (i = 0; i < points.length - 1; i++) {
  33703. points[i + 1].subtractToRef(points[i], curvect);
  33704. nb = Math.floor(curvect.length() / shft);
  33705. curvect.normalize();
  33706. for (var j = 0; j < nb; j++) {
  33707. curshft = shft * j;
  33708. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  33709. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  33710. indices.push(idx, idx + 1);
  33711. idx += 2;
  33712. }
  33713. }
  33714. // Result
  33715. var vertexData = new VertexData();
  33716. vertexData.positions = positions;
  33717. vertexData.indices = indices;
  33718. return vertexData;
  33719. };
  33720. /**
  33721. * Creates the VertexData of the Ground.
  33722. */
  33723. VertexData.CreateGround = function (options) {
  33724. var indices = [];
  33725. var positions = [];
  33726. var normals = [];
  33727. var uvs = [];
  33728. var row, col;
  33729. var width = options.width || 1;
  33730. var height = options.height || 1;
  33731. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  33732. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  33733. for (row = 0; row <= subdivisionsY; row++) {
  33734. for (col = 0; col <= subdivisionsX; col++) {
  33735. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  33736. var normal = new BABYLON.Vector3(0, 1.0, 0);
  33737. positions.push(position.x, position.y, position.z);
  33738. normals.push(normal.x, normal.y, normal.z);
  33739. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  33740. }
  33741. }
  33742. for (row = 0; row < subdivisionsY; row++) {
  33743. for (col = 0; col < subdivisionsX; col++) {
  33744. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  33745. indices.push(col + 1 + row * (subdivisionsX + 1));
  33746. indices.push(col + row * (subdivisionsX + 1));
  33747. indices.push(col + (row + 1) * (subdivisionsX + 1));
  33748. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  33749. indices.push(col + row * (subdivisionsX + 1));
  33750. }
  33751. }
  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 TiledGround.
  33762. */
  33763. VertexData.CreateTiledGround = function (options) {
  33764. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  33765. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  33766. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  33767. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  33768. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  33769. var precision = options.precision || { w: 1, h: 1 };
  33770. var indices = new Array();
  33771. var positions = new Array();
  33772. var normals = new Array();
  33773. var uvs = new Array();
  33774. var row, col, tileRow, tileCol;
  33775. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  33776. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  33777. precision.w = (precision.w < 1) ? 1 : precision.w;
  33778. precision.h = (precision.h < 1) ? 1 : precision.h;
  33779. var tileSize = {
  33780. 'w': (xmax - xmin) / subdivisions.w,
  33781. 'h': (zmax - zmin) / subdivisions.h
  33782. };
  33783. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  33784. // Indices
  33785. var base = positions.length / 3;
  33786. var rowLength = precision.w + 1;
  33787. for (row = 0; row < precision.h; row++) {
  33788. for (col = 0; col < precision.w; col++) {
  33789. var square = [
  33790. base + col + row * rowLength,
  33791. base + (col + 1) + row * rowLength,
  33792. base + (col + 1) + (row + 1) * rowLength,
  33793. base + col + (row + 1) * rowLength
  33794. ];
  33795. indices.push(square[1]);
  33796. indices.push(square[2]);
  33797. indices.push(square[3]);
  33798. indices.push(square[0]);
  33799. indices.push(square[1]);
  33800. indices.push(square[3]);
  33801. }
  33802. }
  33803. // Position, normals and uvs
  33804. var position = BABYLON.Vector3.Zero();
  33805. var normal = new BABYLON.Vector3(0, 1.0, 0);
  33806. for (row = 0; row <= precision.h; row++) {
  33807. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  33808. for (col = 0; col <= precision.w; col++) {
  33809. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  33810. position.y = 0;
  33811. positions.push(position.x, position.y, position.z);
  33812. normals.push(normal.x, normal.y, normal.z);
  33813. uvs.push(col / precision.w, row / precision.h);
  33814. }
  33815. }
  33816. }
  33817. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  33818. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  33819. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  33820. }
  33821. }
  33822. // Result
  33823. var vertexData = new VertexData();
  33824. vertexData.indices = indices;
  33825. vertexData.positions = positions;
  33826. vertexData.normals = normals;
  33827. vertexData.uvs = uvs;
  33828. return vertexData;
  33829. };
  33830. /**
  33831. * Creates the VertexData of the Ground designed from a heightmap.
  33832. */
  33833. VertexData.CreateGroundFromHeightMap = function (options) {
  33834. var indices = [];
  33835. var positions = [];
  33836. var normals = [];
  33837. var uvs = [];
  33838. var row, col;
  33839. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  33840. // Vertices
  33841. for (row = 0; row <= options.subdivisions; row++) {
  33842. for (col = 0; col <= options.subdivisions; col++) {
  33843. 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));
  33844. // Compute height
  33845. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  33846. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  33847. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  33848. var r = options.buffer[pos] / 255.0;
  33849. var g = options.buffer[pos + 1] / 255.0;
  33850. var b = options.buffer[pos + 2] / 255.0;
  33851. var gradient = r * filter.r + g * filter.g + b * filter.b;
  33852. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  33853. // Add vertex
  33854. positions.push(position.x, position.y, position.z);
  33855. normals.push(0, 0, 0);
  33856. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  33857. }
  33858. }
  33859. // Indices
  33860. for (row = 0; row < options.subdivisions; row++) {
  33861. for (col = 0; col < options.subdivisions; col++) {
  33862. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  33863. indices.push(col + 1 + row * (options.subdivisions + 1));
  33864. indices.push(col + row * (options.subdivisions + 1));
  33865. indices.push(col + (row + 1) * (options.subdivisions + 1));
  33866. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  33867. indices.push(col + row * (options.subdivisions + 1));
  33868. }
  33869. }
  33870. // Normals
  33871. VertexData.ComputeNormals(positions, indices, normals);
  33872. // Result
  33873. var vertexData = new VertexData();
  33874. vertexData.indices = indices;
  33875. vertexData.positions = positions;
  33876. vertexData.normals = normals;
  33877. vertexData.uvs = uvs;
  33878. return vertexData;
  33879. };
  33880. /**
  33881. * Creates the VertexData of the Plane.
  33882. */
  33883. VertexData.CreatePlane = function (options) {
  33884. var indices = [];
  33885. var positions = [];
  33886. var normals = [];
  33887. var uvs = [];
  33888. var width = options.width || options.size || 1;
  33889. var height = options.height || options.size || 1;
  33890. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33891. // Vertices
  33892. var halfWidth = width / 2.0;
  33893. var halfHeight = height / 2.0;
  33894. positions.push(-halfWidth, -halfHeight, 0);
  33895. normals.push(0, 0, -1.0);
  33896. uvs.push(0.0, 0.0);
  33897. positions.push(halfWidth, -halfHeight, 0);
  33898. normals.push(0, 0, -1.0);
  33899. uvs.push(1.0, 0.0);
  33900. positions.push(halfWidth, halfHeight, 0);
  33901. normals.push(0, 0, -1.0);
  33902. uvs.push(1.0, 1.0);
  33903. positions.push(-halfWidth, halfHeight, 0);
  33904. normals.push(0, 0, -1.0);
  33905. uvs.push(0.0, 1.0);
  33906. // Indices
  33907. indices.push(0);
  33908. indices.push(1);
  33909. indices.push(2);
  33910. indices.push(0);
  33911. indices.push(2);
  33912. indices.push(3);
  33913. // Sides
  33914. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33915. // Result
  33916. var vertexData = new VertexData();
  33917. vertexData.indices = indices;
  33918. vertexData.positions = positions;
  33919. vertexData.normals = normals;
  33920. vertexData.uvs = uvs;
  33921. return vertexData;
  33922. };
  33923. /**
  33924. * Creates the VertexData of the Disc or regular Polygon.
  33925. */
  33926. VertexData.CreateDisc = function (options) {
  33927. var positions = new Array();
  33928. var indices = new Array();
  33929. var normals = new Array();
  33930. var uvs = new Array();
  33931. var radius = options.radius || 0.5;
  33932. var tessellation = options.tessellation || 64;
  33933. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  33934. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33935. // positions and uvs
  33936. positions.push(0, 0, 0); // disc center first
  33937. uvs.push(0.5, 0.5);
  33938. var theta = Math.PI * 2 * arc;
  33939. var step = theta / tessellation;
  33940. for (var a = 0; a < theta; a += step) {
  33941. var x = Math.cos(a);
  33942. var y = Math.sin(a);
  33943. var u = (x + 1) / 2;
  33944. var v = (1 - y) / 2;
  33945. positions.push(radius * x, radius * y, 0);
  33946. uvs.push(u, v);
  33947. }
  33948. if (arc === 1) {
  33949. positions.push(positions[3], positions[4], positions[5]); // close the circle
  33950. uvs.push(uvs[2], uvs[3]);
  33951. }
  33952. //indices
  33953. var vertexNb = positions.length / 3;
  33954. for (var i = 1; i < vertexNb - 1; i++) {
  33955. indices.push(i + 1, 0, i);
  33956. }
  33957. // result
  33958. VertexData.ComputeNormals(positions, indices, normals);
  33959. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33960. var vertexData = new VertexData();
  33961. vertexData.indices = indices;
  33962. vertexData.positions = positions;
  33963. vertexData.normals = normals;
  33964. vertexData.uvs = uvs;
  33965. return vertexData;
  33966. };
  33967. /**
  33968. * Re-creates the VertexData of the Polygon for sideOrientation.
  33969. */
  33970. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  33971. var faceUV = fUV || new Array(3);
  33972. var faceColors = fColors;
  33973. var colors = [];
  33974. // default face colors and UV if undefined
  33975. for (var f = 0; f < 3; f++) {
  33976. if (faceUV[f] === undefined) {
  33977. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  33978. }
  33979. if (faceColors && faceColors[f] === undefined) {
  33980. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  33981. }
  33982. }
  33983. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33984. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33985. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  33986. var indices = polygon.getIndices();
  33987. // set face colours and textures
  33988. var idx = 0;
  33989. var face = 0;
  33990. for (var index = 0; index < normals.length; index += 3) {
  33991. //Edge Face no. 1
  33992. if (Math.abs(normals[index + 1]) < 0.001) {
  33993. face = 1;
  33994. }
  33995. //Top Face no. 0
  33996. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  33997. face = 0;
  33998. }
  33999. //Bottom Face no. 2
  34000. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  34001. face = 2;
  34002. }
  34003. idx = index / 3;
  34004. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  34005. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  34006. if (faceColors) {
  34007. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  34008. }
  34009. }
  34010. // sides
  34011. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  34012. // Result
  34013. var vertexData = new VertexData();
  34014. vertexData.indices = indices;
  34015. vertexData.positions = positions;
  34016. vertexData.normals = normals;
  34017. vertexData.uvs = uvs;
  34018. if (faceColors) {
  34019. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  34020. vertexData.colors = totalColors;
  34021. }
  34022. return vertexData;
  34023. };
  34024. /**
  34025. * Creates the VertexData of the IcoSphere.
  34026. */
  34027. VertexData.CreateIcoSphere = function (options) {
  34028. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34029. var radius = options.radius || 1;
  34030. var flat = (options.flat === undefined) ? true : options.flat;
  34031. var subdivisions = options.subdivisions || 4;
  34032. var radiusX = options.radiusX || radius;
  34033. var radiusY = options.radiusY || radius;
  34034. var radiusZ = options.radiusZ || radius;
  34035. var t = (1 + Math.sqrt(5)) / 2;
  34036. // 12 vertex x,y,z
  34037. var ico_vertices = [
  34038. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  34039. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  34040. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  34041. ];
  34042. // index of 3 vertex makes a face of icopshere
  34043. var ico_indices = [
  34044. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  34045. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  34046. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  34047. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  34048. ];
  34049. // vertex for uv have aliased position, not for UV
  34050. var vertices_unalias_id = [
  34051. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  34052. // vertex alias
  34053. 0,
  34054. 2,
  34055. 3,
  34056. 3,
  34057. 3,
  34058. 4,
  34059. 7,
  34060. 8,
  34061. 9,
  34062. 9,
  34063. 10,
  34064. 11 // 23: B + 12
  34065. ];
  34066. // uv as integer step (not pixels !)
  34067. var ico_vertexuv = [
  34068. 5, 1, 3, 1, 6, 4, 0, 0,
  34069. 5, 3, 4, 2, 2, 2, 4, 0,
  34070. 2, 0, 1, 1, 6, 0, 6, 2,
  34071. // vertex alias (for same vertex on different faces)
  34072. 0, 4,
  34073. 3, 3,
  34074. 4, 4,
  34075. 3, 1,
  34076. 4, 2,
  34077. 4, 4,
  34078. 0, 2,
  34079. 1, 1,
  34080. 2, 2,
  34081. 3, 3,
  34082. 1, 3,
  34083. 2, 4 // 23: B + 12
  34084. ];
  34085. // Vertices[0, 1, ...9, A, B] : position on UV plane
  34086. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  34087. // First island of uv mapping
  34088. // v = 4h 3+ 2
  34089. // v = 3h 9+ 4
  34090. // v = 2h 9+ 5 B
  34091. // v = 1h 9 1 0
  34092. // v = 0h 3 8 7 A
  34093. // u = 0 1 2 3 4 5 6 *a
  34094. // Second island of uv mapping
  34095. // v = 4h 0+ B+ 4+
  34096. // v = 3h A+ 2+
  34097. // v = 2h 7+ 6 3+
  34098. // v = 1h 8+ 3+
  34099. // v = 0h
  34100. // u = 0 1 2 3 4 5 6 *a
  34101. // Face layout on texture UV mapping
  34102. // ============
  34103. // \ 4 /\ 16 / ======
  34104. // \ / \ / /\ 11 /
  34105. // \/ 7 \/ / \ /
  34106. // ======= / 10 \/
  34107. // /\ 17 /\ =======
  34108. // / \ / \ \ 15 /\
  34109. // / 8 \/ 12 \ \ / \
  34110. // ============ \/ 6 \
  34111. // \ 18 /\ ============
  34112. // \ / \ \ 5 /\ 0 /
  34113. // \/ 13 \ \ / \ /
  34114. // ======= \/ 1 \/
  34115. // =============
  34116. // /\ 19 /\ 2 /\
  34117. // / \ / \ / \
  34118. // / 14 \/ 9 \/ 3 \
  34119. // ===================
  34120. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  34121. var ustep = 138 / 1024;
  34122. var vstep = 239 / 1024;
  34123. var uoffset = 60 / 1024;
  34124. var voffset = 26 / 1024;
  34125. // Second island should have margin, not to touch the first island
  34126. // avoid any borderline artefact in pixel rounding
  34127. var island_u_offset = -40 / 1024;
  34128. var island_v_offset = +20 / 1024;
  34129. // face is either island 0 or 1 :
  34130. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  34131. var island = [
  34132. 0, 0, 0, 0, 1,
  34133. 0, 0, 1, 1, 0,
  34134. 0, 0, 1, 1, 0,
  34135. 0, 1, 1, 1, 0 // 15 - 19
  34136. ];
  34137. var indices = new Array();
  34138. var positions = new Array();
  34139. var normals = new Array();
  34140. var uvs = new Array();
  34141. var current_indice = 0;
  34142. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  34143. var face_vertex_pos = new Array(3);
  34144. var face_vertex_uv = new Array(3);
  34145. var v012;
  34146. for (v012 = 0; v012 < 3; v012++) {
  34147. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  34148. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  34149. }
  34150. // create all with normals
  34151. for (var face = 0; face < 20; face++) {
  34152. // 3 vertex per face
  34153. for (v012 = 0; v012 < 3; v012++) {
  34154. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  34155. var v_id = ico_indices[3 * face + v012];
  34156. // vertex have 3D position (x,y,z)
  34157. 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]);
  34158. // Normalize to get normal, then scale to radius
  34159. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  34160. // uv Coordinates from vertex ID
  34161. 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);
  34162. }
  34163. // Subdivide the face (interpolate pos, norm, uv)
  34164. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  34165. // - norm is linear interpolation of vertex corner normal
  34166. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  34167. // - uv is linear interpolation
  34168. //
  34169. // Topology is as below for sub-divide by 2
  34170. // vertex shown as v0,v1,v2
  34171. // interp index is i1 to progress in range [v0,v1[
  34172. // interp index is i2 to progress in range [v0,v2[
  34173. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  34174. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  34175. //
  34176. //
  34177. // i2 v2
  34178. // ^ ^
  34179. // / / \
  34180. // / / \
  34181. // / / \
  34182. // / / (0,1) \
  34183. // / #---------\
  34184. // / / \ (0,0)'/ \
  34185. // / / \ / \
  34186. // / / \ / \
  34187. // / / (0,0) \ / (1,0) \
  34188. // / #---------#---------\
  34189. // v0 v1
  34190. //
  34191. // --------------------> i1
  34192. //
  34193. // interp of (i1,i2):
  34194. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  34195. // along i1 : lerp(x0,x1, i1/(S-i2))
  34196. //
  34197. // centroid of triangle is needed to get help normal computation
  34198. // (c1,c2) are used for centroid location
  34199. var interp_vertex = function (i1, i2, c1, c2) {
  34200. // vertex is interpolated from
  34201. // - face_vertex_pos[0..2]
  34202. // - face_vertex_uv[0..2]
  34203. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  34204. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  34205. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  34206. pos_interp.normalize();
  34207. var vertex_normal;
  34208. if (flat) {
  34209. // in flat mode, recalculate normal as face centroid normal
  34210. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  34211. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  34212. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  34213. }
  34214. else {
  34215. // in smooth mode, recalculate normal from each single vertex position
  34216. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  34217. }
  34218. // Vertex normal need correction due to X,Y,Z radius scaling
  34219. vertex_normal.x /= radiusX;
  34220. vertex_normal.y /= radiusY;
  34221. vertex_normal.z /= radiusZ;
  34222. vertex_normal.normalize();
  34223. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  34224. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  34225. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  34226. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  34227. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  34228. uvs.push(uv_interp.x, uv_interp.y);
  34229. // push each vertex has member of a face
  34230. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  34231. indices.push(current_indice);
  34232. current_indice++;
  34233. };
  34234. for (var i2 = 0; i2 < subdivisions; i2++) {
  34235. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  34236. // face : (i1,i2) for /\ :
  34237. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  34238. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  34239. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  34240. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  34241. if (i1 + i2 + 1 < subdivisions) {
  34242. // face : (i1,i2)' for \/ :
  34243. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  34244. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  34245. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  34246. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  34247. }
  34248. }
  34249. }
  34250. }
  34251. // Sides
  34252. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  34253. // Result
  34254. var vertexData = new VertexData();
  34255. vertexData.indices = indices;
  34256. vertexData.positions = positions;
  34257. vertexData.normals = normals;
  34258. vertexData.uvs = uvs;
  34259. return vertexData;
  34260. };
  34261. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  34262. /**
  34263. * Creates the VertexData of the Polyhedron.
  34264. */
  34265. VertexData.CreatePolyhedron = function (options) {
  34266. // provided polyhedron types :
  34267. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  34268. // 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)
  34269. var polyhedra = [];
  34270. 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]] };
  34271. 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]] };
  34272. polyhedra[2] = {
  34273. 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]],
  34274. 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]]
  34275. };
  34276. polyhedra[3] = {
  34277. 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]],
  34278. 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]]
  34279. };
  34280. polyhedra[4] = {
  34281. 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]],
  34282. 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]]
  34283. };
  34284. 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]] };
  34285. 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]] };
  34286. 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]] };
  34287. 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]] };
  34288. 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]] };
  34289. 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]] };
  34290. 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]] };
  34291. 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]] };
  34292. 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]] };
  34293. polyhedra[14] = {
  34294. 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]],
  34295. 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]]
  34296. };
  34297. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  34298. var size = options.size;
  34299. var sizeX = options.sizeX || size || 1;
  34300. var sizeY = options.sizeY || size || 1;
  34301. var sizeZ = options.sizeZ || size || 1;
  34302. var data = options.custom || polyhedra[type];
  34303. var nbfaces = data.face.length;
  34304. var faceUV = options.faceUV || new Array(nbfaces);
  34305. var faceColors = options.faceColors;
  34306. var flat = (options.flat === undefined) ? true : options.flat;
  34307. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34308. var positions = new Array();
  34309. var indices = new Array();
  34310. var normals = new Array();
  34311. var uvs = new Array();
  34312. var colors = new Array();
  34313. var index = 0;
  34314. var faceIdx = 0; // face cursor in the array "indexes"
  34315. var indexes = new Array();
  34316. var i = 0;
  34317. var f = 0;
  34318. var u, v, ang, x, y, tmp;
  34319. // default face colors and UV if undefined
  34320. if (flat) {
  34321. for (f = 0; f < nbfaces; f++) {
  34322. if (faceColors && faceColors[f] === undefined) {
  34323. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  34324. }
  34325. if (faceUV && faceUV[f] === undefined) {
  34326. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  34327. }
  34328. }
  34329. }
  34330. if (!flat) {
  34331. for (i = 0; i < data.vertex.length; i++) {
  34332. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  34333. uvs.push(0, 0);
  34334. }
  34335. for (f = 0; f < nbfaces; f++) {
  34336. for (i = 0; i < data.face[f].length - 2; i++) {
  34337. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  34338. }
  34339. }
  34340. }
  34341. else {
  34342. for (f = 0; f < nbfaces; f++) {
  34343. var fl = data.face[f].length; // number of vertices of the current face
  34344. ang = 2 * Math.PI / fl;
  34345. x = 0.5 * Math.tan(ang / 2);
  34346. y = 0.5;
  34347. // positions, uvs, colors
  34348. for (i = 0; i < fl; i++) {
  34349. // positions
  34350. 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);
  34351. indexes.push(index);
  34352. index++;
  34353. // uvs
  34354. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  34355. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  34356. uvs.push(u, v);
  34357. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  34358. y = x * Math.sin(ang) + y * Math.cos(ang);
  34359. x = tmp;
  34360. // colors
  34361. if (faceColors) {
  34362. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  34363. }
  34364. }
  34365. // indices from indexes
  34366. for (i = 0; i < fl - 2; i++) {
  34367. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  34368. }
  34369. faceIdx += fl;
  34370. }
  34371. }
  34372. VertexData.ComputeNormals(positions, indices, normals);
  34373. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  34374. var vertexData = new VertexData();
  34375. vertexData.positions = positions;
  34376. vertexData.indices = indices;
  34377. vertexData.normals = normals;
  34378. vertexData.uvs = uvs;
  34379. if (faceColors && flat) {
  34380. vertexData.colors = colors;
  34381. }
  34382. return vertexData;
  34383. };
  34384. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  34385. /**
  34386. * Creates the VertexData of the Torus Knot.
  34387. */
  34388. VertexData.CreateTorusKnot = function (options) {
  34389. var indices = new Array();
  34390. var positions = new Array();
  34391. var normals = new Array();
  34392. var uvs = new Array();
  34393. var radius = options.radius || 2;
  34394. var tube = options.tube || 0.5;
  34395. var radialSegments = options.radialSegments || 32;
  34396. var tubularSegments = options.tubularSegments || 32;
  34397. var p = options.p || 2;
  34398. var q = options.q || 3;
  34399. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34400. // Helper
  34401. var getPos = function (angle) {
  34402. var cu = Math.cos(angle);
  34403. var su = Math.sin(angle);
  34404. var quOverP = q / p * angle;
  34405. var cs = Math.cos(quOverP);
  34406. var tx = radius * (2 + cs) * 0.5 * cu;
  34407. var ty = radius * (2 + cs) * su * 0.5;
  34408. var tz = radius * Math.sin(quOverP) * 0.5;
  34409. return new BABYLON.Vector3(tx, ty, tz);
  34410. };
  34411. // Vertices
  34412. var i;
  34413. var j;
  34414. for (i = 0; i <= radialSegments; i++) {
  34415. var modI = i % radialSegments;
  34416. var u = modI / radialSegments * 2 * p * Math.PI;
  34417. var p1 = getPos(u);
  34418. var p2 = getPos(u + 0.01);
  34419. var tang = p2.subtract(p1);
  34420. var n = p2.add(p1);
  34421. var bitan = BABYLON.Vector3.Cross(tang, n);
  34422. n = BABYLON.Vector3.Cross(bitan, tang);
  34423. bitan.normalize();
  34424. n.normalize();
  34425. for (j = 0; j < tubularSegments; j++) {
  34426. var modJ = j % tubularSegments;
  34427. var v = modJ / tubularSegments * 2 * Math.PI;
  34428. var cx = -tube * Math.cos(v);
  34429. var cy = tube * Math.sin(v);
  34430. positions.push(p1.x + cx * n.x + cy * bitan.x);
  34431. positions.push(p1.y + cx * n.y + cy * bitan.y);
  34432. positions.push(p1.z + cx * n.z + cy * bitan.z);
  34433. uvs.push(i / radialSegments);
  34434. uvs.push(j / tubularSegments);
  34435. }
  34436. }
  34437. for (i = 0; i < radialSegments; i++) {
  34438. for (j = 0; j < tubularSegments; j++) {
  34439. var jNext = (j + 1) % tubularSegments;
  34440. var a = i * tubularSegments + j;
  34441. var b = (i + 1) * tubularSegments + j;
  34442. var c = (i + 1) * tubularSegments + jNext;
  34443. var d = i * tubularSegments + jNext;
  34444. indices.push(d);
  34445. indices.push(b);
  34446. indices.push(a);
  34447. indices.push(d);
  34448. indices.push(c);
  34449. indices.push(b);
  34450. }
  34451. }
  34452. // Normals
  34453. VertexData.ComputeNormals(positions, indices, normals);
  34454. // Sides
  34455. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  34456. // Result
  34457. var vertexData = new VertexData();
  34458. vertexData.indices = indices;
  34459. vertexData.positions = positions;
  34460. vertexData.normals = normals;
  34461. vertexData.uvs = uvs;
  34462. return vertexData;
  34463. };
  34464. // Tools
  34465. /**
  34466. * @param {any} - positions (number[] or Float32Array)
  34467. * @param {any} - indices (number[] or Uint16Array)
  34468. * @param {any} - normals (number[] or Float32Array)
  34469. * options (optional) :
  34470. * facetPositions : optional array of facet positions (vector3)
  34471. * facetNormals : optional array of facet normals (vector3)
  34472. * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  34473. * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  34474. * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  34475. * bbSize : optional bounding box size data, required for facetPartitioning computation
  34476. * bInfo : optional bounding info, required for facetPartitioning computation
  34477. * useRightHandedSystem: optional boolean to for right handed system computation
  34478. * depthSort : optional boolean to enable the facet depth sort computation
  34479. * distanceTo : optional Vector3 to compute the facet depth from this location
  34480. * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  34481. */
  34482. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  34483. // temporary scalar variables
  34484. var index = 0; // facet index
  34485. var p1p2x = 0.0; // p1p2 vector x coordinate
  34486. var p1p2y = 0.0; // p1p2 vector y coordinate
  34487. var p1p2z = 0.0; // p1p2 vector z coordinate
  34488. var p3p2x = 0.0; // p3p2 vector x coordinate
  34489. var p3p2y = 0.0; // p3p2 vector y coordinate
  34490. var p3p2z = 0.0; // p3p2 vector z coordinate
  34491. var faceNormalx = 0.0; // facet normal x coordinate
  34492. var faceNormaly = 0.0; // facet normal y coordinate
  34493. var faceNormalz = 0.0; // facet normal z coordinate
  34494. var length = 0.0; // facet normal length before normalization
  34495. var v1x = 0; // vector1 x index in the positions array
  34496. var v1y = 0; // vector1 y index in the positions array
  34497. var v1z = 0; // vector1 z index in the positions array
  34498. var v2x = 0; // vector2 x index in the positions array
  34499. var v2y = 0; // vector2 y index in the positions array
  34500. var v2z = 0; // vector2 z index in the positions array
  34501. var v3x = 0; // vector3 x index in the positions array
  34502. var v3y = 0; // vector3 y index in the positions array
  34503. var v3z = 0; // vector3 z index in the positions array
  34504. var computeFacetNormals = false;
  34505. var computeFacetPositions = false;
  34506. var computeFacetPartitioning = false;
  34507. var computeDepthSort = false;
  34508. var faceNormalSign = 1;
  34509. var ratio = 0;
  34510. var distanceTo = null;
  34511. if (options) {
  34512. computeFacetNormals = (options.facetNormals) ? true : false;
  34513. computeFacetPositions = (options.facetPositions) ? true : false;
  34514. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  34515. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  34516. ratio = options.ratio || 0;
  34517. computeDepthSort = (options.depthSort) ? true : false;
  34518. distanceTo = (options.distanceTo);
  34519. if (computeDepthSort) {
  34520. if (distanceTo === undefined) {
  34521. distanceTo = BABYLON.Vector3.Zero();
  34522. }
  34523. var depthSortedFacets = options.depthSortedFacets;
  34524. }
  34525. }
  34526. // facetPartitioning reinit if needed
  34527. var xSubRatio = 0;
  34528. var ySubRatio = 0;
  34529. var zSubRatio = 0;
  34530. var subSq = 0;
  34531. if (computeFacetPartitioning && options && options.bbSize) {
  34532. var ox = 0; // X partitioning index for facet position
  34533. var oy = 0; // Y partinioning index for facet position
  34534. var oz = 0; // Z partinioning index for facet position
  34535. var b1x = 0; // X partitioning index for facet v1 vertex
  34536. var b1y = 0; // Y partitioning index for facet v1 vertex
  34537. var b1z = 0; // z partitioning index for facet v1 vertex
  34538. var b2x = 0; // X partitioning index for facet v2 vertex
  34539. var b2y = 0; // Y partitioning index for facet v2 vertex
  34540. var b2z = 0; // Z partitioning index for facet v2 vertex
  34541. var b3x = 0; // X partitioning index for facet v3 vertex
  34542. var b3y = 0; // Y partitioning index for facet v3 vertex
  34543. var b3z = 0; // Z partitioning index for facet v3 vertex
  34544. var block_idx_o = 0; // facet barycenter block index
  34545. var block_idx_v1 = 0; // v1 vertex block index
  34546. var block_idx_v2 = 0; // v2 vertex block index
  34547. var block_idx_v3 = 0; // v3 vertex block index
  34548. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  34549. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  34550. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  34551. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  34552. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  34553. subSq = options.subDiv.max * options.subDiv.max;
  34554. options.facetPartitioning.length = 0;
  34555. }
  34556. // reset the normals
  34557. for (index = 0; index < positions.length; index++) {
  34558. normals[index] = 0.0;
  34559. }
  34560. // Loop : 1 indice triplet = 1 facet
  34561. var nbFaces = (indices.length / 3) | 0;
  34562. for (index = 0; index < nbFaces; index++) {
  34563. // get the indexes of the coordinates of each vertex of the facet
  34564. v1x = indices[index * 3] * 3;
  34565. v1y = v1x + 1;
  34566. v1z = v1x + 2;
  34567. v2x = indices[index * 3 + 1] * 3;
  34568. v2y = v2x + 1;
  34569. v2z = v2x + 2;
  34570. v3x = indices[index * 3 + 2] * 3;
  34571. v3y = v3x + 1;
  34572. v3z = v3x + 2;
  34573. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  34574. p1p2y = positions[v1y] - positions[v2y];
  34575. p1p2z = positions[v1z] - positions[v2z];
  34576. p3p2x = positions[v3x] - positions[v2x];
  34577. p3p2y = positions[v3y] - positions[v2y];
  34578. p3p2z = positions[v3z] - positions[v2z];
  34579. // compute the face normal with the cross product
  34580. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  34581. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  34582. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  34583. // normalize this normal and store it in the array facetData
  34584. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  34585. length = (length === 0) ? 1.0 : length;
  34586. faceNormalx /= length;
  34587. faceNormaly /= length;
  34588. faceNormalz /= length;
  34589. if (computeFacetNormals && options) {
  34590. options.facetNormals[index].x = faceNormalx;
  34591. options.facetNormals[index].y = faceNormaly;
  34592. options.facetNormals[index].z = faceNormalz;
  34593. }
  34594. if (computeFacetPositions && options) {
  34595. // compute and the facet barycenter coordinates in the array facetPositions
  34596. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  34597. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  34598. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  34599. }
  34600. if (computeFacetPartitioning && options) {
  34601. // store the facet indexes in arrays in the main facetPartitioning array :
  34602. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  34603. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  34604. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  34605. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  34606. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  34607. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  34608. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  34609. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  34610. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  34611. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  34612. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  34613. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  34614. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  34615. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  34616. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  34617. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  34618. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  34619. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  34620. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  34621. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  34622. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  34623. // push each facet index in each block containing the vertex
  34624. options.facetPartitioning[block_idx_v1].push(index);
  34625. if (block_idx_v2 != block_idx_v1) {
  34626. options.facetPartitioning[block_idx_v2].push(index);
  34627. }
  34628. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  34629. options.facetPartitioning[block_idx_v3].push(index);
  34630. }
  34631. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  34632. options.facetPartitioning[block_idx_o].push(index);
  34633. }
  34634. }
  34635. if (computeDepthSort && options && options.facetPositions) {
  34636. var dsf = depthSortedFacets[index];
  34637. dsf.ind = index * 3;
  34638. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  34639. }
  34640. // compute the normals anyway
  34641. normals[v1x] += faceNormalx; // accumulate all the normals per face
  34642. normals[v1y] += faceNormaly;
  34643. normals[v1z] += faceNormalz;
  34644. normals[v2x] += faceNormalx;
  34645. normals[v2y] += faceNormaly;
  34646. normals[v2z] += faceNormalz;
  34647. normals[v3x] += faceNormalx;
  34648. normals[v3y] += faceNormaly;
  34649. normals[v3z] += faceNormalz;
  34650. }
  34651. // last normalization of each normal
  34652. for (index = 0; index < normals.length / 3; index++) {
  34653. faceNormalx = normals[index * 3];
  34654. faceNormaly = normals[index * 3 + 1];
  34655. faceNormalz = normals[index * 3 + 2];
  34656. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  34657. length = (length === 0) ? 1.0 : length;
  34658. faceNormalx /= length;
  34659. faceNormaly /= length;
  34660. faceNormalz /= length;
  34661. normals[index * 3] = faceNormalx;
  34662. normals[index * 3 + 1] = faceNormaly;
  34663. normals[index * 3 + 2] = faceNormalz;
  34664. }
  34665. };
  34666. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  34667. var li = indices.length;
  34668. var ln = normals.length;
  34669. var i;
  34670. var n;
  34671. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34672. switch (sideOrientation) {
  34673. case BABYLON.Mesh.FRONTSIDE:
  34674. // nothing changed
  34675. break;
  34676. case BABYLON.Mesh.BACKSIDE:
  34677. var tmp;
  34678. // indices
  34679. for (i = 0; i < li; i += 3) {
  34680. tmp = indices[i];
  34681. indices[i] = indices[i + 2];
  34682. indices[i + 2] = tmp;
  34683. }
  34684. // normals
  34685. for (n = 0; n < ln; n++) {
  34686. normals[n] = -normals[n];
  34687. }
  34688. break;
  34689. case BABYLON.Mesh.DOUBLESIDE:
  34690. // positions
  34691. var lp = positions.length;
  34692. var l = lp / 3;
  34693. for (var p = 0; p < lp; p++) {
  34694. positions[lp + p] = positions[p];
  34695. }
  34696. // indices
  34697. for (i = 0; i < li; i += 3) {
  34698. indices[i + li] = indices[i + 2] + l;
  34699. indices[i + 1 + li] = indices[i + 1] + l;
  34700. indices[i + 2 + li] = indices[i] + l;
  34701. }
  34702. // normals
  34703. for (n = 0; n < ln; n++) {
  34704. normals[ln + n] = -normals[n];
  34705. }
  34706. // uvs
  34707. var lu = uvs.length;
  34708. var u = 0;
  34709. for (u = 0; u < lu; u++) {
  34710. uvs[u + lu] = uvs[u];
  34711. }
  34712. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  34713. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  34714. u = 0;
  34715. for (i = 0; i < lu / 2; i++) {
  34716. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  34717. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  34718. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  34719. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  34720. u += 2;
  34721. }
  34722. break;
  34723. }
  34724. };
  34725. /**
  34726. * Creates a new VertexData from the imported parameters.
  34727. */
  34728. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  34729. var vertexData = new VertexData();
  34730. // positions
  34731. var positions = parsedVertexData.positions;
  34732. if (positions) {
  34733. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  34734. }
  34735. // normals
  34736. var normals = parsedVertexData.normals;
  34737. if (normals) {
  34738. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  34739. }
  34740. // tangents
  34741. var tangents = parsedVertexData.tangents;
  34742. if (tangents) {
  34743. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  34744. }
  34745. // uvs
  34746. var uvs = parsedVertexData.uvs;
  34747. if (uvs) {
  34748. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  34749. }
  34750. // uv2s
  34751. var uv2s = parsedVertexData.uv2s;
  34752. if (uv2s) {
  34753. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  34754. }
  34755. // uv3s
  34756. var uv3s = parsedVertexData.uv3s;
  34757. if (uv3s) {
  34758. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  34759. }
  34760. // uv4s
  34761. var uv4s = parsedVertexData.uv4s;
  34762. if (uv4s) {
  34763. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  34764. }
  34765. // uv5s
  34766. var uv5s = parsedVertexData.uv5s;
  34767. if (uv5s) {
  34768. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  34769. }
  34770. // uv6s
  34771. var uv6s = parsedVertexData.uv6s;
  34772. if (uv6s) {
  34773. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  34774. }
  34775. // colors
  34776. var colors = parsedVertexData.colors;
  34777. if (colors) {
  34778. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  34779. }
  34780. // matricesIndices
  34781. var matricesIndices = parsedVertexData.matricesIndices;
  34782. if (matricesIndices) {
  34783. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  34784. }
  34785. // matricesWeights
  34786. var matricesWeights = parsedVertexData.matricesWeights;
  34787. if (matricesWeights) {
  34788. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  34789. }
  34790. // indices
  34791. var indices = parsedVertexData.indices;
  34792. if (indices) {
  34793. vertexData.indices = indices;
  34794. }
  34795. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  34796. };
  34797. return VertexData;
  34798. }());
  34799. BABYLON.VertexData = VertexData;
  34800. })(BABYLON || (BABYLON = {}));
  34801. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  34802. var BABYLON;
  34803. (function (BABYLON) {
  34804. /**
  34805. * Class used to store geometry data (vertex buffers + index buffer)
  34806. */
  34807. var Geometry = /** @class */ (function () {
  34808. /**
  34809. * Creates a new geometry
  34810. * @param id defines the unique ID
  34811. * @param scene defines the hosting scene
  34812. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  34813. * @param updatable defines if geometry must be updatable (false by default)
  34814. * @param mesh defines the mesh that will be associated with the geometry
  34815. */
  34816. function Geometry(id, scene, vertexData, updatable, mesh) {
  34817. if (updatable === void 0) { updatable = false; }
  34818. if (mesh === void 0) { mesh = null; }
  34819. /**
  34820. * Gets the delay loading state of the geometry (none by default which means not delayed)
  34821. */
  34822. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  34823. this._totalVertices = 0;
  34824. this._isDisposed = false;
  34825. this._indexBufferIsUpdatable = false;
  34826. this.id = id;
  34827. this._engine = scene.getEngine();
  34828. this._meshes = [];
  34829. this._scene = scene;
  34830. //Init vertex buffer cache
  34831. this._vertexBuffers = {};
  34832. this._indices = [];
  34833. this._updatable = updatable;
  34834. // vertexData
  34835. if (vertexData) {
  34836. this.setAllVerticesData(vertexData, updatable);
  34837. }
  34838. else {
  34839. this._totalVertices = 0;
  34840. this._indices = [];
  34841. }
  34842. if (this._engine.getCaps().vertexArrayObject) {
  34843. this._vertexArrayObjects = {};
  34844. }
  34845. // applyToMesh
  34846. if (mesh) {
  34847. if (mesh.getClassName() === "LinesMesh") {
  34848. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  34849. this.updateExtend();
  34850. }
  34851. this.applyToMesh(mesh);
  34852. mesh.computeWorldMatrix(true);
  34853. }
  34854. }
  34855. Object.defineProperty(Geometry.prototype, "boundingBias", {
  34856. /**
  34857. * 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
  34858. */
  34859. get: function () {
  34860. return this._boundingBias;
  34861. },
  34862. /**
  34863. * 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
  34864. */
  34865. set: function (value) {
  34866. if (this._boundingBias && this._boundingBias.equals(value)) {
  34867. return;
  34868. }
  34869. this._boundingBias = value.clone();
  34870. this.updateBoundingInfo(true, null);
  34871. },
  34872. enumerable: true,
  34873. configurable: true
  34874. });
  34875. /**
  34876. * Static function used to attach a new empty geometry to a mesh
  34877. * @param mesh defines the mesh to attach the geometry to
  34878. * @returns the new {BABYLON.Geometry}
  34879. */
  34880. Geometry.CreateGeometryForMesh = function (mesh) {
  34881. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  34882. geometry.applyToMesh(mesh);
  34883. return geometry;
  34884. };
  34885. Object.defineProperty(Geometry.prototype, "extend", {
  34886. /**
  34887. * Gets the current extend of the geometry
  34888. */
  34889. get: function () {
  34890. return this._extend;
  34891. },
  34892. enumerable: true,
  34893. configurable: true
  34894. });
  34895. /**
  34896. * Gets the hosting scene
  34897. * @returns the hosting {BABYLON.Scene}
  34898. */
  34899. Geometry.prototype.getScene = function () {
  34900. return this._scene;
  34901. };
  34902. /**
  34903. * Gets the hosting engine
  34904. * @returns the hosting {BABYLON.Engine}
  34905. */
  34906. Geometry.prototype.getEngine = function () {
  34907. return this._engine;
  34908. };
  34909. /**
  34910. * Defines if the geometry is ready to use
  34911. * @returns true if the geometry is ready to be used
  34912. */
  34913. Geometry.prototype.isReady = function () {
  34914. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  34915. };
  34916. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  34917. /**
  34918. * Gets a value indicating that the geometry should not be serialized
  34919. */
  34920. get: function () {
  34921. for (var index = 0; index < this._meshes.length; index++) {
  34922. if (!this._meshes[index].doNotSerialize) {
  34923. return false;
  34924. }
  34925. }
  34926. return true;
  34927. },
  34928. enumerable: true,
  34929. configurable: true
  34930. });
  34931. /** @ignore */
  34932. Geometry.prototype._rebuild = function () {
  34933. if (this._vertexArrayObjects) {
  34934. this._vertexArrayObjects = {};
  34935. }
  34936. // Index buffer
  34937. if (this._meshes.length !== 0 && this._indices) {
  34938. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  34939. }
  34940. // Vertex buffers
  34941. for (var key in this._vertexBuffers) {
  34942. var vertexBuffer = this._vertexBuffers[key];
  34943. vertexBuffer._rebuild();
  34944. }
  34945. };
  34946. /**
  34947. * Affects all gemetry data in one call
  34948. * @param vertexData defines the geometry data
  34949. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  34950. */
  34951. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  34952. vertexData.applyToGeometry(this, updatable);
  34953. this.notifyUpdate();
  34954. };
  34955. /**
  34956. * Set specific vertex data
  34957. * @param kind defines the data kind (Position, normal, etc...)
  34958. * @param data defines the vertex data to use
  34959. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  34960. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  34961. */
  34962. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  34963. if (updatable === void 0) { updatable = false; }
  34964. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  34965. this.setVerticesBuffer(buffer);
  34966. };
  34967. /**
  34968. * Removes a specific vertex data
  34969. * @param kind defines the data kind (Position, normal, etc...)
  34970. */
  34971. Geometry.prototype.removeVerticesData = function (kind) {
  34972. if (this._vertexBuffers[kind]) {
  34973. this._vertexBuffers[kind].dispose();
  34974. delete this._vertexBuffers[kind];
  34975. }
  34976. };
  34977. /**
  34978. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  34979. * @param buffer defines the vertex buffer to use
  34980. */
  34981. Geometry.prototype.setVerticesBuffer = function (buffer) {
  34982. var kind = buffer.getKind();
  34983. if (this._vertexBuffers[kind]) {
  34984. this._vertexBuffers[kind].dispose();
  34985. }
  34986. this._vertexBuffers[kind] = buffer;
  34987. if (kind === BABYLON.VertexBuffer.PositionKind) {
  34988. var data = buffer.getData();
  34989. var stride = buffer.getStrideSize();
  34990. this._totalVertices = data.length / stride;
  34991. this.updateExtend(data, stride);
  34992. this._resetPointsArrayCache();
  34993. var meshes = this._meshes;
  34994. var numOfMeshes = meshes.length;
  34995. for (var index = 0; index < numOfMeshes; index++) {
  34996. var mesh = meshes[index];
  34997. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  34998. mesh._createGlobalSubMesh(false);
  34999. mesh.computeWorldMatrix(true);
  35000. }
  35001. }
  35002. this.notifyUpdate(kind);
  35003. if (this._vertexArrayObjects) {
  35004. this._disposeVertexArrayObjects();
  35005. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  35006. }
  35007. };
  35008. /**
  35009. * Update a specific vertex buffer
  35010. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  35011. * It will do nothing if the buffer is not updatable
  35012. * @param kind defines the data kind (Position, normal, etc...)
  35013. * @param data defines the data to use
  35014. * @param offset defines the offset in the target buffer where to store the data
  35015. */
  35016. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  35017. var vertexBuffer = this.getVertexBuffer(kind);
  35018. if (!vertexBuffer) {
  35019. return;
  35020. }
  35021. vertexBuffer.updateDirectly(data, offset);
  35022. this.notifyUpdate(kind);
  35023. };
  35024. /**
  35025. * Update a specific vertex buffer
  35026. * This function will create a new buffer if the current one is not updatable
  35027. * @param kind defines the data kind (Position, normal, etc...)
  35028. * @param data defines the data to use
  35029. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  35030. */
  35031. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  35032. if (updateExtends === void 0) { updateExtends = false; }
  35033. var vertexBuffer = this.getVertexBuffer(kind);
  35034. if (!vertexBuffer) {
  35035. return;
  35036. }
  35037. vertexBuffer.update(data);
  35038. if (kind === BABYLON.VertexBuffer.PositionKind) {
  35039. var stride = vertexBuffer.getStrideSize();
  35040. this._totalVertices = data.length / stride;
  35041. this.updateBoundingInfo(updateExtends, data);
  35042. }
  35043. this.notifyUpdate(kind);
  35044. };
  35045. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  35046. if (updateExtends) {
  35047. this.updateExtend(data);
  35048. }
  35049. var meshes = this._meshes;
  35050. var numOfMeshes = meshes.length;
  35051. this._resetPointsArrayCache();
  35052. for (var index = 0; index < numOfMeshes; index++) {
  35053. var mesh = meshes[index];
  35054. if (updateExtends) {
  35055. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  35056. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  35057. var subMesh = mesh.subMeshes[subIndex];
  35058. subMesh.refreshBoundingInfo();
  35059. }
  35060. }
  35061. }
  35062. };
  35063. /** @ignore */
  35064. Geometry.prototype._bind = function (effect, indexToBind) {
  35065. if (!effect) {
  35066. return;
  35067. }
  35068. if (indexToBind === undefined) {
  35069. indexToBind = this._indexBuffer;
  35070. }
  35071. var vbs = this.getVertexBuffers();
  35072. if (!vbs) {
  35073. return;
  35074. }
  35075. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  35076. this._engine.bindBuffers(vbs, indexToBind, effect);
  35077. return;
  35078. }
  35079. // Using VAO
  35080. if (!this._vertexArrayObjects[effect.key]) {
  35081. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  35082. }
  35083. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  35084. };
  35085. /**
  35086. * Gets total number of vertices
  35087. * @returns the total number of vertices
  35088. */
  35089. Geometry.prototype.getTotalVertices = function () {
  35090. if (!this.isReady()) {
  35091. return 0;
  35092. }
  35093. return this._totalVertices;
  35094. };
  35095. /**
  35096. * Gets a specific vertex data attached to this geometry
  35097. * @param kind defines the data kind (Position, normal, etc...)
  35098. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  35099. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  35100. * @returns a float array containing vertex data
  35101. */
  35102. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  35103. var vertexBuffer = this.getVertexBuffer(kind);
  35104. if (!vertexBuffer) {
  35105. return null;
  35106. }
  35107. var orig = vertexBuffer.getData();
  35108. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  35109. return orig;
  35110. }
  35111. else {
  35112. var len = orig.length;
  35113. var copy = [];
  35114. for (var i = 0; i < len; i++) {
  35115. copy.push(orig[i]);
  35116. }
  35117. return copy;
  35118. }
  35119. };
  35120. /**
  35121. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  35122. * @param kind defines the data kind (Position, normal, etc...)
  35123. * @returns true if the vertex buffer with the specified kind is updatable
  35124. */
  35125. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  35126. var vb = this._vertexBuffers[kind];
  35127. if (!vb) {
  35128. return false;
  35129. }
  35130. return vb.isUpdatable();
  35131. };
  35132. /**
  35133. * Gets a specific vertex buffer
  35134. * @param kind defines the data kind (Position, normal, etc...)
  35135. * @returns a {BABYLON.VertexBuffer}
  35136. */
  35137. Geometry.prototype.getVertexBuffer = function (kind) {
  35138. if (!this.isReady()) {
  35139. return null;
  35140. }
  35141. return this._vertexBuffers[kind];
  35142. };
  35143. /**
  35144. * Returns all vertex buffers
  35145. * @return an object holding all vertex buffers indexed by kind
  35146. */
  35147. Geometry.prototype.getVertexBuffers = function () {
  35148. if (!this.isReady()) {
  35149. return null;
  35150. }
  35151. return this._vertexBuffers;
  35152. };
  35153. /**
  35154. * Gets a boolean indicating if specific vertex buffer is present
  35155. * @param kind defines the data kind (Position, normal, etc...)
  35156. * @returns true if data is present
  35157. */
  35158. Geometry.prototype.isVerticesDataPresent = function (kind) {
  35159. if (!this._vertexBuffers) {
  35160. if (this._delayInfo) {
  35161. return this._delayInfo.indexOf(kind) !== -1;
  35162. }
  35163. return false;
  35164. }
  35165. return this._vertexBuffers[kind] !== undefined;
  35166. };
  35167. /**
  35168. * Gets a list of all attached data kinds (Position, normal, etc...)
  35169. * @returns a list of string containing all kinds
  35170. */
  35171. Geometry.prototype.getVerticesDataKinds = function () {
  35172. var result = [];
  35173. var kind;
  35174. if (!this._vertexBuffers && this._delayInfo) {
  35175. for (kind in this._delayInfo) {
  35176. result.push(kind);
  35177. }
  35178. }
  35179. else {
  35180. for (kind in this._vertexBuffers) {
  35181. result.push(kind);
  35182. }
  35183. }
  35184. return result;
  35185. };
  35186. /**
  35187. * Update index buffer
  35188. * @param indices defines the indices to store in the index buffer
  35189. * @param offset defines the offset in the target buffer where to store the data
  35190. */
  35191. Geometry.prototype.updateIndices = function (indices, offset) {
  35192. if (!this._indexBuffer) {
  35193. return;
  35194. }
  35195. if (!this._indexBufferIsUpdatable) {
  35196. this.setIndices(indices, null, true);
  35197. }
  35198. else {
  35199. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  35200. }
  35201. };
  35202. /**
  35203. * Creates a new index buffer
  35204. * @param indices defines the indices to store in the index buffer
  35205. * @param totalVertices defines the total number of vertices (could be null)
  35206. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  35207. */
  35208. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  35209. if (totalVertices === void 0) { totalVertices = null; }
  35210. if (updatable === void 0) { updatable = false; }
  35211. if (this._indexBuffer) {
  35212. this._engine._releaseBuffer(this._indexBuffer);
  35213. }
  35214. this._disposeVertexArrayObjects();
  35215. this._indices = indices;
  35216. this._indexBufferIsUpdatable = updatable;
  35217. if (this._meshes.length !== 0 && this._indices) {
  35218. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  35219. }
  35220. if (totalVertices != undefined) {
  35221. this._totalVertices = totalVertices;
  35222. }
  35223. var meshes = this._meshes;
  35224. var numOfMeshes = meshes.length;
  35225. for (var index = 0; index < numOfMeshes; index++) {
  35226. meshes[index]._createGlobalSubMesh(true);
  35227. }
  35228. this.notifyUpdate();
  35229. };
  35230. /**
  35231. * Return the total number of indices
  35232. * @returns the total number of indices
  35233. */
  35234. Geometry.prototype.getTotalIndices = function () {
  35235. if (!this.isReady()) {
  35236. return 0;
  35237. }
  35238. return this._indices.length;
  35239. };
  35240. /**
  35241. * Gets the index buffer array
  35242. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  35243. * @returns the index buffer array
  35244. */
  35245. Geometry.prototype.getIndices = function (copyWhenShared) {
  35246. if (!this.isReady()) {
  35247. return null;
  35248. }
  35249. var orig = this._indices;
  35250. if (!copyWhenShared || this._meshes.length === 1) {
  35251. return orig;
  35252. }
  35253. else {
  35254. var len = orig.length;
  35255. var copy = [];
  35256. for (var i = 0; i < len; i++) {
  35257. copy.push(orig[i]);
  35258. }
  35259. return copy;
  35260. }
  35261. };
  35262. /**
  35263. * Gets the index buffer
  35264. * @return the index buffer
  35265. */
  35266. Geometry.prototype.getIndexBuffer = function () {
  35267. if (!this.isReady()) {
  35268. return null;
  35269. }
  35270. return this._indexBuffer;
  35271. };
  35272. /** @ignore */
  35273. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  35274. if (effect === void 0) { effect = null; }
  35275. if (!effect || !this._vertexArrayObjects) {
  35276. return;
  35277. }
  35278. if (this._vertexArrayObjects[effect.key]) {
  35279. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  35280. delete this._vertexArrayObjects[effect.key];
  35281. }
  35282. };
  35283. /**
  35284. * Release the associated resources for a specific mesh
  35285. * @param mesh defines the source mesh
  35286. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  35287. */
  35288. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  35289. var meshes = this._meshes;
  35290. var index = meshes.indexOf(mesh);
  35291. if (index === -1) {
  35292. return;
  35293. }
  35294. meshes.splice(index, 1);
  35295. mesh._geometry = null;
  35296. if (meshes.length === 0 && shouldDispose) {
  35297. this.dispose();
  35298. }
  35299. };
  35300. /**
  35301. * Apply current geometry to a given mesh
  35302. * @param mesh defines the mesh to apply geometry to
  35303. */
  35304. Geometry.prototype.applyToMesh = function (mesh) {
  35305. if (mesh._geometry === this) {
  35306. return;
  35307. }
  35308. var previousGeometry = mesh._geometry;
  35309. if (previousGeometry) {
  35310. previousGeometry.releaseForMesh(mesh);
  35311. }
  35312. var meshes = this._meshes;
  35313. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  35314. mesh._geometry = this;
  35315. this._scene.pushGeometry(this);
  35316. meshes.push(mesh);
  35317. if (this.isReady()) {
  35318. this._applyToMesh(mesh);
  35319. }
  35320. else {
  35321. mesh._boundingInfo = this._boundingInfo;
  35322. }
  35323. };
  35324. Geometry.prototype.updateExtend = function (data, stride) {
  35325. if (data === void 0) { data = null; }
  35326. if (!data) {
  35327. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  35328. }
  35329. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  35330. };
  35331. Geometry.prototype._applyToMesh = function (mesh) {
  35332. var numOfMeshes = this._meshes.length;
  35333. // vertexBuffers
  35334. for (var kind in this._vertexBuffers) {
  35335. if (numOfMeshes === 1) {
  35336. this._vertexBuffers[kind].create();
  35337. }
  35338. var buffer = this._vertexBuffers[kind].getBuffer();
  35339. if (buffer)
  35340. buffer.references = numOfMeshes;
  35341. if (kind === BABYLON.VertexBuffer.PositionKind) {
  35342. if (!this._extend) {
  35343. this.updateExtend(this._vertexBuffers[kind].getData());
  35344. }
  35345. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  35346. mesh._createGlobalSubMesh(false);
  35347. //bounding info was just created again, world matrix should be applied again.
  35348. mesh._updateBoundingInfo();
  35349. }
  35350. }
  35351. // indexBuffer
  35352. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  35353. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  35354. }
  35355. if (this._indexBuffer) {
  35356. this._indexBuffer.references = numOfMeshes;
  35357. }
  35358. };
  35359. Geometry.prototype.notifyUpdate = function (kind) {
  35360. if (this.onGeometryUpdated) {
  35361. this.onGeometryUpdated(this, kind);
  35362. }
  35363. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  35364. var mesh = _a[_i];
  35365. mesh._markSubMeshesAsAttributesDirty();
  35366. }
  35367. };
  35368. /**
  35369. * Load the geometry if it was flagged as delay loaded
  35370. * @param scene defines the hosting scene
  35371. * @param onLoaded defines a callback called when the geometry is loaded
  35372. */
  35373. Geometry.prototype.load = function (scene, onLoaded) {
  35374. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  35375. return;
  35376. }
  35377. if (this.isReady()) {
  35378. if (onLoaded) {
  35379. onLoaded();
  35380. }
  35381. return;
  35382. }
  35383. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  35384. this._queueLoad(scene, onLoaded);
  35385. };
  35386. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  35387. var _this = this;
  35388. if (!this.delayLoadingFile) {
  35389. return;
  35390. }
  35391. scene._addPendingData(this);
  35392. scene._loadFile(this.delayLoadingFile, function (data) {
  35393. if (!_this._delayLoadingFunction) {
  35394. return;
  35395. }
  35396. _this._delayLoadingFunction(JSON.parse(data), _this);
  35397. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  35398. _this._delayInfo = [];
  35399. scene._removePendingData(_this);
  35400. var meshes = _this._meshes;
  35401. var numOfMeshes = meshes.length;
  35402. for (var index = 0; index < numOfMeshes; index++) {
  35403. _this._applyToMesh(meshes[index]);
  35404. }
  35405. if (onLoaded) {
  35406. onLoaded();
  35407. }
  35408. }, undefined, true);
  35409. };
  35410. /**
  35411. * Invert the geometry to move from a right handed system to a left handed one.
  35412. */
  35413. Geometry.prototype.toLeftHanded = function () {
  35414. // Flip faces
  35415. var tIndices = this.getIndices(false);
  35416. if (tIndices != null && tIndices.length > 0) {
  35417. for (var i = 0; i < tIndices.length; i += 3) {
  35418. var tTemp = tIndices[i + 0];
  35419. tIndices[i + 0] = tIndices[i + 2];
  35420. tIndices[i + 2] = tTemp;
  35421. }
  35422. this.setIndices(tIndices);
  35423. }
  35424. // Negate position.z
  35425. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  35426. if (tPositions != null && tPositions.length > 0) {
  35427. for (var i = 0; i < tPositions.length; i += 3) {
  35428. tPositions[i + 2] = -tPositions[i + 2];
  35429. }
  35430. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  35431. }
  35432. // Negate normal.z
  35433. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  35434. if (tNormals != null && tNormals.length > 0) {
  35435. for (var i = 0; i < tNormals.length; i += 3) {
  35436. tNormals[i + 2] = -tNormals[i + 2];
  35437. }
  35438. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  35439. }
  35440. };
  35441. // Cache
  35442. /** @ignore */
  35443. Geometry.prototype._resetPointsArrayCache = function () {
  35444. this._positions = null;
  35445. };
  35446. /** @ignore */
  35447. Geometry.prototype._generatePointsArray = function () {
  35448. if (this._positions)
  35449. return true;
  35450. this._positions = [];
  35451. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  35452. if (!data) {
  35453. return false;
  35454. }
  35455. for (var index = 0; index < data.length; index += 3) {
  35456. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  35457. }
  35458. return true;
  35459. };
  35460. /**
  35461. * Gets a value indicating if the geometry is disposed
  35462. * @returns true if the geometry was disposed
  35463. */
  35464. Geometry.prototype.isDisposed = function () {
  35465. return this._isDisposed;
  35466. };
  35467. Geometry.prototype._disposeVertexArrayObjects = function () {
  35468. if (this._vertexArrayObjects) {
  35469. for (var kind in this._vertexArrayObjects) {
  35470. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  35471. }
  35472. this._vertexArrayObjects = {};
  35473. }
  35474. };
  35475. /**
  35476. * Free all associated resources
  35477. */
  35478. Geometry.prototype.dispose = function () {
  35479. var meshes = this._meshes;
  35480. var numOfMeshes = meshes.length;
  35481. var index;
  35482. for (index = 0; index < numOfMeshes; index++) {
  35483. this.releaseForMesh(meshes[index]);
  35484. }
  35485. this._meshes = [];
  35486. this._disposeVertexArrayObjects();
  35487. for (var kind in this._vertexBuffers) {
  35488. this._vertexBuffers[kind].dispose();
  35489. }
  35490. this._vertexBuffers = {};
  35491. this._totalVertices = 0;
  35492. if (this._indexBuffer) {
  35493. this._engine._releaseBuffer(this._indexBuffer);
  35494. }
  35495. this._indexBuffer = null;
  35496. this._indices = [];
  35497. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  35498. this.delayLoadingFile = null;
  35499. this._delayLoadingFunction = null;
  35500. this._delayInfo = [];
  35501. this._boundingInfo = null;
  35502. this._scene.removeGeometry(this);
  35503. this._isDisposed = true;
  35504. };
  35505. /**
  35506. * Clone the current geometry into a new geometry
  35507. * @param id defines the unique ID of the new geometry
  35508. * @returns a new geometry object
  35509. */
  35510. Geometry.prototype.copy = function (id) {
  35511. var vertexData = new BABYLON.VertexData();
  35512. vertexData.indices = [];
  35513. var indices = this.getIndices();
  35514. if (indices) {
  35515. for (var index = 0; index < indices.length; index++) {
  35516. vertexData.indices.push(indices[index]);
  35517. }
  35518. }
  35519. var updatable = false;
  35520. var stopChecking = false;
  35521. var kind;
  35522. for (kind in this._vertexBuffers) {
  35523. // using slice() to make a copy of the array and not just reference it
  35524. var data = this.getVerticesData(kind);
  35525. if (data instanceof Float32Array) {
  35526. vertexData.set(new Float32Array(data), kind);
  35527. }
  35528. else {
  35529. vertexData.set(data.slice(0), kind);
  35530. }
  35531. if (!stopChecking) {
  35532. var vb = this.getVertexBuffer(kind);
  35533. if (vb) {
  35534. updatable = vb.isUpdatable();
  35535. stopChecking = !updatable;
  35536. }
  35537. }
  35538. }
  35539. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  35540. geometry.delayLoadState = this.delayLoadState;
  35541. geometry.delayLoadingFile = this.delayLoadingFile;
  35542. geometry._delayLoadingFunction = this._delayLoadingFunction;
  35543. for (kind in this._delayInfo) {
  35544. geometry._delayInfo = geometry._delayInfo || [];
  35545. geometry._delayInfo.push(kind);
  35546. }
  35547. // Bounding info
  35548. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  35549. return geometry;
  35550. };
  35551. /**
  35552. * Serialize the current geometry info (and not the vertices data) into a JSON object
  35553. * @return a JSON representation of the current geometry data (without the vertices data)
  35554. */
  35555. Geometry.prototype.serialize = function () {
  35556. var serializationObject = {};
  35557. serializationObject.id = this.id;
  35558. serializationObject.updatable = this._updatable;
  35559. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  35560. serializationObject.tags = BABYLON.Tags.GetTags(this);
  35561. }
  35562. return serializationObject;
  35563. };
  35564. Geometry.prototype.toNumberArray = function (origin) {
  35565. if (Array.isArray(origin)) {
  35566. return origin;
  35567. }
  35568. else {
  35569. return Array.prototype.slice.call(origin);
  35570. }
  35571. };
  35572. /**
  35573. * Serialize all vertices data into a JSON oject
  35574. * @returns a JSON representation of the current geometry data
  35575. */
  35576. Geometry.prototype.serializeVerticeData = function () {
  35577. var serializationObject = this.serialize();
  35578. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  35579. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  35580. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  35581. serializationObject.positions._updatable = true;
  35582. }
  35583. }
  35584. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  35585. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  35586. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  35587. serializationObject.normals._updatable = true;
  35588. }
  35589. }
  35590. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  35591. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  35592. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  35593. serializationObject.tangets._updatable = true;
  35594. }
  35595. }
  35596. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  35597. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  35598. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  35599. serializationObject.uvs._updatable = true;
  35600. }
  35601. }
  35602. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  35603. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  35604. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  35605. serializationObject.uv2s._updatable = true;
  35606. }
  35607. }
  35608. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  35609. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  35610. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  35611. serializationObject.uv3s._updatable = true;
  35612. }
  35613. }
  35614. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  35615. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  35616. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  35617. serializationObject.uv4s._updatable = true;
  35618. }
  35619. }
  35620. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  35621. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  35622. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  35623. serializationObject.uv5s._updatable = true;
  35624. }
  35625. }
  35626. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  35627. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  35628. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  35629. serializationObject.uv6s._updatable = true;
  35630. }
  35631. }
  35632. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  35633. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  35634. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  35635. serializationObject.colors._updatable = true;
  35636. }
  35637. }
  35638. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  35639. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  35640. serializationObject.matricesIndices._isExpanded = true;
  35641. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  35642. serializationObject.matricesIndices._updatable = true;
  35643. }
  35644. }
  35645. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  35646. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  35647. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  35648. serializationObject.matricesWeights._updatable = true;
  35649. }
  35650. }
  35651. serializationObject.indices = this.toNumberArray(this.getIndices());
  35652. return serializationObject;
  35653. };
  35654. // Statics
  35655. /**
  35656. * Extracts a clone of a mesh geometry
  35657. * @param mesh defines the source mesh
  35658. * @param id defines the unique ID of the new geometry object
  35659. * @returns the new geometry object
  35660. */
  35661. Geometry.ExtractFromMesh = function (mesh, id) {
  35662. var geometry = mesh._geometry;
  35663. if (!geometry) {
  35664. return null;
  35665. }
  35666. return geometry.copy(id);
  35667. };
  35668. /**
  35669. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  35670. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  35671. * Be aware Math.random() could cause collisions, but:
  35672. * "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"
  35673. * @returns a string containing a new GUID
  35674. */
  35675. Geometry.RandomId = function () {
  35676. return BABYLON.Tools.RandomId();
  35677. };
  35678. /** @ignore */
  35679. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  35680. var scene = mesh.getScene();
  35681. // Geometry
  35682. var geometryId = parsedGeometry.geometryId;
  35683. if (geometryId) {
  35684. var geometry = scene.getGeometryByID(geometryId);
  35685. if (geometry) {
  35686. geometry.applyToMesh(mesh);
  35687. }
  35688. }
  35689. else if (parsedGeometry instanceof ArrayBuffer) {
  35690. var binaryInfo = mesh._binaryInfo;
  35691. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  35692. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  35693. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  35694. }
  35695. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  35696. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  35697. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  35698. }
  35699. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  35700. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  35701. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  35702. }
  35703. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  35704. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  35705. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  35706. }
  35707. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  35708. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  35709. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  35710. }
  35711. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  35712. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  35713. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  35714. }
  35715. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  35716. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  35717. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  35718. }
  35719. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  35720. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  35721. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  35722. }
  35723. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  35724. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  35725. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  35726. }
  35727. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  35728. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  35729. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  35730. }
  35731. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  35732. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  35733. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  35734. }
  35735. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  35736. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  35737. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  35738. }
  35739. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  35740. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  35741. mesh.setIndices(indicesData, null);
  35742. }
  35743. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  35744. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  35745. mesh.subMeshes = [];
  35746. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  35747. var materialIndex = subMeshesData[(i * 5) + 0];
  35748. var verticesStart = subMeshesData[(i * 5) + 1];
  35749. var verticesCount = subMeshesData[(i * 5) + 2];
  35750. var indexStart = subMeshesData[(i * 5) + 3];
  35751. var indexCount = subMeshesData[(i * 5) + 4];
  35752. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  35753. }
  35754. }
  35755. }
  35756. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  35757. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  35758. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  35759. if (parsedGeometry.tangents) {
  35760. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  35761. }
  35762. if (parsedGeometry.uvs) {
  35763. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  35764. }
  35765. if (parsedGeometry.uvs2) {
  35766. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  35767. }
  35768. if (parsedGeometry.uvs3) {
  35769. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  35770. }
  35771. if (parsedGeometry.uvs4) {
  35772. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  35773. }
  35774. if (parsedGeometry.uvs5) {
  35775. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  35776. }
  35777. if (parsedGeometry.uvs6) {
  35778. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  35779. }
  35780. if (parsedGeometry.colors) {
  35781. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  35782. }
  35783. if (parsedGeometry.matricesIndices) {
  35784. if (!parsedGeometry.matricesIndices._isExpanded) {
  35785. var floatIndices = [];
  35786. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  35787. var matricesIndex = parsedGeometry.matricesIndices[i];
  35788. floatIndices.push(matricesIndex & 0x000000FF);
  35789. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  35790. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  35791. floatIndices.push(matricesIndex >> 24);
  35792. }
  35793. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  35794. }
  35795. else {
  35796. delete parsedGeometry.matricesIndices._isExpanded;
  35797. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  35798. }
  35799. }
  35800. if (parsedGeometry.matricesIndicesExtra) {
  35801. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  35802. var floatIndices = [];
  35803. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  35804. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  35805. floatIndices.push(matricesIndex & 0x000000FF);
  35806. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  35807. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  35808. floatIndices.push(matricesIndex >> 24);
  35809. }
  35810. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  35811. }
  35812. else {
  35813. delete parsedGeometry.matricesIndices._isExpanded;
  35814. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  35815. }
  35816. }
  35817. if (parsedGeometry.matricesWeights) {
  35818. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  35819. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  35820. }
  35821. if (parsedGeometry.matricesWeightsExtra) {
  35822. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  35823. }
  35824. mesh.setIndices(parsedGeometry.indices, null);
  35825. }
  35826. // SubMeshes
  35827. if (parsedGeometry.subMeshes) {
  35828. mesh.subMeshes = [];
  35829. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  35830. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  35831. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  35832. }
  35833. }
  35834. // Flat shading
  35835. if (mesh._shouldGenerateFlatShading) {
  35836. mesh.convertToFlatShadedMesh();
  35837. delete mesh._shouldGenerateFlatShading;
  35838. }
  35839. // Update
  35840. mesh.computeWorldMatrix(true);
  35841. // Octree
  35842. var sceneOctree = scene.selectionOctree;
  35843. if (sceneOctree !== undefined && sceneOctree !== null) {
  35844. sceneOctree.addMesh(mesh);
  35845. }
  35846. };
  35847. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  35848. var epsilon = 1e-3;
  35849. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  35850. return;
  35851. }
  35852. var noInfluenceBoneIndex = 0.0;
  35853. if (parsedGeometry.skeletonId > -1) {
  35854. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  35855. if (!skeleton) {
  35856. return;
  35857. }
  35858. noInfluenceBoneIndex = skeleton.bones.length;
  35859. }
  35860. else {
  35861. return;
  35862. }
  35863. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  35864. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  35865. var matricesWeights = parsedGeometry.matricesWeights;
  35866. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  35867. var influencers = parsedGeometry.numBoneInfluencer;
  35868. var size = matricesWeights.length;
  35869. for (var i = 0; i < size; i += 4) {
  35870. var weight = 0.0;
  35871. var firstZeroWeight = -1;
  35872. for (var j = 0; j < 4; j++) {
  35873. var w = matricesWeights[i + j];
  35874. weight += w;
  35875. if (w < epsilon && firstZeroWeight < 0) {
  35876. firstZeroWeight = j;
  35877. }
  35878. }
  35879. if (matricesWeightsExtra) {
  35880. for (var j = 0; j < 4; j++) {
  35881. var w = matricesWeightsExtra[i + j];
  35882. weight += w;
  35883. if (w < epsilon && firstZeroWeight < 0) {
  35884. firstZeroWeight = j + 4;
  35885. }
  35886. }
  35887. }
  35888. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  35889. firstZeroWeight = influencers - 1;
  35890. }
  35891. if (weight > epsilon) {
  35892. var mweight = 1.0 / weight;
  35893. for (var j = 0; j < 4; j++) {
  35894. matricesWeights[i + j] *= mweight;
  35895. }
  35896. if (matricesWeightsExtra) {
  35897. for (var j = 0; j < 4; j++) {
  35898. matricesWeightsExtra[i + j] *= mweight;
  35899. }
  35900. }
  35901. }
  35902. else {
  35903. if (firstZeroWeight >= 4) {
  35904. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  35905. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  35906. }
  35907. else {
  35908. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  35909. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  35910. }
  35911. }
  35912. }
  35913. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  35914. if (parsedGeometry.matricesWeightsExtra) {
  35915. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  35916. }
  35917. };
  35918. /**
  35919. * Create a new geometry from persisted data (Using .babylon file format)
  35920. * @param parsedVertexData defines the persisted data
  35921. * @param scene defines the hosting scene
  35922. * @param rootUrl defines the root url to use to load assets (like delayed data)
  35923. * @returns the new geometry object
  35924. */
  35925. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  35926. if (scene.getGeometryByID(parsedVertexData.id)) {
  35927. return null; // null since geometry could be something else than a box...
  35928. }
  35929. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  35930. if (BABYLON.Tags) {
  35931. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  35932. }
  35933. if (parsedVertexData.delayLoadingFile) {
  35934. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  35935. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  35936. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  35937. geometry._delayInfo = [];
  35938. if (parsedVertexData.hasUVs) {
  35939. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  35940. }
  35941. if (parsedVertexData.hasUVs2) {
  35942. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  35943. }
  35944. if (parsedVertexData.hasUVs3) {
  35945. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  35946. }
  35947. if (parsedVertexData.hasUVs4) {
  35948. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  35949. }
  35950. if (parsedVertexData.hasUVs5) {
  35951. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  35952. }
  35953. if (parsedVertexData.hasUVs6) {
  35954. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  35955. }
  35956. if (parsedVertexData.hasColors) {
  35957. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  35958. }
  35959. if (parsedVertexData.hasMatricesIndices) {
  35960. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  35961. }
  35962. if (parsedVertexData.hasMatricesWeights) {
  35963. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  35964. }
  35965. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  35966. }
  35967. else {
  35968. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  35969. }
  35970. scene.pushGeometry(geometry, true);
  35971. return geometry;
  35972. };
  35973. return Geometry;
  35974. }());
  35975. BABYLON.Geometry = Geometry;
  35976. // Primitives
  35977. /// Abstract class
  35978. /**
  35979. * Abstract class used to provide common services for all typed geometries
  35980. */
  35981. var _PrimitiveGeometry = /** @class */ (function (_super) {
  35982. __extends(_PrimitiveGeometry, _super);
  35983. /**
  35984. * Creates a new typed geometry
  35985. * @param id defines the unique ID of the geometry
  35986. * @param scene defines the hosting scene
  35987. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35988. * @param mesh defines the hosting mesh (can be null)
  35989. */
  35990. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  35991. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  35992. if (mesh === void 0) { mesh = null; }
  35993. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  35994. _this._canBeRegenerated = _canBeRegenerated;
  35995. _this._beingRegenerated = true;
  35996. _this.regenerate();
  35997. _this._beingRegenerated = false;
  35998. return _this;
  35999. }
  36000. /**
  36001. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  36002. * @returns true if the geometry can be regenerated
  36003. */
  36004. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  36005. return this._canBeRegenerated;
  36006. };
  36007. /**
  36008. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  36009. */
  36010. _PrimitiveGeometry.prototype.regenerate = function () {
  36011. if (!this._canBeRegenerated) {
  36012. return;
  36013. }
  36014. this._beingRegenerated = true;
  36015. this.setAllVerticesData(this._regenerateVertexData(), false);
  36016. this._beingRegenerated = false;
  36017. };
  36018. /**
  36019. * Clone the geometry
  36020. * @param id defines the unique ID of the new geometry
  36021. * @returns the new geometry
  36022. */
  36023. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  36024. return _super.prototype.copy.call(this, id);
  36025. };
  36026. // overrides
  36027. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  36028. if (!this._beingRegenerated) {
  36029. return;
  36030. }
  36031. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  36032. };
  36033. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  36034. if (!this._beingRegenerated) {
  36035. return;
  36036. }
  36037. _super.prototype.setVerticesData.call(this, kind, data, false);
  36038. };
  36039. // to override
  36040. /** @ignore */
  36041. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  36042. throw new Error("Abstract method");
  36043. };
  36044. _PrimitiveGeometry.prototype.copy = function (id) {
  36045. throw new Error("Must be overriden in sub-classes.");
  36046. };
  36047. _PrimitiveGeometry.prototype.serialize = function () {
  36048. var serializationObject = _super.prototype.serialize.call(this);
  36049. serializationObject.canBeRegenerated = this.canBeRegenerated();
  36050. return serializationObject;
  36051. };
  36052. return _PrimitiveGeometry;
  36053. }(Geometry));
  36054. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  36055. /**
  36056. * Creates a ribbon geometry
  36057. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  36058. */
  36059. var RibbonGeometry = /** @class */ (function (_super) {
  36060. __extends(RibbonGeometry, _super);
  36061. /**
  36062. * Creates a ribbon geometry
  36063. * @param id defines the unique ID of the geometry
  36064. * @param scene defines the hosting scene
  36065. * @param pathArray defines the array of paths to use
  36066. * @param closeArray defines if the last path and the first path must be joined
  36067. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  36068. * @param offset defines the offset between points
  36069. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36070. * @param mesh defines the hosting mesh (can be null)
  36071. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36072. */
  36073. function RibbonGeometry(id, scene,
  36074. /**
  36075. * Defines the array of paths to use
  36076. */
  36077. pathArray,
  36078. /**
  36079. * Defines if the last and first points of each path in your pathArray must be joined
  36080. */
  36081. closeArray,
  36082. /**
  36083. * Defines if the last and first points of each path in your pathArray must be joined
  36084. */
  36085. closePath,
  36086. /**
  36087. * Defines the offset between points
  36088. */
  36089. offset, canBeRegenerated, mesh,
  36090. /**
  36091. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36092. */
  36093. side) {
  36094. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36095. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36096. _this.pathArray = pathArray;
  36097. _this.closeArray = closeArray;
  36098. _this.closePath = closePath;
  36099. _this.offset = offset;
  36100. _this.side = side;
  36101. return _this;
  36102. }
  36103. /** @ignore */
  36104. RibbonGeometry.prototype._regenerateVertexData = function () {
  36105. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  36106. };
  36107. RibbonGeometry.prototype.copy = function (id) {
  36108. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  36109. };
  36110. return RibbonGeometry;
  36111. }(_PrimitiveGeometry));
  36112. BABYLON.RibbonGeometry = RibbonGeometry;
  36113. /**
  36114. * Creates a box geometry
  36115. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  36116. */
  36117. var BoxGeometry = /** @class */ (function (_super) {
  36118. __extends(BoxGeometry, _super);
  36119. /**
  36120. * Creates a box geometry
  36121. * @param id defines the unique ID of the geometry
  36122. * @param scene defines the hosting scene
  36123. * @param size defines the zise of the box (width, height and depth are the same)
  36124. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36125. * @param mesh defines the hosting mesh (can be null)
  36126. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36127. */
  36128. function BoxGeometry(id, scene,
  36129. /**
  36130. * Defines the zise of the box (width, height and depth are the same)
  36131. */
  36132. size, canBeRegenerated, mesh,
  36133. /**
  36134. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36135. */
  36136. side) {
  36137. if (mesh === void 0) { mesh = null; }
  36138. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36139. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36140. _this.size = size;
  36141. _this.side = side;
  36142. return _this;
  36143. }
  36144. BoxGeometry.prototype._regenerateVertexData = function () {
  36145. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  36146. };
  36147. BoxGeometry.prototype.copy = function (id) {
  36148. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  36149. };
  36150. BoxGeometry.prototype.serialize = function () {
  36151. var serializationObject = _super.prototype.serialize.call(this);
  36152. serializationObject.size = this.size;
  36153. return serializationObject;
  36154. };
  36155. BoxGeometry.Parse = function (parsedBox, scene) {
  36156. if (scene.getGeometryByID(parsedBox.id)) {
  36157. return null; // null since geometry could be something else than a box...
  36158. }
  36159. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  36160. if (BABYLON.Tags) {
  36161. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  36162. }
  36163. scene.pushGeometry(box, true);
  36164. return box;
  36165. };
  36166. return BoxGeometry;
  36167. }(_PrimitiveGeometry));
  36168. BABYLON.BoxGeometry = BoxGeometry;
  36169. /**
  36170. * Creates a sphere geometry
  36171. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  36172. */
  36173. var SphereGeometry = /** @class */ (function (_super) {
  36174. __extends(SphereGeometry, _super);
  36175. /**
  36176. * Create a new sphere geometry
  36177. * @param id defines the unique ID of the geometry
  36178. * @param scene defines the hosting scene
  36179. * @param segments defines the number of segments to use to create the sphere
  36180. * @param diameter defines the diameter of the sphere
  36181. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36182. * @param mesh defines the hosting mesh (can be null)
  36183. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36184. */
  36185. function SphereGeometry(id, scene,
  36186. /**
  36187. * Defines the number of segments to use to create the sphere
  36188. */
  36189. segments,
  36190. /**
  36191. * Defines the diameter of the sphere
  36192. */
  36193. diameter, canBeRegenerated, mesh,
  36194. /**
  36195. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36196. */
  36197. side) {
  36198. if (mesh === void 0) { mesh = null; }
  36199. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36200. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36201. _this.segments = segments;
  36202. _this.diameter = diameter;
  36203. _this.side = side;
  36204. return _this;
  36205. }
  36206. SphereGeometry.prototype._regenerateVertexData = function () {
  36207. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  36208. };
  36209. SphereGeometry.prototype.copy = function (id) {
  36210. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  36211. };
  36212. SphereGeometry.prototype.serialize = function () {
  36213. var serializationObject = _super.prototype.serialize.call(this);
  36214. serializationObject.segments = this.segments;
  36215. serializationObject.diameter = this.diameter;
  36216. return serializationObject;
  36217. };
  36218. SphereGeometry.Parse = function (parsedSphere, scene) {
  36219. if (scene.getGeometryByID(parsedSphere.id)) {
  36220. return null; // null since geometry could be something else than a sphere...
  36221. }
  36222. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  36223. if (BABYLON.Tags) {
  36224. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  36225. }
  36226. scene.pushGeometry(sphere, true);
  36227. return sphere;
  36228. };
  36229. return SphereGeometry;
  36230. }(_PrimitiveGeometry));
  36231. BABYLON.SphereGeometry = SphereGeometry;
  36232. /**
  36233. * Creates a disc geometry
  36234. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  36235. */
  36236. var DiscGeometry = /** @class */ (function (_super) {
  36237. __extends(DiscGeometry, _super);
  36238. /**
  36239. * Creates a new disc geometry
  36240. * @param id defines the unique ID of the geometry
  36241. * @param scene defines the hosting scene
  36242. * @param radius defines the radius of the disc
  36243. * @param tessellation defines the tesselation factor to apply to the disc
  36244. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36245. * @param mesh defines the hosting mesh (can be null)
  36246. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36247. */
  36248. function DiscGeometry(id, scene,
  36249. /**
  36250. * Defines the radius of the disc
  36251. */
  36252. radius,
  36253. /**
  36254. * Defines the tesselation factor to apply to the disc
  36255. */
  36256. tessellation, canBeRegenerated, mesh,
  36257. /**
  36258. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36259. */
  36260. side) {
  36261. if (mesh === void 0) { mesh = null; }
  36262. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36263. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36264. _this.radius = radius;
  36265. _this.tessellation = tessellation;
  36266. _this.side = side;
  36267. return _this;
  36268. }
  36269. DiscGeometry.prototype._regenerateVertexData = function () {
  36270. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  36271. };
  36272. DiscGeometry.prototype.copy = function (id) {
  36273. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  36274. };
  36275. return DiscGeometry;
  36276. }(_PrimitiveGeometry));
  36277. BABYLON.DiscGeometry = DiscGeometry;
  36278. /**
  36279. * Creates a new cylinder geometry
  36280. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  36281. */
  36282. var CylinderGeometry = /** @class */ (function (_super) {
  36283. __extends(CylinderGeometry, _super);
  36284. /**
  36285. * Creates a new cylinder geometry
  36286. * @param id defines the unique ID of the geometry
  36287. * @param scene defines the hosting scene
  36288. * @param height defines the height of the cylinder
  36289. * @param diameterTop defines the diameter of the cylinder's top cap
  36290. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  36291. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  36292. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  36293. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36294. * @param mesh defines the hosting mesh (can be null)
  36295. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36296. */
  36297. function CylinderGeometry(id, scene,
  36298. /**
  36299. * Defines the height of the cylinder
  36300. */
  36301. height,
  36302. /**
  36303. * Defines the diameter of the cylinder's top cap
  36304. */
  36305. diameterTop,
  36306. /**
  36307. * Defines the diameter of the cylinder's bottom cap
  36308. */
  36309. diameterBottom,
  36310. /**
  36311. * Defines the tessellation factor to apply to the cylinder
  36312. */
  36313. tessellation,
  36314. /**
  36315. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  36316. */
  36317. subdivisions, canBeRegenerated, mesh,
  36318. /**
  36319. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36320. */
  36321. side) {
  36322. if (subdivisions === void 0) { subdivisions = 1; }
  36323. if (mesh === void 0) { mesh = null; }
  36324. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36325. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36326. _this.height = height;
  36327. _this.diameterTop = diameterTop;
  36328. _this.diameterBottom = diameterBottom;
  36329. _this.tessellation = tessellation;
  36330. _this.subdivisions = subdivisions;
  36331. _this.side = side;
  36332. return _this;
  36333. }
  36334. CylinderGeometry.prototype._regenerateVertexData = function () {
  36335. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  36336. };
  36337. CylinderGeometry.prototype.copy = function (id) {
  36338. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  36339. };
  36340. CylinderGeometry.prototype.serialize = function () {
  36341. var serializationObject = _super.prototype.serialize.call(this);
  36342. serializationObject.height = this.height;
  36343. serializationObject.diameterTop = this.diameterTop;
  36344. serializationObject.diameterBottom = this.diameterBottom;
  36345. serializationObject.tessellation = this.tessellation;
  36346. return serializationObject;
  36347. };
  36348. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  36349. if (scene.getGeometryByID(parsedCylinder.id)) {
  36350. return null; // null since geometry could be something else than a cylinder...
  36351. }
  36352. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  36353. if (BABYLON.Tags) {
  36354. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  36355. }
  36356. scene.pushGeometry(cylinder, true);
  36357. return cylinder;
  36358. };
  36359. return CylinderGeometry;
  36360. }(_PrimitiveGeometry));
  36361. BABYLON.CylinderGeometry = CylinderGeometry;
  36362. /**
  36363. * Creates a new torus geometry
  36364. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  36365. */
  36366. var TorusGeometry = /** @class */ (function (_super) {
  36367. __extends(TorusGeometry, _super);
  36368. /**
  36369. * Creates a new torus geometry
  36370. * @param id defines the unique ID of the geometry
  36371. * @param scene defines the hosting scene
  36372. * @param diameter defines the diameter of the torus
  36373. * @param thickness defines the thickness of the torus (ie. internal diameter)
  36374. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  36375. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36376. * @param mesh defines the hosting mesh (can be null)
  36377. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36378. */
  36379. function TorusGeometry(id, scene,
  36380. /**
  36381. * Defines the diameter of the torus
  36382. */
  36383. diameter,
  36384. /**
  36385. * Defines the thickness of the torus (ie. internal diameter)
  36386. */
  36387. thickness,
  36388. /**
  36389. * Defines the tesselation factor to apply to the torus
  36390. */
  36391. tessellation, canBeRegenerated, mesh,
  36392. /**
  36393. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36394. */
  36395. side) {
  36396. if (mesh === void 0) { mesh = null; }
  36397. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36398. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36399. _this.diameter = diameter;
  36400. _this.thickness = thickness;
  36401. _this.tessellation = tessellation;
  36402. _this.side = side;
  36403. return _this;
  36404. }
  36405. TorusGeometry.prototype._regenerateVertexData = function () {
  36406. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  36407. };
  36408. TorusGeometry.prototype.copy = function (id) {
  36409. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  36410. };
  36411. TorusGeometry.prototype.serialize = function () {
  36412. var serializationObject = _super.prototype.serialize.call(this);
  36413. serializationObject.diameter = this.diameter;
  36414. serializationObject.thickness = this.thickness;
  36415. serializationObject.tessellation = this.tessellation;
  36416. return serializationObject;
  36417. };
  36418. TorusGeometry.Parse = function (parsedTorus, scene) {
  36419. if (scene.getGeometryByID(parsedTorus.id)) {
  36420. return null; // null since geometry could be something else than a torus...
  36421. }
  36422. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  36423. if (BABYLON.Tags) {
  36424. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  36425. }
  36426. scene.pushGeometry(torus, true);
  36427. return torus;
  36428. };
  36429. return TorusGeometry;
  36430. }(_PrimitiveGeometry));
  36431. BABYLON.TorusGeometry = TorusGeometry;
  36432. /**
  36433. * Creates a new ground geometry
  36434. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  36435. */
  36436. var GroundGeometry = /** @class */ (function (_super) {
  36437. __extends(GroundGeometry, _super);
  36438. /**
  36439. * Creates a new ground geometry
  36440. * @param id defines the unique ID of the geometry
  36441. * @param scene defines the hosting scene
  36442. * @param width defines the width of the ground
  36443. * @param height defines the height of the ground
  36444. * @param subdivisions defines the subdivisions to apply to the ground
  36445. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36446. * @param mesh defines the hosting mesh (can be null)
  36447. */
  36448. function GroundGeometry(id, scene,
  36449. /**
  36450. * Defines the width of the ground
  36451. */
  36452. width,
  36453. /**
  36454. * Defines the height of the ground
  36455. */
  36456. height,
  36457. /**
  36458. * Defines the subdivisions to apply to the ground
  36459. */
  36460. subdivisions, canBeRegenerated, mesh) {
  36461. if (mesh === void 0) { mesh = null; }
  36462. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36463. _this.width = width;
  36464. _this.height = height;
  36465. _this.subdivisions = subdivisions;
  36466. return _this;
  36467. }
  36468. GroundGeometry.prototype._regenerateVertexData = function () {
  36469. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  36470. };
  36471. GroundGeometry.prototype.copy = function (id) {
  36472. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  36473. };
  36474. GroundGeometry.prototype.serialize = function () {
  36475. var serializationObject = _super.prototype.serialize.call(this);
  36476. serializationObject.width = this.width;
  36477. serializationObject.height = this.height;
  36478. serializationObject.subdivisions = this.subdivisions;
  36479. return serializationObject;
  36480. };
  36481. GroundGeometry.Parse = function (parsedGround, scene) {
  36482. if (scene.getGeometryByID(parsedGround.id)) {
  36483. return null; // null since geometry could be something else than a ground...
  36484. }
  36485. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  36486. if (BABYLON.Tags) {
  36487. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  36488. }
  36489. scene.pushGeometry(ground, true);
  36490. return ground;
  36491. };
  36492. return GroundGeometry;
  36493. }(_PrimitiveGeometry));
  36494. BABYLON.GroundGeometry = GroundGeometry;
  36495. /**
  36496. * Creates a tiled ground geometry
  36497. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  36498. */
  36499. var TiledGroundGeometry = /** @class */ (function (_super) {
  36500. __extends(TiledGroundGeometry, _super);
  36501. /**
  36502. * Creates a tiled ground geometry
  36503. * @param id defines the unique ID of the geometry
  36504. * @param scene defines the hosting scene
  36505. * @param xmin defines the minimum value on X axis
  36506. * @param zmin defines the minimum value on Z axis
  36507. * @param xmax defines the maximum value on X axis
  36508. * @param zmax defines the maximum value on Z axis
  36509. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  36510. * @param precision defines the precision to use when computing the tiles
  36511. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36512. * @param mesh defines the hosting mesh (can be null)
  36513. */
  36514. function TiledGroundGeometry(id, scene,
  36515. /**
  36516. * Defines the minimum value on X axis
  36517. */
  36518. xmin,
  36519. /**
  36520. * Defines the minimum value on Z axis
  36521. */
  36522. zmin,
  36523. /**
  36524. * Defines the maximum value on X axis
  36525. */
  36526. xmax,
  36527. /**
  36528. * Defines the maximum value on Z axis
  36529. */
  36530. zmax,
  36531. /**
  36532. * Defines the subdivisions to apply to the ground
  36533. */
  36534. subdivisions,
  36535. /**
  36536. * Defines the precision to use when computing the tiles
  36537. */
  36538. precision, canBeRegenerated, mesh) {
  36539. if (mesh === void 0) { mesh = null; }
  36540. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36541. _this.xmin = xmin;
  36542. _this.zmin = zmin;
  36543. _this.xmax = xmax;
  36544. _this.zmax = zmax;
  36545. _this.subdivisions = subdivisions;
  36546. _this.precision = precision;
  36547. return _this;
  36548. }
  36549. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  36550. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  36551. };
  36552. TiledGroundGeometry.prototype.copy = function (id) {
  36553. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  36554. };
  36555. return TiledGroundGeometry;
  36556. }(_PrimitiveGeometry));
  36557. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  36558. /**
  36559. * Creates a plane geometry
  36560. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  36561. */
  36562. var PlaneGeometry = /** @class */ (function (_super) {
  36563. __extends(PlaneGeometry, _super);
  36564. /**
  36565. * Creates a plane geometry
  36566. * @param id defines the unique ID of the geometry
  36567. * @param scene defines the hosting scene
  36568. * @param size defines the size of the plane (width === height)
  36569. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36570. * @param mesh defines the hosting mesh (can be null)
  36571. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36572. */
  36573. function PlaneGeometry(id, scene,
  36574. /**
  36575. * Defines the size of the plane (width === height)
  36576. */
  36577. size, canBeRegenerated, mesh,
  36578. /**
  36579. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36580. */
  36581. side) {
  36582. if (mesh === void 0) { mesh = null; }
  36583. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36584. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36585. _this.size = size;
  36586. _this.side = side;
  36587. return _this;
  36588. }
  36589. PlaneGeometry.prototype._regenerateVertexData = function () {
  36590. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  36591. };
  36592. PlaneGeometry.prototype.copy = function (id) {
  36593. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  36594. };
  36595. PlaneGeometry.prototype.serialize = function () {
  36596. var serializationObject = _super.prototype.serialize.call(this);
  36597. serializationObject.size = this.size;
  36598. return serializationObject;
  36599. };
  36600. PlaneGeometry.Parse = function (parsedPlane, scene) {
  36601. if (scene.getGeometryByID(parsedPlane.id)) {
  36602. return null; // null since geometry could be something else than a ground...
  36603. }
  36604. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  36605. if (BABYLON.Tags) {
  36606. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  36607. }
  36608. scene.pushGeometry(plane, true);
  36609. return plane;
  36610. };
  36611. return PlaneGeometry;
  36612. }(_PrimitiveGeometry));
  36613. BABYLON.PlaneGeometry = PlaneGeometry;
  36614. /**
  36615. * Creates a torus knot geometry
  36616. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  36617. */
  36618. var TorusKnotGeometry = /** @class */ (function (_super) {
  36619. __extends(TorusKnotGeometry, _super);
  36620. /**
  36621. * Creates a torus knot geometry
  36622. * @param id defines the unique ID of the geometry
  36623. * @param scene defines the hosting scene
  36624. * @param radius defines the radius of the torus knot
  36625. * @param tube defines the thickness of the torus knot tube
  36626. * @param radialSegments defines the number of radial segments
  36627. * @param tubularSegments defines the number of tubular segments
  36628. * @param p defines the first number of windings
  36629. * @param q defines the second number of windings
  36630. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36631. * @param mesh defines the hosting mesh (can be null)
  36632. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36633. */
  36634. function TorusKnotGeometry(id, scene,
  36635. /**
  36636. * Defines the radius of the torus knot
  36637. */
  36638. radius,
  36639. /**
  36640. * Defines the thickness of the torus knot tube
  36641. */
  36642. tube,
  36643. /**
  36644. * Defines the number of radial segments
  36645. */
  36646. radialSegments,
  36647. /**
  36648. * Defines the number of tubular segments
  36649. */
  36650. tubularSegments,
  36651. /**
  36652. * Defines the first number of windings
  36653. */
  36654. p,
  36655. /**
  36656. * Defines the second number of windings
  36657. */
  36658. q, canBeRegenerated, mesh,
  36659. /**
  36660. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36661. */
  36662. side) {
  36663. if (mesh === void 0) { mesh = null; }
  36664. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36665. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36666. _this.radius = radius;
  36667. _this.tube = tube;
  36668. _this.radialSegments = radialSegments;
  36669. _this.tubularSegments = tubularSegments;
  36670. _this.p = p;
  36671. _this.q = q;
  36672. _this.side = side;
  36673. return _this;
  36674. }
  36675. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  36676. 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 });
  36677. };
  36678. TorusKnotGeometry.prototype.copy = function (id) {
  36679. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  36680. };
  36681. TorusKnotGeometry.prototype.serialize = function () {
  36682. var serializationObject = _super.prototype.serialize.call(this);
  36683. serializationObject.radius = this.radius;
  36684. serializationObject.tube = this.tube;
  36685. serializationObject.radialSegments = this.radialSegments;
  36686. serializationObject.tubularSegments = this.tubularSegments;
  36687. serializationObject.p = this.p;
  36688. serializationObject.q = this.q;
  36689. return serializationObject;
  36690. };
  36691. ;
  36692. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  36693. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  36694. return null; // null since geometry could be something else than a ground...
  36695. }
  36696. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  36697. if (BABYLON.Tags) {
  36698. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  36699. }
  36700. scene.pushGeometry(torusKnot, true);
  36701. return torusKnot;
  36702. };
  36703. return TorusKnotGeometry;
  36704. }(_PrimitiveGeometry));
  36705. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  36706. //}
  36707. })(BABYLON || (BABYLON = {}));
  36708. //# sourceMappingURL=babylon.geometry.js.map
  36709. var BABYLON;
  36710. (function (BABYLON) {
  36711. /**
  36712. * PostProcessManager is used to manage one or more post processes or post process pipelines
  36713. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  36714. */
  36715. var PostProcessManager = /** @class */ (function () {
  36716. /**
  36717. * Creates a new instance of @see PostProcess
  36718. * @param scene The scene that the post process is associated with.
  36719. */
  36720. function PostProcessManager(scene) {
  36721. this._vertexBuffers = {};
  36722. this._scene = scene;
  36723. }
  36724. PostProcessManager.prototype._prepareBuffers = function () {
  36725. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  36726. return;
  36727. }
  36728. // VBO
  36729. var vertices = [];
  36730. vertices.push(1, 1);
  36731. vertices.push(-1, 1);
  36732. vertices.push(-1, -1);
  36733. vertices.push(1, -1);
  36734. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  36735. this._buildIndexBuffer();
  36736. };
  36737. PostProcessManager.prototype._buildIndexBuffer = function () {
  36738. // Indices
  36739. var indices = [];
  36740. indices.push(0);
  36741. indices.push(1);
  36742. indices.push(2);
  36743. indices.push(0);
  36744. indices.push(2);
  36745. indices.push(3);
  36746. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  36747. };
  36748. /**
  36749. * Rebuilds the vertex buffers of the manager.
  36750. */
  36751. PostProcessManager.prototype._rebuild = function () {
  36752. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  36753. if (!vb) {
  36754. return;
  36755. }
  36756. vb._rebuild();
  36757. this._buildIndexBuffer();
  36758. };
  36759. // Methods
  36760. /**
  36761. * Prepares a frame to be run through a post process.
  36762. * @param sourceTexture The input texture to the post procesess. (default: null)
  36763. * @param postProcesses An array of post processes to be run. (default: null)
  36764. * @returns True if the post processes were able to be run.
  36765. */
  36766. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  36767. if (sourceTexture === void 0) { sourceTexture = null; }
  36768. if (postProcesses === void 0) { postProcesses = null; }
  36769. var camera = this._scene.activeCamera;
  36770. if (!camera) {
  36771. return false;
  36772. }
  36773. var postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  36774. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  36775. return false;
  36776. }
  36777. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  36778. return true;
  36779. };
  36780. /**
  36781. * Manually render a set of post processes to a texture.
  36782. * @param postProcesses An array of post processes to be run.
  36783. * @param targetTexture The target texture to render to.
  36784. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  36785. */
  36786. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport) {
  36787. if (targetTexture === void 0) { targetTexture = null; }
  36788. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  36789. var engine = this._scene.getEngine();
  36790. for (var index = 0; index < postProcesses.length; index++) {
  36791. if (index < postProcesses.length - 1) {
  36792. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  36793. }
  36794. else {
  36795. if (targetTexture) {
  36796. engine.bindFramebuffer(targetTexture, 0, undefined, undefined, forceFullscreenViewport);
  36797. }
  36798. else {
  36799. engine.restoreDefaultFramebuffer();
  36800. }
  36801. }
  36802. var pp = postProcesses[index];
  36803. var effect = pp.apply();
  36804. if (effect) {
  36805. pp.onBeforeRenderObservable.notifyObservers(effect);
  36806. // VBOs
  36807. this._prepareBuffers();
  36808. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  36809. // Draw order
  36810. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  36811. pp.onAfterRenderObservable.notifyObservers(effect);
  36812. }
  36813. }
  36814. // Restore depth buffer
  36815. engine.setDepthBuffer(true);
  36816. engine.setDepthWrite(true);
  36817. };
  36818. /**
  36819. * Finalize the result of the output of the postprocesses.
  36820. * @param doNotPresent If true the result will not be displayed to the screen.
  36821. * @param targetTexture The target texture to render to.
  36822. * @param faceIndex The index of the face to bind the target texture to.
  36823. * @param postProcesses The array of post processes to render.
  36824. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  36825. */
  36826. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  36827. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  36828. var camera = this._scene.activeCamera;
  36829. if (!camera) {
  36830. return;
  36831. }
  36832. postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  36833. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  36834. return;
  36835. }
  36836. var engine = this._scene.getEngine();
  36837. for (var index = 0, len = postProcesses.length; index < len; index++) {
  36838. if (index < len - 1) {
  36839. postProcesses[index + 1].activate(camera, targetTexture);
  36840. }
  36841. else {
  36842. if (targetTexture) {
  36843. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  36844. }
  36845. else {
  36846. engine.restoreDefaultFramebuffer();
  36847. }
  36848. }
  36849. if (doNotPresent) {
  36850. break;
  36851. }
  36852. var pp = postProcesses[index];
  36853. var effect = pp.apply();
  36854. if (effect) {
  36855. pp.onBeforeRenderObservable.notifyObservers(effect);
  36856. // VBOs
  36857. this._prepareBuffers();
  36858. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  36859. // Draw order
  36860. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  36861. pp.onAfterRenderObservable.notifyObservers(effect);
  36862. }
  36863. }
  36864. // Restore states
  36865. engine.setDepthBuffer(true);
  36866. engine.setDepthWrite(true);
  36867. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  36868. };
  36869. /**
  36870. * Disposes of the post process manager.
  36871. */
  36872. PostProcessManager.prototype.dispose = function () {
  36873. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  36874. if (buffer) {
  36875. buffer.dispose();
  36876. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  36877. }
  36878. if (this._indexBuffer) {
  36879. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  36880. this._indexBuffer = null;
  36881. }
  36882. };
  36883. return PostProcessManager;
  36884. }());
  36885. BABYLON.PostProcessManager = PostProcessManager;
  36886. })(BABYLON || (BABYLON = {}));
  36887. //# sourceMappingURL=babylon.postProcessManager.js.map
  36888. var BABYLON;
  36889. (function (BABYLON) {
  36890. /**
  36891. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  36892. */
  36893. var PerformanceMonitor = /** @class */ (function () {
  36894. /**
  36895. * constructor
  36896. * @param frameSampleSize The number of samples required to saturate the sliding window
  36897. */
  36898. function PerformanceMonitor(frameSampleSize) {
  36899. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  36900. this._enabled = true;
  36901. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  36902. }
  36903. /**
  36904. * Samples current frame
  36905. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  36906. */
  36907. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  36908. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  36909. if (!this._enabled)
  36910. return;
  36911. if (this._lastFrameTimeMs != null) {
  36912. var dt = timeMs - this._lastFrameTimeMs;
  36913. this._rollingFrameTime.add(dt);
  36914. }
  36915. this._lastFrameTimeMs = timeMs;
  36916. };
  36917. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  36918. /**
  36919. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  36920. * @return Average frame time in milliseconds
  36921. */
  36922. get: function () {
  36923. return this._rollingFrameTime.average;
  36924. },
  36925. enumerable: true,
  36926. configurable: true
  36927. });
  36928. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  36929. /**
  36930. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  36931. * @return Frame time variance in milliseconds squared
  36932. */
  36933. get: function () {
  36934. return this._rollingFrameTime.variance;
  36935. },
  36936. enumerable: true,
  36937. configurable: true
  36938. });
  36939. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  36940. /**
  36941. * Returns the frame time of the most recent frame
  36942. * @return Frame time in milliseconds
  36943. */
  36944. get: function () {
  36945. return this._rollingFrameTime.history(0);
  36946. },
  36947. enumerable: true,
  36948. configurable: true
  36949. });
  36950. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  36951. /**
  36952. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  36953. * @return Framerate in frames per second
  36954. */
  36955. get: function () {
  36956. return 1000.0 / this._rollingFrameTime.average;
  36957. },
  36958. enumerable: true,
  36959. configurable: true
  36960. });
  36961. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  36962. /**
  36963. * Returns the average framerate in frames per second using the most recent frame time
  36964. * @return Framerate in frames per second
  36965. */
  36966. get: function () {
  36967. var history = this._rollingFrameTime.history(0);
  36968. if (history === 0) {
  36969. return 0;
  36970. }
  36971. return 1000.0 / history;
  36972. },
  36973. enumerable: true,
  36974. configurable: true
  36975. });
  36976. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  36977. /**
  36978. * Returns true if enough samples have been taken to completely fill the sliding window
  36979. * @return true if saturated
  36980. */
  36981. get: function () {
  36982. return this._rollingFrameTime.isSaturated();
  36983. },
  36984. enumerable: true,
  36985. configurable: true
  36986. });
  36987. /**
  36988. * Enables contributions to the sliding window sample set
  36989. */
  36990. PerformanceMonitor.prototype.enable = function () {
  36991. this._enabled = true;
  36992. };
  36993. /**
  36994. * Disables contributions to the sliding window sample set
  36995. * Samples will not be interpolated over the disabled period
  36996. */
  36997. PerformanceMonitor.prototype.disable = function () {
  36998. this._enabled = false;
  36999. //clear last sample to avoid interpolating over the disabled period when next enabled
  37000. this._lastFrameTimeMs = null;
  37001. };
  37002. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  37003. /**
  37004. * Returns true if sampling is enabled
  37005. * @return true if enabled
  37006. */
  37007. get: function () {
  37008. return this._enabled;
  37009. },
  37010. enumerable: true,
  37011. configurable: true
  37012. });
  37013. /**
  37014. * Resets performance monitor
  37015. */
  37016. PerformanceMonitor.prototype.reset = function () {
  37017. //clear last sample to avoid interpolating over the disabled period when next enabled
  37018. this._lastFrameTimeMs = null;
  37019. //wipe record
  37020. this._rollingFrameTime.reset();
  37021. };
  37022. return PerformanceMonitor;
  37023. }());
  37024. BABYLON.PerformanceMonitor = PerformanceMonitor;
  37025. /**
  37026. * RollingAverage
  37027. *
  37028. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  37029. */
  37030. var RollingAverage = /** @class */ (function () {
  37031. /**
  37032. * constructor
  37033. * @param length The number of samples required to saturate the sliding window
  37034. */
  37035. function RollingAverage(length) {
  37036. this._samples = new Array(length);
  37037. this.reset();
  37038. }
  37039. /**
  37040. * Adds a sample to the sample set
  37041. * @param v The sample value
  37042. */
  37043. RollingAverage.prototype.add = function (v) {
  37044. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  37045. var delta;
  37046. //we need to check if we've already wrapped round
  37047. if (this.isSaturated()) {
  37048. //remove bottom of stack from mean
  37049. var bottomValue = this._samples[this._pos];
  37050. delta = bottomValue - this.average;
  37051. this.average -= delta / (this._sampleCount - 1);
  37052. this._m2 -= delta * (bottomValue - this.average);
  37053. }
  37054. else {
  37055. this._sampleCount++;
  37056. }
  37057. //add new value to mean
  37058. delta = v - this.average;
  37059. this.average += delta / (this._sampleCount);
  37060. this._m2 += delta * (v - this.average);
  37061. //set the new variance
  37062. this.variance = this._m2 / (this._sampleCount - 1);
  37063. this._samples[this._pos] = v;
  37064. this._pos++;
  37065. this._pos %= this._samples.length; //positive wrap around
  37066. };
  37067. /**
  37068. * Returns previously added values or null if outside of history or outside the sliding window domain
  37069. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  37070. * @return Value previously recorded with add() or null if outside of range
  37071. */
  37072. RollingAverage.prototype.history = function (i) {
  37073. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  37074. return 0;
  37075. }
  37076. var i0 = this._wrapPosition(this._pos - 1.0);
  37077. return this._samples[this._wrapPosition(i0 - i)];
  37078. };
  37079. /**
  37080. * Returns true if enough samples have been taken to completely fill the sliding window
  37081. * @return true if sample-set saturated
  37082. */
  37083. RollingAverage.prototype.isSaturated = function () {
  37084. return this._sampleCount >= this._samples.length;
  37085. };
  37086. /**
  37087. * Resets the rolling average (equivalent to 0 samples taken so far)
  37088. */
  37089. RollingAverage.prototype.reset = function () {
  37090. this.average = 0;
  37091. this.variance = 0;
  37092. this._sampleCount = 0;
  37093. this._pos = 0;
  37094. this._m2 = 0;
  37095. };
  37096. /**
  37097. * Wraps a value around the sample range boundaries
  37098. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  37099. * @return Wrapped position in sample range
  37100. */
  37101. RollingAverage.prototype._wrapPosition = function (i) {
  37102. var max = this._samples.length;
  37103. return ((i % max) + max) % max;
  37104. };
  37105. return RollingAverage;
  37106. }());
  37107. BABYLON.RollingAverage = RollingAverage;
  37108. })(BABYLON || (BABYLON = {}));
  37109. //# sourceMappingURL=babylon.performanceMonitor.js.map
  37110. var BABYLON;
  37111. (function (BABYLON) {
  37112. /**
  37113. * This groups together the common properties used for image processing either in direct forward pass
  37114. * or through post processing effect depending on the use of the image processing pipeline in your scene
  37115. * or not.
  37116. */
  37117. var ImageProcessingConfiguration = /** @class */ (function () {
  37118. function ImageProcessingConfiguration() {
  37119. /**
  37120. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  37121. */
  37122. this.colorCurves = new BABYLON.ColorCurves();
  37123. this._colorCurvesEnabled = false;
  37124. this._colorGradingEnabled = false;
  37125. this._colorGradingWithGreenDepth = true;
  37126. this._colorGradingBGR = true;
  37127. this._exposure = 1.0;
  37128. this._toneMappingEnabled = false;
  37129. this._contrast = 1.0;
  37130. /**
  37131. * Vignette stretch size.
  37132. */
  37133. this.vignetteStretch = 0;
  37134. /**
  37135. * Vignette centre X Offset.
  37136. */
  37137. this.vignetteCentreX = 0;
  37138. /**
  37139. * Vignette centre Y Offset.
  37140. */
  37141. this.vignetteCentreY = 0;
  37142. /**
  37143. * Vignette weight or intensity of the vignette effect.
  37144. */
  37145. this.vignetteWeight = 1.5;
  37146. /**
  37147. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  37148. * if vignetteEnabled is set to true.
  37149. */
  37150. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  37151. /**
  37152. * Camera field of view used by the Vignette effect.
  37153. */
  37154. this.vignetteCameraFov = 0.5;
  37155. this._grainEnabled = false;
  37156. this._grainIntensity = 30;
  37157. this._grainAnimated = false;
  37158. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  37159. this._vignetteEnabled = false;
  37160. this._applyByPostProcess = false;
  37161. this._isEnabled = true;
  37162. /**
  37163. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  37164. * @type {BABYLON.Observable}
  37165. */
  37166. this.onUpdateParameters = new BABYLON.Observable();
  37167. }
  37168. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  37169. /**
  37170. * Gets wether the color curves effect is enabled.
  37171. */
  37172. get: function () {
  37173. return this._colorCurvesEnabled;
  37174. },
  37175. /**
  37176. * Sets wether the color curves effect is enabled.
  37177. */
  37178. set: function (value) {
  37179. if (this._colorCurvesEnabled === value) {
  37180. return;
  37181. }
  37182. this._colorCurvesEnabled = value;
  37183. this._updateParameters();
  37184. },
  37185. enumerable: true,
  37186. configurable: true
  37187. });
  37188. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  37189. /**
  37190. * Gets wether the color grading effect is enabled.
  37191. */
  37192. get: function () {
  37193. return this._colorGradingEnabled;
  37194. },
  37195. /**
  37196. * Sets wether the color grading effect is enabled.
  37197. */
  37198. set: function (value) {
  37199. if (this._colorGradingEnabled === value) {
  37200. return;
  37201. }
  37202. this._colorGradingEnabled = value;
  37203. this._updateParameters();
  37204. },
  37205. enumerable: true,
  37206. configurable: true
  37207. });
  37208. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  37209. /**
  37210. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  37211. */
  37212. get: function () {
  37213. return this._colorGradingWithGreenDepth;
  37214. },
  37215. /**
  37216. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  37217. */
  37218. set: function (value) {
  37219. if (this._colorGradingWithGreenDepth === value) {
  37220. return;
  37221. }
  37222. this._colorGradingWithGreenDepth = value;
  37223. this._updateParameters();
  37224. },
  37225. enumerable: true,
  37226. configurable: true
  37227. });
  37228. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  37229. /**
  37230. * Gets wether the color grading texture contains BGR values.
  37231. */
  37232. get: function () {
  37233. return this._colorGradingBGR;
  37234. },
  37235. /**
  37236. * Sets wether the color grading texture contains BGR values.
  37237. */
  37238. set: function (value) {
  37239. if (this._colorGradingBGR === value) {
  37240. return;
  37241. }
  37242. this._colorGradingBGR = value;
  37243. this._updateParameters();
  37244. },
  37245. enumerable: true,
  37246. configurable: true
  37247. });
  37248. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  37249. /**
  37250. * Gets the Exposure used in the effect.
  37251. */
  37252. get: function () {
  37253. return this._exposure;
  37254. },
  37255. /**
  37256. * Sets the Exposure used in the effect.
  37257. */
  37258. set: function (value) {
  37259. if (this._exposure === value) {
  37260. return;
  37261. }
  37262. this._exposure = value;
  37263. this._updateParameters();
  37264. },
  37265. enumerable: true,
  37266. configurable: true
  37267. });
  37268. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  37269. /**
  37270. * Gets wether the tone mapping effect is enabled.
  37271. */
  37272. get: function () {
  37273. return this._toneMappingEnabled;
  37274. },
  37275. /**
  37276. * Sets wether the tone mapping effect is enabled.
  37277. */
  37278. set: function (value) {
  37279. if (this._toneMappingEnabled === value) {
  37280. return;
  37281. }
  37282. this._toneMappingEnabled = value;
  37283. this._updateParameters();
  37284. },
  37285. enumerable: true,
  37286. configurable: true
  37287. });
  37288. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  37289. /**
  37290. * Gets the contrast used in the effect.
  37291. */
  37292. get: function () {
  37293. return this._contrast;
  37294. },
  37295. /**
  37296. * Sets the contrast used in the effect.
  37297. */
  37298. set: function (value) {
  37299. if (this._contrast === value) {
  37300. return;
  37301. }
  37302. this._contrast = value;
  37303. this._updateParameters();
  37304. },
  37305. enumerable: true,
  37306. configurable: true
  37307. });
  37308. Object.defineProperty(ImageProcessingConfiguration.prototype, "grainEnabled", {
  37309. /**
  37310. * If the grain effect should be enabled.
  37311. */
  37312. get: function () {
  37313. return this._grainEnabled;
  37314. },
  37315. set: function (value) {
  37316. if (this._grainEnabled === value) {
  37317. return;
  37318. }
  37319. this._grainEnabled = value;
  37320. this._updateParameters();
  37321. },
  37322. enumerable: true,
  37323. configurable: true
  37324. });
  37325. Object.defineProperty(ImageProcessingConfiguration.prototype, "grainIntensity", {
  37326. /**
  37327. * Amount of grain to be applied by the grain effect.
  37328. */
  37329. get: function () {
  37330. return this._grainIntensity;
  37331. },
  37332. set: function (value) {
  37333. if (this._grainIntensity === value) {
  37334. return;
  37335. }
  37336. this._grainIntensity = value;
  37337. },
  37338. enumerable: true,
  37339. configurable: true
  37340. });
  37341. Object.defineProperty(ImageProcessingConfiguration.prototype, "grainAnimated", {
  37342. /**
  37343. * If the grain effect should be animated.
  37344. */
  37345. get: function () {
  37346. return this._grainAnimated;
  37347. },
  37348. set: function (value) {
  37349. if (this._grainAnimated === value) {
  37350. return;
  37351. }
  37352. this._grainAnimated = value;
  37353. this._updateParameters();
  37354. },
  37355. enumerable: true,
  37356. configurable: true
  37357. });
  37358. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  37359. /**
  37360. * Gets the vignette blend mode allowing different kind of effect.
  37361. */
  37362. get: function () {
  37363. return this._vignetteBlendMode;
  37364. },
  37365. /**
  37366. * Sets the vignette blend mode allowing different kind of effect.
  37367. */
  37368. set: function (value) {
  37369. if (this._vignetteBlendMode === value) {
  37370. return;
  37371. }
  37372. this._vignetteBlendMode = value;
  37373. this._updateParameters();
  37374. },
  37375. enumerable: true,
  37376. configurable: true
  37377. });
  37378. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  37379. /**
  37380. * Gets wether the vignette effect is enabled.
  37381. */
  37382. get: function () {
  37383. return this._vignetteEnabled;
  37384. },
  37385. /**
  37386. * Sets wether the vignette effect is enabled.
  37387. */
  37388. set: function (value) {
  37389. if (this._vignetteEnabled === value) {
  37390. return;
  37391. }
  37392. this._vignetteEnabled = value;
  37393. this._updateParameters();
  37394. },
  37395. enumerable: true,
  37396. configurable: true
  37397. });
  37398. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  37399. /**
  37400. * Gets wether the image processing is applied through a post process or not.
  37401. */
  37402. get: function () {
  37403. return this._applyByPostProcess;
  37404. },
  37405. /**
  37406. * Sets wether the image processing is applied through a post process or not.
  37407. */
  37408. set: function (value) {
  37409. if (this._applyByPostProcess === value) {
  37410. return;
  37411. }
  37412. this._applyByPostProcess = value;
  37413. this._updateParameters();
  37414. },
  37415. enumerable: true,
  37416. configurable: true
  37417. });
  37418. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  37419. /**
  37420. * Gets wether the image processing is enabled or not.
  37421. */
  37422. get: function () {
  37423. return this._isEnabled;
  37424. },
  37425. /**
  37426. * Sets wether the image processing is enabled or not.
  37427. */
  37428. set: function (value) {
  37429. if (this._isEnabled === value) {
  37430. return;
  37431. }
  37432. this._isEnabled = value;
  37433. this._updateParameters();
  37434. },
  37435. enumerable: true,
  37436. configurable: true
  37437. });
  37438. /**
  37439. * Method called each time the image processing information changes requires to recompile the effect.
  37440. */
  37441. ImageProcessingConfiguration.prototype._updateParameters = function () {
  37442. this.onUpdateParameters.notifyObservers(this);
  37443. };
  37444. ImageProcessingConfiguration.prototype.getClassName = function () {
  37445. return "ImageProcessingConfiguration";
  37446. };
  37447. /**
  37448. * Prepare the list of uniforms associated with the Image Processing effects.
  37449. * @param uniformsList The list of uniforms used in the effect
  37450. * @param defines the list of defines currently in use
  37451. */
  37452. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  37453. if (defines.EXPOSURE) {
  37454. uniforms.push("exposureLinear");
  37455. }
  37456. if (defines.CONTRAST) {
  37457. uniforms.push("contrast");
  37458. }
  37459. if (defines.COLORGRADING) {
  37460. uniforms.push("colorTransformSettings");
  37461. }
  37462. if (defines.VIGNETTE) {
  37463. uniforms.push("vInverseScreenSize");
  37464. uniforms.push("vignetteSettings1");
  37465. uniforms.push("vignetteSettings2");
  37466. }
  37467. if (defines.COLORCURVES) {
  37468. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  37469. }
  37470. if (defines.GRAIN) {
  37471. uniforms.push("grainVarianceAmount");
  37472. uniforms.push("grainAnimatedSeed");
  37473. }
  37474. };
  37475. /**
  37476. * Prepare the list of samplers associated with the Image Processing effects.
  37477. * @param uniformsList The list of uniforms used in the effect
  37478. * @param defines the list of defines currently in use
  37479. */
  37480. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  37481. if (defines.COLORGRADING) {
  37482. samplersList.push("txColorTransform");
  37483. }
  37484. };
  37485. /**
  37486. * Prepare the list of defines associated to the shader.
  37487. * @param defines the list of defines to complete
  37488. */
  37489. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  37490. if (forPostProcess === void 0) { forPostProcess = false; }
  37491. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  37492. defines.VIGNETTE = false;
  37493. defines.TONEMAPPING = false;
  37494. defines.CONTRAST = false;
  37495. defines.EXPOSURE = false;
  37496. defines.COLORCURVES = false;
  37497. defines.COLORGRADING = false;
  37498. defines.COLORGRADING3D = false;
  37499. defines.IMAGEPROCESSING = false;
  37500. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  37501. return;
  37502. }
  37503. defines.VIGNETTE = this.vignetteEnabled;
  37504. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  37505. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  37506. defines.TONEMAPPING = this.toneMappingEnabled;
  37507. defines.CONTRAST = (this.contrast !== 1.0);
  37508. defines.EXPOSURE = (this.exposure !== 1.0);
  37509. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  37510. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  37511. if (defines.COLORGRADING) {
  37512. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  37513. }
  37514. else {
  37515. defines.COLORGRADING3D = false;
  37516. }
  37517. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  37518. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  37519. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  37520. defines.GRAIN = this.grainEnabled;
  37521. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING || defines.GRAIN;
  37522. };
  37523. /**
  37524. * Returns true if all the image processing information are ready.
  37525. */
  37526. ImageProcessingConfiguration.prototype.isReady = function () {
  37527. // Color Grading texure can not be none blocking.
  37528. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  37529. };
  37530. /**
  37531. * Binds the image processing to the shader.
  37532. * @param effect The effect to bind to
  37533. */
  37534. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  37535. if (aspectRatio === void 0) { aspectRatio = 1; }
  37536. // Color Curves
  37537. if (this._colorCurvesEnabled && this.colorCurves) {
  37538. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  37539. }
  37540. // Vignette
  37541. if (this._vignetteEnabled) {
  37542. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  37543. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  37544. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  37545. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  37546. var vignetteScaleX = vignetteScaleY * aspectRatio;
  37547. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  37548. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  37549. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  37550. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  37551. var vignettePower = -2.0 * this.vignetteWeight;
  37552. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  37553. }
  37554. // Exposure
  37555. effect.setFloat("exposureLinear", this.exposure);
  37556. // Contrast
  37557. effect.setFloat("contrast", this.contrast);
  37558. // Color transform settings
  37559. if (this.colorGradingTexture) {
  37560. effect.setTexture("txColorTransform", this.colorGradingTexture);
  37561. var textureSize = this.colorGradingTexture.getSize().height;
  37562. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  37563. 0.5 / textureSize, // textureOffset
  37564. textureSize, // textureSize
  37565. this.colorGradingTexture.level // weight
  37566. );
  37567. }
  37568. effect.setFloat("grainVarianceAmount", this.grainIntensity);
  37569. effect.setFloat("grainAnimatedSeed", this.grainAnimated ? Math.random() + 1 : 1);
  37570. };
  37571. /**
  37572. * Clones the current image processing instance.
  37573. * @return The cloned image processing
  37574. */
  37575. ImageProcessingConfiguration.prototype.clone = function () {
  37576. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  37577. };
  37578. /**
  37579. * Serializes the current image processing instance to a json representation.
  37580. * @return a JSON representation
  37581. */
  37582. ImageProcessingConfiguration.prototype.serialize = function () {
  37583. return BABYLON.SerializationHelper.Serialize(this);
  37584. };
  37585. /**
  37586. * Parses the image processing from a json representation.
  37587. * @param source the JSON source to parse
  37588. * @return The parsed image processing
  37589. */
  37590. ImageProcessingConfiguration.Parse = function (source) {
  37591. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  37592. };
  37593. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  37594. /**
  37595. * Used to apply the vignette as a mix with the pixel color.
  37596. */
  37597. get: function () {
  37598. return this._VIGNETTEMODE_MULTIPLY;
  37599. },
  37600. enumerable: true,
  37601. configurable: true
  37602. });
  37603. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  37604. /**
  37605. * Used to apply the vignette as a replacement of the pixel color.
  37606. */
  37607. get: function () {
  37608. return this._VIGNETTEMODE_OPAQUE;
  37609. },
  37610. enumerable: true,
  37611. configurable: true
  37612. });
  37613. // Static constants associated to the image processing.
  37614. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  37615. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  37616. __decorate([
  37617. BABYLON.serializeAsColorCurves()
  37618. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  37619. __decorate([
  37620. BABYLON.serialize()
  37621. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  37622. __decorate([
  37623. BABYLON.serializeAsTexture()
  37624. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  37625. __decorate([
  37626. BABYLON.serialize()
  37627. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  37628. __decorate([
  37629. BABYLON.serialize()
  37630. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  37631. __decorate([
  37632. BABYLON.serialize()
  37633. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  37634. __decorate([
  37635. BABYLON.serialize()
  37636. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  37637. __decorate([
  37638. BABYLON.serialize()
  37639. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  37640. __decorate([
  37641. BABYLON.serialize()
  37642. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  37643. __decorate([
  37644. BABYLON.serialize()
  37645. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  37646. __decorate([
  37647. BABYLON.serialize()
  37648. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  37649. __decorate([
  37650. BABYLON.serialize()
  37651. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  37652. __decorate([
  37653. BABYLON.serialize()
  37654. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  37655. __decorate([
  37656. BABYLON.serializeAsColor4()
  37657. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  37658. __decorate([
  37659. BABYLON.serialize()
  37660. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  37661. __decorate([
  37662. BABYLON.serialize()
  37663. ], ImageProcessingConfiguration.prototype, "_grainEnabled", void 0);
  37664. __decorate([
  37665. BABYLON.serialize()
  37666. ], ImageProcessingConfiguration.prototype, "_grainIntensity", void 0);
  37667. __decorate([
  37668. BABYLON.serialize()
  37669. ], ImageProcessingConfiguration.prototype, "_grainAnimated", void 0);
  37670. __decorate([
  37671. BABYLON.serialize()
  37672. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  37673. __decorate([
  37674. BABYLON.serialize()
  37675. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  37676. __decorate([
  37677. BABYLON.serialize()
  37678. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  37679. __decorate([
  37680. BABYLON.serialize()
  37681. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  37682. return ImageProcessingConfiguration;
  37683. }());
  37684. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  37685. })(BABYLON || (BABYLON = {}));
  37686. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  37687. var BABYLON;
  37688. (function (BABYLON) {
  37689. /**
  37690. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  37691. * It can help converting any input color in a desired output one. This can then be used to create effects
  37692. * from sepia, black and white to sixties or futuristic rendering...
  37693. *
  37694. * The only supported format is currently 3dl.
  37695. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  37696. */
  37697. var ColorGradingTexture = /** @class */ (function (_super) {
  37698. __extends(ColorGradingTexture, _super);
  37699. /**
  37700. * Instantiates a ColorGradingTexture from the following parameters.
  37701. *
  37702. * @param url The location of the color gradind data (currently only supporting 3dl)
  37703. * @param scene The scene the texture will be used in
  37704. */
  37705. function ColorGradingTexture(url, scene) {
  37706. var _this = _super.call(this, scene) || this;
  37707. if (!url) {
  37708. return _this;
  37709. }
  37710. _this._engine = scene.getEngine();
  37711. _this._textureMatrix = BABYLON.Matrix.Identity();
  37712. _this.name = url;
  37713. _this.url = url;
  37714. _this.hasAlpha = false;
  37715. _this.isCube = false;
  37716. _this.is3D = _this._engine.webGLVersion > 1;
  37717. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  37718. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  37719. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  37720. _this.anisotropicFilteringLevel = 1;
  37721. _this._texture = _this._getFromCache(url, true);
  37722. if (!_this._texture) {
  37723. if (!scene.useDelayedTextureLoading) {
  37724. _this.loadTexture();
  37725. }
  37726. else {
  37727. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  37728. }
  37729. }
  37730. return _this;
  37731. }
  37732. /**
  37733. * Returns the texture matrix used in most of the material.
  37734. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  37735. */
  37736. ColorGradingTexture.prototype.getTextureMatrix = function () {
  37737. return this._textureMatrix;
  37738. };
  37739. /**
  37740. * Occurs when the file being loaded is a .3dl LUT file.
  37741. */
  37742. ColorGradingTexture.prototype.load3dlTexture = function () {
  37743. var engine = this._engine;
  37744. var texture;
  37745. if (engine.webGLVersion === 1) {
  37746. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  37747. }
  37748. else {
  37749. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  37750. }
  37751. this._texture = texture;
  37752. var callback = function (text) {
  37753. if (typeof text !== "string") {
  37754. return;
  37755. }
  37756. var data = null;
  37757. var tempData = null;
  37758. var line;
  37759. var lines = text.split('\n');
  37760. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  37761. var maxColor = 0;
  37762. for (var i = 0; i < lines.length; i++) {
  37763. line = lines[i];
  37764. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  37765. continue;
  37766. if (line.indexOf('#') === 0)
  37767. continue;
  37768. var words = line.split(" ");
  37769. if (size === 0) {
  37770. // Number of space + one
  37771. size = words.length;
  37772. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  37773. tempData = new Float32Array(size * size * size * 4);
  37774. continue;
  37775. }
  37776. if (size != 0) {
  37777. var r = Math.max(parseInt(words[0]), 0);
  37778. var g = Math.max(parseInt(words[1]), 0);
  37779. var b = Math.max(parseInt(words[2]), 0);
  37780. maxColor = Math.max(r, maxColor);
  37781. maxColor = Math.max(g, maxColor);
  37782. maxColor = Math.max(b, maxColor);
  37783. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  37784. if (tempData) {
  37785. tempData[pixelStorageIndex + 0] = r;
  37786. tempData[pixelStorageIndex + 1] = g;
  37787. tempData[pixelStorageIndex + 2] = b;
  37788. }
  37789. pixelIndexSlice++;
  37790. if (pixelIndexSlice % size == 0) {
  37791. pixelIndexH++;
  37792. pixelIndexSlice = 0;
  37793. if (pixelIndexH % size == 0) {
  37794. pixelIndexW++;
  37795. pixelIndexH = 0;
  37796. }
  37797. }
  37798. }
  37799. }
  37800. if (tempData && data) {
  37801. for (var i = 0; i < tempData.length; i++) {
  37802. if (i > 0 && (i + 1) % 4 === 0) {
  37803. data[i] = 255;
  37804. }
  37805. else {
  37806. var value = tempData[i];
  37807. data[i] = (value / maxColor * 255);
  37808. }
  37809. }
  37810. }
  37811. if (texture.is3D) {
  37812. texture.updateSize(size, size, size);
  37813. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  37814. }
  37815. else {
  37816. texture.updateSize(size * size, size);
  37817. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  37818. }
  37819. };
  37820. var scene = this.getScene();
  37821. if (scene) {
  37822. scene._loadFile(this.url, callback);
  37823. }
  37824. else {
  37825. this._engine._loadFile(this.url, callback);
  37826. }
  37827. return this._texture;
  37828. };
  37829. /**
  37830. * Starts the loading process of the texture.
  37831. */
  37832. ColorGradingTexture.prototype.loadTexture = function () {
  37833. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  37834. this.load3dlTexture();
  37835. }
  37836. };
  37837. /**
  37838. * Clones the color gradind texture.
  37839. */
  37840. ColorGradingTexture.prototype.clone = function () {
  37841. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  37842. // Base texture
  37843. newTexture.level = this.level;
  37844. return newTexture;
  37845. };
  37846. /**
  37847. * Called during delayed load for textures.
  37848. */
  37849. ColorGradingTexture.prototype.delayLoad = function () {
  37850. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  37851. return;
  37852. }
  37853. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  37854. this._texture = this._getFromCache(this.url, true);
  37855. if (!this._texture) {
  37856. this.loadTexture();
  37857. }
  37858. };
  37859. /**
  37860. * Parses a color grading texture serialized by Babylon.
  37861. * @param parsedTexture The texture information being parsedTexture
  37862. * @param scene The scene to load the texture in
  37863. * @param rootUrl The root url of the data assets to load
  37864. * @return A color gradind texture
  37865. */
  37866. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  37867. var texture = null;
  37868. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  37869. texture = new ColorGradingTexture(parsedTexture.name, scene);
  37870. texture.name = parsedTexture.name;
  37871. texture.level = parsedTexture.level;
  37872. }
  37873. return texture;
  37874. };
  37875. /**
  37876. * Serializes the LUT texture to json format.
  37877. */
  37878. ColorGradingTexture.prototype.serialize = function () {
  37879. if (!this.name) {
  37880. return null;
  37881. }
  37882. var serializationObject = {};
  37883. serializationObject.name = this.name;
  37884. serializationObject.level = this.level;
  37885. serializationObject.customType = "BABYLON.ColorGradingTexture";
  37886. return serializationObject;
  37887. };
  37888. /**
  37889. * Empty line regex stored for GC.
  37890. */
  37891. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  37892. return ColorGradingTexture;
  37893. }(BABYLON.BaseTexture));
  37894. BABYLON.ColorGradingTexture = ColorGradingTexture;
  37895. })(BABYLON || (BABYLON = {}));
  37896. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  37897. var BABYLON;
  37898. (function (BABYLON) {
  37899. /**
  37900. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  37901. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  37902. * 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;
  37903. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  37904. */
  37905. var ColorCurves = /** @class */ (function () {
  37906. function ColorCurves() {
  37907. this._dirty = true;
  37908. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  37909. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  37910. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  37911. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  37912. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  37913. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  37914. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  37915. this._globalHue = 30;
  37916. this._globalDensity = 0;
  37917. this._globalSaturation = 0;
  37918. this._globalExposure = 0;
  37919. this._highlightsHue = 30;
  37920. this._highlightsDensity = 0;
  37921. this._highlightsSaturation = 0;
  37922. this._highlightsExposure = 0;
  37923. this._midtonesHue = 30;
  37924. this._midtonesDensity = 0;
  37925. this._midtonesSaturation = 0;
  37926. this._midtonesExposure = 0;
  37927. this._shadowsHue = 30;
  37928. this._shadowsDensity = 0;
  37929. this._shadowsSaturation = 0;
  37930. this._shadowsExposure = 0;
  37931. }
  37932. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  37933. /**
  37934. * Gets the global Hue value.
  37935. * 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).
  37936. */
  37937. get: function () {
  37938. return this._globalHue;
  37939. },
  37940. /**
  37941. * Sets the global Hue value.
  37942. * 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).
  37943. */
  37944. set: function (value) {
  37945. this._globalHue = value;
  37946. this._dirty = true;
  37947. },
  37948. enumerable: true,
  37949. configurable: true
  37950. });
  37951. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  37952. /**
  37953. * Gets the global Density value.
  37954. * 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.
  37955. * Values less than zero provide a filter of opposite hue.
  37956. */
  37957. get: function () {
  37958. return this._globalDensity;
  37959. },
  37960. /**
  37961. * Sets the global Density value.
  37962. * 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.
  37963. * Values less than zero provide a filter of opposite hue.
  37964. */
  37965. set: function (value) {
  37966. this._globalDensity = value;
  37967. this._dirty = true;
  37968. },
  37969. enumerable: true,
  37970. configurable: true
  37971. });
  37972. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  37973. /**
  37974. * Gets the global Saturation value.
  37975. * 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.
  37976. */
  37977. get: function () {
  37978. return this._globalSaturation;
  37979. },
  37980. /**
  37981. * Sets the global Saturation value.
  37982. * 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.
  37983. */
  37984. set: function (value) {
  37985. this._globalSaturation = value;
  37986. this._dirty = true;
  37987. },
  37988. enumerable: true,
  37989. configurable: true
  37990. });
  37991. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  37992. /**
  37993. * Gets the highlights Hue value.
  37994. * 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).
  37995. */
  37996. get: function () {
  37997. return this._highlightsHue;
  37998. },
  37999. /**
  38000. * Sets the highlights Hue value.
  38001. * 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).
  38002. */
  38003. set: function (value) {
  38004. this._highlightsHue = value;
  38005. this._dirty = true;
  38006. },
  38007. enumerable: true,
  38008. configurable: true
  38009. });
  38010. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  38011. /**
  38012. * Gets the highlights Density value.
  38013. * 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.
  38014. * Values less than zero provide a filter of opposite hue.
  38015. */
  38016. get: function () {
  38017. return this._highlightsDensity;
  38018. },
  38019. /**
  38020. * Sets the highlights Density value.
  38021. * 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.
  38022. * Values less than zero provide a filter of opposite hue.
  38023. */
  38024. set: function (value) {
  38025. this._highlightsDensity = value;
  38026. this._dirty = true;
  38027. },
  38028. enumerable: true,
  38029. configurable: true
  38030. });
  38031. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  38032. /**
  38033. * Gets the highlights Saturation value.
  38034. * 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.
  38035. */
  38036. get: function () {
  38037. return this._highlightsSaturation;
  38038. },
  38039. /**
  38040. * Sets the highlights Saturation value.
  38041. * 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.
  38042. */
  38043. set: function (value) {
  38044. this._highlightsSaturation = value;
  38045. this._dirty = true;
  38046. },
  38047. enumerable: true,
  38048. configurable: true
  38049. });
  38050. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  38051. /**
  38052. * Gets the highlights Exposure value.
  38053. * 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.
  38054. */
  38055. get: function () {
  38056. return this._highlightsExposure;
  38057. },
  38058. /**
  38059. * Sets the highlights Exposure value.
  38060. * 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.
  38061. */
  38062. set: function (value) {
  38063. this._highlightsExposure = value;
  38064. this._dirty = true;
  38065. },
  38066. enumerable: true,
  38067. configurable: true
  38068. });
  38069. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  38070. /**
  38071. * Gets the midtones Hue value.
  38072. * 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).
  38073. */
  38074. get: function () {
  38075. return this._midtonesHue;
  38076. },
  38077. /**
  38078. * Sets the midtones Hue value.
  38079. * 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).
  38080. */
  38081. set: function (value) {
  38082. this._midtonesHue = value;
  38083. this._dirty = true;
  38084. },
  38085. enumerable: true,
  38086. configurable: true
  38087. });
  38088. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  38089. /**
  38090. * Gets the midtones Density value.
  38091. * 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.
  38092. * Values less than zero provide a filter of opposite hue.
  38093. */
  38094. get: function () {
  38095. return this._midtonesDensity;
  38096. },
  38097. /**
  38098. * Sets the midtones Density value.
  38099. * 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.
  38100. * Values less than zero provide a filter of opposite hue.
  38101. */
  38102. set: function (value) {
  38103. this._midtonesDensity = value;
  38104. this._dirty = true;
  38105. },
  38106. enumerable: true,
  38107. configurable: true
  38108. });
  38109. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  38110. /**
  38111. * Gets the midtones Saturation value.
  38112. * 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.
  38113. */
  38114. get: function () {
  38115. return this._midtonesSaturation;
  38116. },
  38117. /**
  38118. * Sets the midtones Saturation value.
  38119. * 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.
  38120. */
  38121. set: function (value) {
  38122. this._midtonesSaturation = value;
  38123. this._dirty = true;
  38124. },
  38125. enumerable: true,
  38126. configurable: true
  38127. });
  38128. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  38129. /**
  38130. * Gets the midtones Exposure value.
  38131. * 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.
  38132. */
  38133. get: function () {
  38134. return this._midtonesExposure;
  38135. },
  38136. /**
  38137. * Sets the midtones Exposure value.
  38138. * 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.
  38139. */
  38140. set: function (value) {
  38141. this._midtonesExposure = value;
  38142. this._dirty = true;
  38143. },
  38144. enumerable: true,
  38145. configurable: true
  38146. });
  38147. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  38148. /**
  38149. * Gets the shadows Hue value.
  38150. * 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).
  38151. */
  38152. get: function () {
  38153. return this._shadowsHue;
  38154. },
  38155. /**
  38156. * Sets the shadows Hue value.
  38157. * 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).
  38158. */
  38159. set: function (value) {
  38160. this._shadowsHue = value;
  38161. this._dirty = true;
  38162. },
  38163. enumerable: true,
  38164. configurable: true
  38165. });
  38166. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  38167. /**
  38168. * Gets the shadows Density value.
  38169. * 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.
  38170. * Values less than zero provide a filter of opposite hue.
  38171. */
  38172. get: function () {
  38173. return this._shadowsDensity;
  38174. },
  38175. /**
  38176. * Sets the shadows Density value.
  38177. * 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.
  38178. * Values less than zero provide a filter of opposite hue.
  38179. */
  38180. set: function (value) {
  38181. this._shadowsDensity = value;
  38182. this._dirty = true;
  38183. },
  38184. enumerable: true,
  38185. configurable: true
  38186. });
  38187. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  38188. /**
  38189. * Gets the shadows Saturation value.
  38190. * 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.
  38191. */
  38192. get: function () {
  38193. return this._shadowsSaturation;
  38194. },
  38195. /**
  38196. * Sets the shadows Saturation value.
  38197. * 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.
  38198. */
  38199. set: function (value) {
  38200. this._shadowsSaturation = value;
  38201. this._dirty = true;
  38202. },
  38203. enumerable: true,
  38204. configurable: true
  38205. });
  38206. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  38207. /**
  38208. * Gets the shadows Exposure value.
  38209. * 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.
  38210. */
  38211. get: function () {
  38212. return this._shadowsExposure;
  38213. },
  38214. /**
  38215. * Sets the shadows Exposure value.
  38216. * 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.
  38217. */
  38218. set: function (value) {
  38219. this._shadowsExposure = value;
  38220. this._dirty = true;
  38221. },
  38222. enumerable: true,
  38223. configurable: true
  38224. });
  38225. ColorCurves.prototype.getClassName = function () {
  38226. return "ColorCurves";
  38227. };
  38228. /**
  38229. * Binds the color curves to the shader.
  38230. * @param colorCurves The color curve to bind
  38231. * @param effect The effect to bind to
  38232. */
  38233. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  38234. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  38235. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  38236. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  38237. if (colorCurves._dirty) {
  38238. colorCurves._dirty = false;
  38239. // Fill in global info.
  38240. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  38241. // Compute highlights info.
  38242. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  38243. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  38244. // Compute midtones info.
  38245. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  38246. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  38247. // Compute shadows info.
  38248. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  38249. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  38250. // Compute deltas (neutral is midtones).
  38251. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  38252. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  38253. }
  38254. if (effect) {
  38255. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  38256. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  38257. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  38258. }
  38259. };
  38260. /**
  38261. * Prepare the list of uniforms associated with the ColorCurves effects.
  38262. * @param uniformsList The list of uniforms used in the effect
  38263. */
  38264. ColorCurves.PrepareUniforms = function (uniformsList) {
  38265. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  38266. };
  38267. /**
  38268. * Returns color grading data based on a hue, density, saturation and exposure value.
  38269. * @param filterHue The hue of the color filter.
  38270. * @param filterDensity The density of the color filter.
  38271. * @param saturation The saturation.
  38272. * @param exposure The exposure.
  38273. * @param result The result data container.
  38274. */
  38275. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  38276. if (hue == null) {
  38277. return;
  38278. }
  38279. hue = ColorCurves.clamp(hue, 0, 360);
  38280. density = ColorCurves.clamp(density, -100, 100);
  38281. saturation = ColorCurves.clamp(saturation, -100, 100);
  38282. exposure = ColorCurves.clamp(exposure, -100, 100);
  38283. // Remap the slider/config filter density with non-linear mapping and also scale by half
  38284. // so that the maximum filter density is only 50% control. This provides fine control
  38285. // for small values and reasonable range.
  38286. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  38287. density *= 0.5;
  38288. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  38289. if (density < 0) {
  38290. density *= -1;
  38291. hue = (hue + 180) % 360;
  38292. }
  38293. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  38294. result.scaleToRef(2, result);
  38295. result.a = 1 + 0.01 * saturation;
  38296. };
  38297. /**
  38298. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  38299. * @param value The input slider value in range [-100,100].
  38300. * @returns Adjusted value.
  38301. */
  38302. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  38303. value /= 100;
  38304. var x = Math.abs(value);
  38305. x = Math.pow(x, 2);
  38306. if (value < 0) {
  38307. x *= -1;
  38308. }
  38309. x *= 100;
  38310. return x;
  38311. };
  38312. /**
  38313. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  38314. * @param hue The hue (H) input.
  38315. * @param saturation The saturation (S) input.
  38316. * @param brightness The brightness (B) input.
  38317. * @result An RGBA color represented as Vector4.
  38318. */
  38319. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  38320. var h = ColorCurves.clamp(hue, 0, 360);
  38321. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  38322. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  38323. if (s === 0) {
  38324. result.r = v;
  38325. result.g = v;
  38326. result.b = v;
  38327. }
  38328. else {
  38329. // sector 0 to 5
  38330. h /= 60;
  38331. var i = Math.floor(h);
  38332. // fractional part of h
  38333. var f = h - i;
  38334. var p = v * (1 - s);
  38335. var q = v * (1 - s * f);
  38336. var t = v * (1 - s * (1 - f));
  38337. switch (i) {
  38338. case 0:
  38339. result.r = v;
  38340. result.g = t;
  38341. result.b = p;
  38342. break;
  38343. case 1:
  38344. result.r = q;
  38345. result.g = v;
  38346. result.b = p;
  38347. break;
  38348. case 2:
  38349. result.r = p;
  38350. result.g = v;
  38351. result.b = t;
  38352. break;
  38353. case 3:
  38354. result.r = p;
  38355. result.g = q;
  38356. result.b = v;
  38357. break;
  38358. case 4:
  38359. result.r = t;
  38360. result.g = p;
  38361. result.b = v;
  38362. break;
  38363. default:// case 5:
  38364. result.r = v;
  38365. result.g = p;
  38366. result.b = q;
  38367. break;
  38368. }
  38369. }
  38370. result.a = 1;
  38371. };
  38372. /**
  38373. * Returns a value clamped between min and max
  38374. * @param value The value to clamp
  38375. * @param min The minimum of value
  38376. * @param max The maximum of value
  38377. * @returns The clamped value.
  38378. */
  38379. ColorCurves.clamp = function (value, min, max) {
  38380. return Math.min(Math.max(value, min), max);
  38381. };
  38382. /**
  38383. * Clones the current color curve instance.
  38384. * @return The cloned curves
  38385. */
  38386. ColorCurves.prototype.clone = function () {
  38387. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  38388. };
  38389. /**
  38390. * Serializes the current color curve instance to a json representation.
  38391. * @return a JSON representation
  38392. */
  38393. ColorCurves.prototype.serialize = function () {
  38394. return BABYLON.SerializationHelper.Serialize(this);
  38395. };
  38396. /**
  38397. * Parses the color curve from a json representation.
  38398. * @param source the JSON source to parse
  38399. * @return The parsed curves
  38400. */
  38401. ColorCurves.Parse = function (source) {
  38402. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  38403. };
  38404. __decorate([
  38405. BABYLON.serialize()
  38406. ], ColorCurves.prototype, "_globalHue", void 0);
  38407. __decorate([
  38408. BABYLON.serialize()
  38409. ], ColorCurves.prototype, "_globalDensity", void 0);
  38410. __decorate([
  38411. BABYLON.serialize()
  38412. ], ColorCurves.prototype, "_globalSaturation", void 0);
  38413. __decorate([
  38414. BABYLON.serialize()
  38415. ], ColorCurves.prototype, "_globalExposure", void 0);
  38416. __decorate([
  38417. BABYLON.serialize()
  38418. ], ColorCurves.prototype, "_highlightsHue", void 0);
  38419. __decorate([
  38420. BABYLON.serialize()
  38421. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  38422. __decorate([
  38423. BABYLON.serialize()
  38424. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  38425. __decorate([
  38426. BABYLON.serialize()
  38427. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  38428. __decorate([
  38429. BABYLON.serialize()
  38430. ], ColorCurves.prototype, "_midtonesHue", void 0);
  38431. __decorate([
  38432. BABYLON.serialize()
  38433. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  38434. __decorate([
  38435. BABYLON.serialize()
  38436. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  38437. __decorate([
  38438. BABYLON.serialize()
  38439. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  38440. return ColorCurves;
  38441. }());
  38442. BABYLON.ColorCurves = ColorCurves;
  38443. })(BABYLON || (BABYLON = {}));
  38444. //# sourceMappingURL=babylon.colorCurves.js.map
  38445. //# sourceMappingURL=babylon.behavior.js.map
  38446. var BABYLON;
  38447. (function (BABYLON) {
  38448. /**
  38449. * "Static Class" containing the most commonly used helper while dealing with material for
  38450. * rendering purpose.
  38451. *
  38452. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  38453. *
  38454. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  38455. */
  38456. var MaterialHelper = /** @class */ (function () {
  38457. function MaterialHelper() {
  38458. }
  38459. /**
  38460. * Bind the current view position to an effect.
  38461. * @param effect The effect to be bound
  38462. * @param scene The scene the eyes position is used from
  38463. */
  38464. MaterialHelper.BindEyePosition = function (effect, scene) {
  38465. if (scene._forcedViewPosition) {
  38466. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  38467. return;
  38468. }
  38469. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  38470. };
  38471. /**
  38472. * Helps preparing the defines values about the UVs in used in the effect.
  38473. * UVs are shared as much as we can accross chanels in the shaders.
  38474. * @param texture The texture we are preparing the UVs for
  38475. * @param defines The defines to update
  38476. * @param key The chanel key "diffuse", "specular"... used in the shader
  38477. */
  38478. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  38479. defines._needUVs = true;
  38480. defines[key] = true;
  38481. if (texture.getTextureMatrix().isIdentity(true)) {
  38482. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  38483. if (texture.coordinatesIndex === 0) {
  38484. defines["MAINUV1"] = true;
  38485. }
  38486. else {
  38487. defines["MAINUV2"] = true;
  38488. }
  38489. }
  38490. else {
  38491. defines[key + "DIRECTUV"] = 0;
  38492. }
  38493. };
  38494. /**
  38495. * Binds a texture matrix value to its corrsponding uniform
  38496. * @param texture The texture to bind the matrix for
  38497. * @param uniformBuffer The uniform buffer receivin the data
  38498. * @param key The chanel key "diffuse", "specular"... used in the shader
  38499. */
  38500. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  38501. var matrix = texture.getTextureMatrix();
  38502. if (!matrix.isIdentity(true)) {
  38503. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  38504. }
  38505. };
  38506. /**
  38507. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  38508. * @param mesh defines the current mesh
  38509. * @param scene defines the current scene
  38510. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  38511. * @param pointsCloud defines if point cloud rendering has to be turned on
  38512. * @param fogEnabled defines if fog has to be turned on
  38513. * @param alphaTest defines if alpha testing has to be turned on
  38514. * @param defines defines the current list of defines
  38515. */
  38516. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  38517. if (defines._areMiscDirty) {
  38518. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  38519. defines["POINTSIZE"] = (pointsCloud || scene.forcePointsCloud);
  38520. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  38521. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  38522. defines["ALPHATEST"] = alphaTest;
  38523. }
  38524. };
  38525. /**
  38526. * Helper used to prepare the list of defines associated with frame values for shader compilation
  38527. * @param scene defines the current scene
  38528. * @param engine defines the current engine
  38529. * @param defines specifies the list of active defines
  38530. * @param useInstances defines if instances have to be turned on
  38531. * @param useClipPlane defines if clip plane have to be turned on
  38532. */
  38533. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) {
  38534. if (useClipPlane === void 0) { useClipPlane = null; }
  38535. var changed = false;
  38536. if (useClipPlane == null) {
  38537. useClipPlane = (scene.clipPlane !== undefined && scene.clipPlane !== null);
  38538. }
  38539. if (defines["CLIPPLANE"] !== useClipPlane) {
  38540. defines["CLIPPLANE"] = useClipPlane;
  38541. changed = true;
  38542. }
  38543. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  38544. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  38545. changed = true;
  38546. }
  38547. if (defines["INSTANCES"] !== useInstances) {
  38548. defines["INSTANCES"] = useInstances;
  38549. changed = true;
  38550. }
  38551. if (changed) {
  38552. defines.markAsUnprocessed();
  38553. }
  38554. };
  38555. /**
  38556. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  38557. * @param mesh The mesh containing the geometry data we will draw
  38558. * @param defines The defines to update
  38559. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  38560. * @param useBones Precise whether bones should be used or not (override mesh info)
  38561. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  38562. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  38563. * @returns false if defines are considered not dirty and have not been checked
  38564. */
  38565. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  38566. if (useMorphTargets === void 0) { useMorphTargets = false; }
  38567. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  38568. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  38569. return false;
  38570. }
  38571. defines._normals = defines._needNormals;
  38572. defines._uvs = defines._needUVs;
  38573. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  38574. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  38575. defines["TANGENT"] = true;
  38576. }
  38577. if (defines._needUVs) {
  38578. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  38579. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  38580. }
  38581. else {
  38582. defines["UV1"] = false;
  38583. defines["UV2"] = false;
  38584. }
  38585. if (useVertexColor) {
  38586. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  38587. defines["VERTEXCOLOR"] = hasVertexColors;
  38588. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  38589. }
  38590. if (useBones) {
  38591. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  38592. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  38593. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  38594. }
  38595. else {
  38596. defines["NUM_BONE_INFLUENCERS"] = 0;
  38597. defines["BonesPerMesh"] = 0;
  38598. }
  38599. }
  38600. if (useMorphTargets) {
  38601. var manager = mesh.morphTargetManager;
  38602. if (manager) {
  38603. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  38604. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  38605. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  38606. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  38607. }
  38608. else {
  38609. defines["MORPHTARGETS_TANGENT"] = false;
  38610. defines["MORPHTARGETS_NORMAL"] = false;
  38611. defines["MORPHTARGETS"] = false;
  38612. defines["NUM_MORPH_INFLUENCERS"] = 0;
  38613. }
  38614. }
  38615. return true;
  38616. };
  38617. /**
  38618. * Prepares the defines related to the light information passed in parameter
  38619. * @param scene The scene we are intending to draw
  38620. * @param mesh The mesh the effect is compiling for
  38621. * @param defines The defines to update
  38622. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  38623. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  38624. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  38625. * @returns true if normals will be required for the rest of the effect
  38626. */
  38627. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  38628. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  38629. if (disableLighting === void 0) { disableLighting = false; }
  38630. if (!defines._areLightsDirty) {
  38631. return defines._needNormals;
  38632. }
  38633. var lightIndex = 0;
  38634. var needNormals = false;
  38635. var needRebuild = false;
  38636. var lightmapMode = false;
  38637. var shadowEnabled = false;
  38638. var specularEnabled = false;
  38639. if (scene.lightsEnabled && !disableLighting) {
  38640. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  38641. var light = _a[_i];
  38642. needNormals = true;
  38643. if (defines["LIGHT" + lightIndex] === undefined) {
  38644. needRebuild = true;
  38645. }
  38646. defines["LIGHT" + lightIndex] = true;
  38647. defines["SPOTLIGHT" + lightIndex] = false;
  38648. defines["HEMILIGHT" + lightIndex] = false;
  38649. defines["POINTLIGHT" + lightIndex] = false;
  38650. defines["DIRLIGHT" + lightIndex] = false;
  38651. var type;
  38652. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  38653. type = "SPOTLIGHT" + lightIndex;
  38654. var spotLight = light;
  38655. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = spotLight.projectionTexture ? spotLight.projectionTexture.isReady() : false;
  38656. }
  38657. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  38658. type = "HEMILIGHT" + lightIndex;
  38659. }
  38660. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  38661. type = "POINTLIGHT" + lightIndex;
  38662. }
  38663. else {
  38664. type = "DIRLIGHT" + lightIndex;
  38665. }
  38666. defines[type] = true;
  38667. // Specular
  38668. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  38669. specularEnabled = true;
  38670. }
  38671. // Shadows
  38672. defines["SHADOW" + lightIndex] = false;
  38673. defines["SHADOWPCF" + lightIndex] = false;
  38674. defines["SHADOWESM" + lightIndex] = false;
  38675. defines["SHADOWCUBE" + lightIndex] = false;
  38676. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  38677. var shadowGenerator = light.getShadowGenerator();
  38678. if (shadowGenerator) {
  38679. shadowEnabled = true;
  38680. shadowGenerator.prepareDefines(defines, lightIndex);
  38681. }
  38682. }
  38683. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  38684. lightmapMode = true;
  38685. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  38686. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  38687. }
  38688. else {
  38689. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  38690. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  38691. }
  38692. lightIndex++;
  38693. if (lightIndex === maxSimultaneousLights)
  38694. break;
  38695. }
  38696. }
  38697. defines["SPECULARTERM"] = specularEnabled;
  38698. defines["SHADOWS"] = shadowEnabled;
  38699. // Resetting all other lights if any
  38700. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  38701. if (defines["LIGHT" + index] !== undefined) {
  38702. defines["LIGHT" + index] = false;
  38703. defines["HEMILIGHT" + lightIndex] = false;
  38704. defines["POINTLIGHT" + lightIndex] = false;
  38705. defines["DIRLIGHT" + lightIndex] = false;
  38706. defines["SPOTLIGHT" + lightIndex] = false;
  38707. defines["SHADOW" + lightIndex] = false;
  38708. }
  38709. }
  38710. var caps = scene.getEngine().getCaps();
  38711. if (defines["SHADOWFLOAT"] === undefined) {
  38712. needRebuild = true;
  38713. }
  38714. defines["SHADOWFLOAT"] = shadowEnabled &&
  38715. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  38716. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  38717. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  38718. if (needRebuild) {
  38719. defines.rebuild();
  38720. }
  38721. return needNormals;
  38722. };
  38723. /**
  38724. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  38725. * that won t be acctive due to defines being turned off.
  38726. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  38727. * @param samplersList The samplers list
  38728. * @param defines The defines helping in the list generation
  38729. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  38730. */
  38731. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  38732. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  38733. var uniformsList;
  38734. var uniformBuffersList = null;
  38735. if (uniformsListOrOptions.uniformsNames) {
  38736. var options = uniformsListOrOptions;
  38737. uniformsList = options.uniformsNames;
  38738. uniformBuffersList = options.uniformBuffersNames;
  38739. samplersList = options.samplers;
  38740. defines = options.defines;
  38741. maxSimultaneousLights = options.maxSimultaneousLights;
  38742. }
  38743. else {
  38744. uniformsList = uniformsListOrOptions;
  38745. if (!samplersList) {
  38746. samplersList = [];
  38747. }
  38748. }
  38749. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  38750. if (!defines["LIGHT" + lightIndex]) {
  38751. break;
  38752. }
  38753. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  38754. if (uniformBuffersList) {
  38755. uniformBuffersList.push("Light" + lightIndex);
  38756. }
  38757. samplersList.push("shadowSampler" + lightIndex);
  38758. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  38759. samplersList.push("projectionLightSampler" + lightIndex);
  38760. uniformsList.push("textureProjectionMatrix" + lightIndex);
  38761. }
  38762. }
  38763. if (defines["NUM_MORPH_INFLUENCERS"]) {
  38764. uniformsList.push("morphTargetInfluences");
  38765. }
  38766. };
  38767. /**
  38768. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  38769. * @param defines The defines to update while falling back
  38770. * @param fallbacks The authorized effect fallbacks
  38771. * @param maxSimultaneousLights The maximum number of lights allowed
  38772. * @param rank the current rank of the Effect
  38773. * @returns The newly affected rank
  38774. */
  38775. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  38776. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  38777. if (rank === void 0) { rank = 0; }
  38778. var lightFallbackRank = 0;
  38779. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  38780. if (!defines["LIGHT" + lightIndex]) {
  38781. break;
  38782. }
  38783. if (lightIndex > 0) {
  38784. lightFallbackRank = rank + lightIndex;
  38785. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  38786. }
  38787. if (!defines["SHADOWS"]) {
  38788. if (defines["SHADOW" + lightIndex]) {
  38789. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  38790. }
  38791. if (defines["SHADOWPCF" + lightIndex]) {
  38792. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  38793. }
  38794. if (defines["SHADOWESM" + lightIndex]) {
  38795. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  38796. }
  38797. }
  38798. }
  38799. return lightFallbackRank++;
  38800. };
  38801. /**
  38802. * Prepares the list of attributes required for morph targets according to the effect defines.
  38803. * @param attribs The current list of supported attribs
  38804. * @param mesh The mesh to prepare the morph targets attributes for
  38805. * @param defines The current Defines of the effect
  38806. */
  38807. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  38808. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  38809. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  38810. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  38811. var manager = mesh.morphTargetManager;
  38812. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  38813. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  38814. for (var index = 0; index < influencers; index++) {
  38815. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  38816. if (normal) {
  38817. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  38818. }
  38819. if (tangent) {
  38820. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  38821. }
  38822. if (attribs.length > maxAttributesCount) {
  38823. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  38824. }
  38825. }
  38826. }
  38827. };
  38828. /**
  38829. * Prepares the list of attributes required for bones according to the effect defines.
  38830. * @param attribs The current list of supported attribs
  38831. * @param mesh The mesh to prepare the bones attributes for
  38832. * @param defines The current Defines of the effect
  38833. * @param fallbacks The current efffect fallback strategy
  38834. */
  38835. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  38836. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  38837. fallbacks.addCPUSkinningFallback(0, mesh);
  38838. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  38839. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  38840. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  38841. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  38842. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  38843. }
  38844. }
  38845. };
  38846. /**
  38847. * Prepares the list of attributes required for instances according to the effect defines.
  38848. * @param attribs The current list of supported attribs
  38849. * @param defines The current Defines of the effect
  38850. */
  38851. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  38852. if (defines["INSTANCES"]) {
  38853. attribs.push("world0");
  38854. attribs.push("world1");
  38855. attribs.push("world2");
  38856. attribs.push("world3");
  38857. }
  38858. };
  38859. /**
  38860. * Binds the light shadow information to the effect for the given mesh.
  38861. * @param light The light containing the generator
  38862. * @param scene The scene the lights belongs to
  38863. * @param mesh The mesh we are binding the information to render
  38864. * @param lightIndex The light index in the effect used to render the mesh
  38865. * @param effect The effect we are binding the data to
  38866. */
  38867. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  38868. if (light.shadowEnabled && mesh.receiveShadows) {
  38869. var shadowGenerator = light.getShadowGenerator();
  38870. if (shadowGenerator) {
  38871. shadowGenerator.bindShadowLight(lightIndex, effect);
  38872. }
  38873. }
  38874. };
  38875. /**
  38876. * Binds the light information to the effect.
  38877. * @param light The light containing the generator
  38878. * @param effect The effect we are binding the data to
  38879. * @param lightIndex The light index in the effect used to render
  38880. */
  38881. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  38882. light.transferToEffect(effect, lightIndex + "");
  38883. };
  38884. /**
  38885. * Binds the lights information from the scene to the effect for the given mesh.
  38886. * @param scene The scene the lights belongs to
  38887. * @param mesh The mesh we are binding the information to render
  38888. * @param effect The effect we are binding the data to
  38889. * @param defines The generated defines for the effect
  38890. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  38891. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  38892. */
  38893. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  38894. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  38895. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  38896. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  38897. for (var i = 0; i < len; i++) {
  38898. var light = mesh._lightSources[i];
  38899. var iAsString = i.toString();
  38900. var scaledIntensity = light.getScaledIntensity();
  38901. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  38902. MaterialHelper.BindLightProperties(light, effect, i);
  38903. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  38904. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  38905. if (defines["SPECULARTERM"]) {
  38906. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  38907. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  38908. }
  38909. // Shadows
  38910. if (scene.shadowsEnabled) {
  38911. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  38912. }
  38913. light._uniformBuffer.update();
  38914. }
  38915. };
  38916. /**
  38917. * Binds the fog information from the scene to the effect for the given mesh.
  38918. * @param scene The scene the lights belongs to
  38919. * @param mesh The mesh we are binding the information to render
  38920. * @param effect The effect we are binding the data to
  38921. */
  38922. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  38923. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  38924. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  38925. effect.setColor3("vFogColor", scene.fogColor);
  38926. }
  38927. };
  38928. /**
  38929. * Binds the bones information from the mesh to the effect.
  38930. * @param mesh The mesh we are binding the information to render
  38931. * @param effect The effect we are binding the data to
  38932. */
  38933. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  38934. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  38935. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  38936. if (matrices && effect) {
  38937. effect.setMatrices("mBones", matrices);
  38938. }
  38939. }
  38940. };
  38941. /**
  38942. * Binds the morph targets information from the mesh to the effect.
  38943. * @param abstractMesh The mesh we are binding the information to render
  38944. * @param effect The effect we are binding the data to
  38945. */
  38946. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  38947. var manager = abstractMesh.morphTargetManager;
  38948. if (!abstractMesh || !manager) {
  38949. return;
  38950. }
  38951. effect.setFloatArray("morphTargetInfluences", manager.influences);
  38952. };
  38953. /**
  38954. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  38955. * @param defines The generated defines used in the effect
  38956. * @param effect The effect we are binding the data to
  38957. * @param scene The scene we are willing to render with logarithmic scale for
  38958. */
  38959. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  38960. if (defines["LOGARITHMICDEPTH"]) {
  38961. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  38962. }
  38963. };
  38964. /**
  38965. * Binds the clip plane information from the scene to the effect.
  38966. * @param scene The scene the clip plane information are extracted from
  38967. * @param effect The effect we are binding the data to
  38968. */
  38969. MaterialHelper.BindClipPlane = function (effect, scene) {
  38970. if (scene.clipPlane) {
  38971. var clipPlane = scene.clipPlane;
  38972. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  38973. }
  38974. };
  38975. return MaterialHelper;
  38976. }());
  38977. BABYLON.MaterialHelper = MaterialHelper;
  38978. })(BABYLON || (BABYLON = {}));
  38979. //# sourceMappingURL=babylon.materialHelper.js.map
  38980. var BABYLON;
  38981. (function (BABYLON) {
  38982. var PushMaterial = /** @class */ (function (_super) {
  38983. __extends(PushMaterial, _super);
  38984. function PushMaterial(name, scene) {
  38985. var _this = _super.call(this, name, scene) || this;
  38986. _this._normalMatrix = new BABYLON.Matrix();
  38987. _this.storeEffectOnSubMeshes = true;
  38988. return _this;
  38989. }
  38990. PushMaterial.prototype.getEffect = function () {
  38991. return this._activeEffect;
  38992. };
  38993. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  38994. if (!mesh) {
  38995. return false;
  38996. }
  38997. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  38998. return true;
  38999. }
  39000. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  39001. };
  39002. /**
  39003. * Binds the given world matrix to the active effect
  39004. *
  39005. * @param world the matrix to bind
  39006. */
  39007. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  39008. this._activeEffect.setMatrix("world", world);
  39009. };
  39010. /**
  39011. * Binds the given normal matrix to the active effect
  39012. *
  39013. * @param normalMatrix the matrix to bind
  39014. */
  39015. PushMaterial.prototype.bindOnlyNormalMatrix = function (normalMatrix) {
  39016. this._activeEffect.setMatrix("normalMatrix", normalMatrix);
  39017. };
  39018. PushMaterial.prototype.bind = function (world, mesh) {
  39019. if (!mesh) {
  39020. return;
  39021. }
  39022. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  39023. };
  39024. PushMaterial.prototype._afterBind = function (mesh, effect) {
  39025. if (effect === void 0) { effect = null; }
  39026. _super.prototype._afterBind.call(this, mesh);
  39027. this.getScene()._cachedEffect = effect;
  39028. };
  39029. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  39030. if (visibility === void 0) { visibility = 1; }
  39031. return scene.isCachedMaterialInvalid(this, effect, visibility);
  39032. };
  39033. return PushMaterial;
  39034. }(BABYLON.Material));
  39035. BABYLON.PushMaterial = PushMaterial;
  39036. })(BABYLON || (BABYLON = {}));
  39037. //# sourceMappingURL=babylon.pushMaterial.js.map
  39038. var BABYLON;
  39039. (function (BABYLON) {
  39040. /** @ignore */
  39041. var StandardMaterialDefines = /** @class */ (function (_super) {
  39042. __extends(StandardMaterialDefines, _super);
  39043. function StandardMaterialDefines() {
  39044. var _this = _super.call(this) || this;
  39045. _this.MAINUV1 = false;
  39046. _this.MAINUV2 = false;
  39047. _this.DIFFUSE = false;
  39048. _this.DIFFUSEDIRECTUV = 0;
  39049. _this.AMBIENT = false;
  39050. _this.AMBIENTDIRECTUV = 0;
  39051. _this.OPACITY = false;
  39052. _this.OPACITYDIRECTUV = 0;
  39053. _this.OPACITYRGB = false;
  39054. _this.REFLECTION = false;
  39055. _this.EMISSIVE = false;
  39056. _this.EMISSIVEDIRECTUV = 0;
  39057. _this.SPECULAR = false;
  39058. _this.SPECULARDIRECTUV = 0;
  39059. _this.BUMP = false;
  39060. _this.BUMPDIRECTUV = 0;
  39061. _this.PARALLAX = false;
  39062. _this.PARALLAXOCCLUSION = false;
  39063. _this.SPECULAROVERALPHA = false;
  39064. _this.CLIPPLANE = false;
  39065. _this.ALPHATEST = false;
  39066. _this.DEPTHPREPASS = false;
  39067. _this.ALPHAFROMDIFFUSE = false;
  39068. _this.POINTSIZE = false;
  39069. _this.FOG = false;
  39070. _this.SPECULARTERM = false;
  39071. _this.DIFFUSEFRESNEL = false;
  39072. _this.OPACITYFRESNEL = false;
  39073. _this.REFLECTIONFRESNEL = false;
  39074. _this.REFRACTIONFRESNEL = false;
  39075. _this.EMISSIVEFRESNEL = false;
  39076. _this.FRESNEL = false;
  39077. _this.NORMAL = false;
  39078. _this.UV1 = false;
  39079. _this.UV2 = false;
  39080. _this.VERTEXCOLOR = false;
  39081. _this.VERTEXALPHA = false;
  39082. _this.NUM_BONE_INFLUENCERS = 0;
  39083. _this.BonesPerMesh = 0;
  39084. _this.INSTANCES = false;
  39085. _this.GLOSSINESS = false;
  39086. _this.ROUGHNESS = false;
  39087. _this.EMISSIVEASILLUMINATION = false;
  39088. _this.LINKEMISSIVEWITHDIFFUSE = false;
  39089. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  39090. _this.LIGHTMAP = false;
  39091. _this.LIGHTMAPDIRECTUV = 0;
  39092. _this.OBJECTSPACE_NORMALMAP = false;
  39093. _this.USELIGHTMAPASSHADOWMAP = false;
  39094. _this.REFLECTIONMAP_3D = false;
  39095. _this.REFLECTIONMAP_SPHERICAL = false;
  39096. _this.REFLECTIONMAP_PLANAR = false;
  39097. _this.REFLECTIONMAP_CUBIC = false;
  39098. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  39099. _this.REFLECTIONMAP_PROJECTION = false;
  39100. _this.REFLECTIONMAP_SKYBOX = false;
  39101. _this.REFLECTIONMAP_EXPLICIT = false;
  39102. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  39103. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  39104. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  39105. _this.INVERTCUBICMAP = false;
  39106. _this.LOGARITHMICDEPTH = false;
  39107. _this.REFRACTION = false;
  39108. _this.REFRACTIONMAP_3D = false;
  39109. _this.REFLECTIONOVERALPHA = false;
  39110. _this.TWOSIDEDLIGHTING = false;
  39111. _this.SHADOWFLOAT = false;
  39112. _this.MORPHTARGETS = false;
  39113. _this.MORPHTARGETS_NORMAL = false;
  39114. _this.MORPHTARGETS_TANGENT = false;
  39115. _this.NUM_MORPH_INFLUENCERS = 0;
  39116. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  39117. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  39118. _this.IMAGEPROCESSING = false;
  39119. _this.VIGNETTE = false;
  39120. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  39121. _this.VIGNETTEBLENDMODEOPAQUE = false;
  39122. _this.TONEMAPPING = false;
  39123. _this.CONTRAST = false;
  39124. _this.COLORCURVES = false;
  39125. _this.COLORGRADING = false;
  39126. _this.COLORGRADING3D = false;
  39127. _this.SAMPLER3DGREENDEPTH = false;
  39128. _this.SAMPLER3DBGRMAP = false;
  39129. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  39130. _this.EXPOSURE = false;
  39131. _this.GRAIN = false;
  39132. _this.rebuild();
  39133. return _this;
  39134. }
  39135. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  39136. var modes = [
  39137. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  39138. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  39139. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  39140. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  39141. ];
  39142. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  39143. var mode = modes_1[_i];
  39144. this[mode] = (mode === modeToEnable);
  39145. }
  39146. };
  39147. return StandardMaterialDefines;
  39148. }(BABYLON.MaterialDefines));
  39149. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  39150. var StandardMaterial = /** @class */ (function (_super) {
  39151. __extends(StandardMaterial, _super);
  39152. function StandardMaterial(name, scene) {
  39153. var _this = _super.call(this, name, scene) || this;
  39154. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  39155. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  39156. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  39157. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  39158. _this.specularPower = 64;
  39159. _this._useAlphaFromDiffuseTexture = false;
  39160. _this._useEmissiveAsIllumination = false;
  39161. _this._linkEmissiveWithDiffuse = false;
  39162. _this._useSpecularOverAlpha = false;
  39163. _this._useReflectionOverAlpha = false;
  39164. _this._disableLighting = false;
  39165. _this._useObjectSpaceNormalMap = false;
  39166. _this._useParallax = false;
  39167. _this._useParallaxOcclusion = false;
  39168. _this.parallaxScaleBias = 0.05;
  39169. _this._roughness = 0;
  39170. _this.indexOfRefraction = 0.98;
  39171. _this.invertRefractionY = true;
  39172. _this._useLightmapAsShadowmap = false;
  39173. _this._useReflectionFresnelFromSpecular = false;
  39174. _this._useGlossinessFromSpecularMapAlpha = false;
  39175. _this._maxSimultaneousLights = 4;
  39176. /**
  39177. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  39178. */
  39179. _this._invertNormalMapX = false;
  39180. /**
  39181. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  39182. */
  39183. _this._invertNormalMapY = false;
  39184. /**
  39185. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  39186. */
  39187. _this._twoSidedLighting = false;
  39188. _this._renderTargets = new BABYLON.SmartArray(16);
  39189. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  39190. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  39191. // Setup the default processing configuration to the scene.
  39192. _this._attachImageProcessingConfiguration(null);
  39193. _this.getRenderTargetTextures = function () {
  39194. _this._renderTargets.reset();
  39195. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  39196. _this._renderTargets.push(_this._reflectionTexture);
  39197. }
  39198. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  39199. _this._renderTargets.push(_this._refractionTexture);
  39200. }
  39201. return _this._renderTargets;
  39202. };
  39203. return _this;
  39204. }
  39205. ;
  39206. ;
  39207. ;
  39208. ;
  39209. ;
  39210. ;
  39211. ;
  39212. ;
  39213. ;
  39214. ;
  39215. ;
  39216. ;
  39217. ;
  39218. ;
  39219. ;
  39220. ;
  39221. ;
  39222. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  39223. /**
  39224. * Gets the image processing configuration used either in this material.
  39225. */
  39226. get: function () {
  39227. return this._imageProcessingConfiguration;
  39228. },
  39229. /**
  39230. * Sets the Default image processing configuration used either in the this material.
  39231. *
  39232. * If sets to null, the scene one is in use.
  39233. */
  39234. set: function (value) {
  39235. this._attachImageProcessingConfiguration(value);
  39236. // Ensure the effect will be rebuilt.
  39237. this._markAllSubMeshesAsTexturesDirty();
  39238. },
  39239. enumerable: true,
  39240. configurable: true
  39241. });
  39242. /**
  39243. * Attaches a new image processing configuration to the Standard Material.
  39244. * @param configuration
  39245. */
  39246. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  39247. var _this = this;
  39248. if (configuration === this._imageProcessingConfiguration) {
  39249. return;
  39250. }
  39251. // Detaches observer.
  39252. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  39253. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  39254. }
  39255. // Pick the scene configuration if needed.
  39256. if (!configuration) {
  39257. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  39258. }
  39259. else {
  39260. this._imageProcessingConfiguration = configuration;
  39261. }
  39262. // Attaches observer.
  39263. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  39264. _this._markAllSubMeshesAsImageProcessingDirty();
  39265. });
  39266. };
  39267. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  39268. /**
  39269. * Gets wether the color curves effect is enabled.
  39270. */
  39271. get: function () {
  39272. return this.imageProcessingConfiguration.colorCurvesEnabled;
  39273. },
  39274. /**
  39275. * Sets wether the color curves effect is enabled.
  39276. */
  39277. set: function (value) {
  39278. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  39279. },
  39280. enumerable: true,
  39281. configurable: true
  39282. });
  39283. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  39284. /**
  39285. * Gets wether the color grading effect is enabled.
  39286. */
  39287. get: function () {
  39288. return this.imageProcessingConfiguration.colorGradingEnabled;
  39289. },
  39290. /**
  39291. * Gets wether the color grading effect is enabled.
  39292. */
  39293. set: function (value) {
  39294. this.imageProcessingConfiguration.colorGradingEnabled = value;
  39295. },
  39296. enumerable: true,
  39297. configurable: true
  39298. });
  39299. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  39300. /**
  39301. * Gets wether tonemapping is enabled or not.
  39302. */
  39303. get: function () {
  39304. return this._imageProcessingConfiguration.toneMappingEnabled;
  39305. },
  39306. /**
  39307. * Sets wether tonemapping is enabled or not
  39308. */
  39309. set: function (value) {
  39310. this._imageProcessingConfiguration.toneMappingEnabled = value;
  39311. },
  39312. enumerable: true,
  39313. configurable: true
  39314. });
  39315. ;
  39316. ;
  39317. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  39318. /**
  39319. * The camera exposure used on this material.
  39320. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  39321. * This corresponds to a photographic exposure.
  39322. */
  39323. get: function () {
  39324. return this._imageProcessingConfiguration.exposure;
  39325. },
  39326. /**
  39327. * The camera exposure used on this material.
  39328. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  39329. * This corresponds to a photographic exposure.
  39330. */
  39331. set: function (value) {
  39332. this._imageProcessingConfiguration.exposure = value;
  39333. },
  39334. enumerable: true,
  39335. configurable: true
  39336. });
  39337. ;
  39338. ;
  39339. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  39340. /**
  39341. * Gets The camera contrast used on this material.
  39342. */
  39343. get: function () {
  39344. return this._imageProcessingConfiguration.contrast;
  39345. },
  39346. /**
  39347. * Sets The camera contrast used on this material.
  39348. */
  39349. set: function (value) {
  39350. this._imageProcessingConfiguration.contrast = value;
  39351. },
  39352. enumerable: true,
  39353. configurable: true
  39354. });
  39355. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  39356. /**
  39357. * Gets the Color Grading 2D Lookup Texture.
  39358. */
  39359. get: function () {
  39360. return this._imageProcessingConfiguration.colorGradingTexture;
  39361. },
  39362. /**
  39363. * Sets the Color Grading 2D Lookup Texture.
  39364. */
  39365. set: function (value) {
  39366. this._imageProcessingConfiguration.colorGradingTexture = value;
  39367. },
  39368. enumerable: true,
  39369. configurable: true
  39370. });
  39371. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  39372. /**
  39373. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  39374. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  39375. * 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;
  39376. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  39377. */
  39378. get: function () {
  39379. return this._imageProcessingConfiguration.colorCurves;
  39380. },
  39381. /**
  39382. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  39383. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  39384. * 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;
  39385. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  39386. */
  39387. set: function (value) {
  39388. this._imageProcessingConfiguration.colorCurves = value;
  39389. },
  39390. enumerable: true,
  39391. configurable: true
  39392. });
  39393. StandardMaterial.prototype.getClassName = function () {
  39394. return "StandardMaterial";
  39395. };
  39396. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  39397. get: function () {
  39398. return this._useLogarithmicDepth;
  39399. },
  39400. set: function (value) {
  39401. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  39402. this._markAllSubMeshesAsMiscDirty();
  39403. },
  39404. enumerable: true,
  39405. configurable: true
  39406. });
  39407. StandardMaterial.prototype.needAlphaBlending = function () {
  39408. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  39409. };
  39410. StandardMaterial.prototype.needAlphaTesting = function () {
  39411. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  39412. };
  39413. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  39414. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  39415. };
  39416. StandardMaterial.prototype.getAlphaTestTexture = function () {
  39417. return this._diffuseTexture;
  39418. };
  39419. /**
  39420. * Child classes can use it to update shaders
  39421. */
  39422. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  39423. if (useInstances === void 0) { useInstances = false; }
  39424. if (subMesh.effect && this.isFrozen) {
  39425. if (this._wasPreviouslyReady && subMesh.effect) {
  39426. return true;
  39427. }
  39428. }
  39429. if (!subMesh._materialDefines) {
  39430. subMesh._materialDefines = new StandardMaterialDefines();
  39431. }
  39432. var scene = this.getScene();
  39433. var defines = subMesh._materialDefines;
  39434. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  39435. if (defines._renderId === scene.getRenderId()) {
  39436. return true;
  39437. }
  39438. }
  39439. var engine = scene.getEngine();
  39440. // Lights
  39441. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  39442. // Textures
  39443. if (defines._areTexturesDirty) {
  39444. defines._needUVs = false;
  39445. defines.MAINUV1 = false;
  39446. defines.MAINUV2 = false;
  39447. if (scene.texturesEnabled) {
  39448. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  39449. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  39450. return false;
  39451. }
  39452. else {
  39453. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  39454. }
  39455. }
  39456. else {
  39457. defines.DIFFUSE = false;
  39458. }
  39459. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  39460. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  39461. return false;
  39462. }
  39463. else {
  39464. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  39465. }
  39466. }
  39467. else {
  39468. defines.AMBIENT = false;
  39469. }
  39470. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  39471. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  39472. return false;
  39473. }
  39474. else {
  39475. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  39476. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  39477. }
  39478. }
  39479. else {
  39480. defines.OPACITY = false;
  39481. }
  39482. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  39483. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  39484. return false;
  39485. }
  39486. else {
  39487. defines._needNormals = true;
  39488. defines.REFLECTION = true;
  39489. defines.ROUGHNESS = (this._roughness > 0);
  39490. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  39491. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  39492. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  39493. switch (this._reflectionTexture.coordinatesMode) {
  39494. case BABYLON.Texture.CUBIC_MODE:
  39495. case BABYLON.Texture.INVCUBIC_MODE:
  39496. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  39497. break;
  39498. case BABYLON.Texture.EXPLICIT_MODE:
  39499. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  39500. break;
  39501. case BABYLON.Texture.PLANAR_MODE:
  39502. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  39503. break;
  39504. case BABYLON.Texture.PROJECTION_MODE:
  39505. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  39506. break;
  39507. case BABYLON.Texture.SKYBOX_MODE:
  39508. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  39509. break;
  39510. case BABYLON.Texture.SPHERICAL_MODE:
  39511. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  39512. break;
  39513. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  39514. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  39515. break;
  39516. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  39517. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  39518. break;
  39519. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  39520. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  39521. break;
  39522. }
  39523. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
  39524. }
  39525. }
  39526. else {
  39527. defines.REFLECTION = false;
  39528. }
  39529. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  39530. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  39531. return false;
  39532. }
  39533. else {
  39534. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  39535. }
  39536. }
  39537. else {
  39538. defines.EMISSIVE = false;
  39539. }
  39540. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  39541. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  39542. return false;
  39543. }
  39544. else {
  39545. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  39546. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  39547. }
  39548. }
  39549. else {
  39550. defines.LIGHTMAP = false;
  39551. }
  39552. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  39553. if (!this._specularTexture.isReadyOrNotBlocking()) {
  39554. return false;
  39555. }
  39556. else {
  39557. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  39558. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  39559. }
  39560. }
  39561. else {
  39562. defines.SPECULAR = false;
  39563. }
  39564. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  39565. // Bump texure can not be not blocking.
  39566. if (!this._bumpTexture.isReady()) {
  39567. return false;
  39568. }
  39569. else {
  39570. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  39571. defines.PARALLAX = this._useParallax;
  39572. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  39573. }
  39574. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  39575. }
  39576. else {
  39577. defines.BUMP = false;
  39578. }
  39579. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  39580. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  39581. return false;
  39582. }
  39583. else {
  39584. defines._needUVs = true;
  39585. defines.REFRACTION = true;
  39586. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  39587. }
  39588. }
  39589. else {
  39590. defines.REFRACTION = false;
  39591. }
  39592. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  39593. }
  39594. else {
  39595. defines.DIFFUSE = false;
  39596. defines.AMBIENT = false;
  39597. defines.OPACITY = false;
  39598. defines.REFLECTION = false;
  39599. defines.EMISSIVE = false;
  39600. defines.LIGHTMAP = false;
  39601. defines.BUMP = false;
  39602. defines.REFRACTION = false;
  39603. }
  39604. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  39605. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  39606. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  39607. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  39608. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  39609. }
  39610. if (defines._areImageProcessingDirty) {
  39611. if (!this._imageProcessingConfiguration.isReady()) {
  39612. return false;
  39613. }
  39614. this._imageProcessingConfiguration.prepareDefines(defines);
  39615. }
  39616. if (defines._areFresnelDirty) {
  39617. if (StandardMaterial.FresnelEnabled) {
  39618. // Fresnel
  39619. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  39620. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  39621. this._reflectionFresnelParameters) {
  39622. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  39623. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  39624. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  39625. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  39626. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  39627. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  39628. defines._needNormals = true;
  39629. defines.FRESNEL = true;
  39630. }
  39631. }
  39632. else {
  39633. defines.FRESNEL = false;
  39634. }
  39635. }
  39636. // Misc.
  39637. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  39638. // Attribs
  39639. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  39640. // Values that need to be evaluated on every frame
  39641. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  39642. // Get correct effect
  39643. if (defines.isDirty) {
  39644. defines.markAsProcessed();
  39645. scene.resetCachedMaterial();
  39646. // Fallbacks
  39647. var fallbacks = new BABYLON.EffectFallbacks();
  39648. if (defines.REFLECTION) {
  39649. fallbacks.addFallback(0, "REFLECTION");
  39650. }
  39651. if (defines.SPECULAR) {
  39652. fallbacks.addFallback(0, "SPECULAR");
  39653. }
  39654. if (defines.BUMP) {
  39655. fallbacks.addFallback(0, "BUMP");
  39656. }
  39657. if (defines.PARALLAX) {
  39658. fallbacks.addFallback(1, "PARALLAX");
  39659. }
  39660. if (defines.PARALLAXOCCLUSION) {
  39661. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  39662. }
  39663. if (defines.SPECULAROVERALPHA) {
  39664. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  39665. }
  39666. if (defines.FOG) {
  39667. fallbacks.addFallback(1, "FOG");
  39668. }
  39669. if (defines.POINTSIZE) {
  39670. fallbacks.addFallback(0, "POINTSIZE");
  39671. }
  39672. if (defines.LOGARITHMICDEPTH) {
  39673. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  39674. }
  39675. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  39676. if (defines.SPECULARTERM) {
  39677. fallbacks.addFallback(0, "SPECULARTERM");
  39678. }
  39679. if (defines.DIFFUSEFRESNEL) {
  39680. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  39681. }
  39682. if (defines.OPACITYFRESNEL) {
  39683. fallbacks.addFallback(2, "OPACITYFRESNEL");
  39684. }
  39685. if (defines.REFLECTIONFRESNEL) {
  39686. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  39687. }
  39688. if (defines.EMISSIVEFRESNEL) {
  39689. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  39690. }
  39691. if (defines.FRESNEL) {
  39692. fallbacks.addFallback(4, "FRESNEL");
  39693. }
  39694. //Attributes
  39695. var attribs = [BABYLON.VertexBuffer.PositionKind];
  39696. if (defines.NORMAL) {
  39697. attribs.push(BABYLON.VertexBuffer.NormalKind);
  39698. }
  39699. if (defines.UV1) {
  39700. attribs.push(BABYLON.VertexBuffer.UVKind);
  39701. }
  39702. if (defines.UV2) {
  39703. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  39704. }
  39705. if (defines.VERTEXCOLOR) {
  39706. attribs.push(BABYLON.VertexBuffer.ColorKind);
  39707. }
  39708. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  39709. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  39710. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  39711. var shaderName = "default";
  39712. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  39713. "vFogInfos", "vFogColor", "pointSize",
  39714. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  39715. "mBones",
  39716. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "normalMatrix", "lightmapMatrix", "refractionMatrix",
  39717. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  39718. "vReflectionPosition", "vReflectionSize",
  39719. "logarithmicDepthConstant", "vTangentSpaceParams"
  39720. ];
  39721. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  39722. var uniformBuffers = ["Material", "Scene"];
  39723. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  39724. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  39725. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  39726. uniformsNames: uniforms,
  39727. uniformBuffersNames: uniformBuffers,
  39728. samplers: samplers,
  39729. defines: defines,
  39730. maxSimultaneousLights: this._maxSimultaneousLights
  39731. });
  39732. if (this.customShaderNameResolve) {
  39733. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  39734. }
  39735. var join = defines.toString();
  39736. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  39737. attributes: attribs,
  39738. uniformsNames: uniforms,
  39739. uniformBuffersNames: uniformBuffers,
  39740. samplers: samplers,
  39741. defines: join,
  39742. fallbacks: fallbacks,
  39743. onCompiled: this.onCompiled,
  39744. onError: this.onError,
  39745. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  39746. }, engine), defines);
  39747. this.buildUniformLayout();
  39748. }
  39749. if (!subMesh.effect || !subMesh.effect.isReady()) {
  39750. return false;
  39751. }
  39752. defines._renderId = scene.getRenderId();
  39753. this._wasPreviouslyReady = true;
  39754. return true;
  39755. };
  39756. StandardMaterial.prototype.buildUniformLayout = function () {
  39757. // Order is important !
  39758. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  39759. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  39760. this._uniformBuffer.addUniform("opacityParts", 4);
  39761. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  39762. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  39763. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  39764. this._uniformBuffer.addUniform("refractionRightColor", 4);
  39765. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  39766. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  39767. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  39768. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  39769. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  39770. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  39771. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  39772. this._uniformBuffer.addUniform("vReflectionSize", 3);
  39773. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  39774. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  39775. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  39776. this._uniformBuffer.addUniform("vBumpInfos", 3);
  39777. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  39778. this._uniformBuffer.addUniform("ambientMatrix", 16);
  39779. this._uniformBuffer.addUniform("opacityMatrix", 16);
  39780. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  39781. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  39782. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  39783. this._uniformBuffer.addUniform("specularMatrix", 16);
  39784. this._uniformBuffer.addUniform("bumpMatrix", 16);
  39785. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  39786. this._uniformBuffer.addUniform("refractionMatrix", 16);
  39787. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  39788. this._uniformBuffer.addUniform("vSpecularColor", 4);
  39789. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  39790. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  39791. this._uniformBuffer.addUniform("pointSize", 1);
  39792. this._uniformBuffer.create();
  39793. };
  39794. StandardMaterial.prototype.unbind = function () {
  39795. if (this._activeEffect) {
  39796. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  39797. this._activeEffect.setTexture("reflection2DSampler", null);
  39798. }
  39799. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  39800. this._activeEffect.setTexture("refraction2DSampler", null);
  39801. }
  39802. }
  39803. _super.prototype.unbind.call(this);
  39804. };
  39805. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  39806. var scene = this.getScene();
  39807. var defines = subMesh._materialDefines;
  39808. if (!defines) {
  39809. return;
  39810. }
  39811. var effect = subMesh.effect;
  39812. if (!effect) {
  39813. return;
  39814. }
  39815. this._activeEffect = effect;
  39816. // Matrices
  39817. this.bindOnlyWorldMatrix(world);
  39818. // Normal Matrix
  39819. if (defines.OBJECTSPACE_NORMALMAP) {
  39820. world.toNormalMatrix(this._normalMatrix);
  39821. this.bindOnlyNormalMatrix(this._normalMatrix);
  39822. }
  39823. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  39824. // Bones
  39825. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  39826. if (mustRebind) {
  39827. this._uniformBuffer.bindToEffect(effect, "Material");
  39828. this.bindViewProjection(effect);
  39829. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  39830. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  39831. // Fresnel
  39832. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  39833. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  39834. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  39835. }
  39836. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  39837. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  39838. }
  39839. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  39840. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  39841. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  39842. }
  39843. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  39844. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  39845. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  39846. }
  39847. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  39848. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  39849. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  39850. }
  39851. }
  39852. // Textures
  39853. if (scene.texturesEnabled) {
  39854. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  39855. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  39856. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  39857. }
  39858. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  39859. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  39860. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  39861. }
  39862. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  39863. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  39864. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  39865. }
  39866. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  39867. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  39868. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  39869. if (this._reflectionTexture.boundingBoxSize) {
  39870. var cubeTexture = this._reflectionTexture;
  39871. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  39872. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  39873. }
  39874. }
  39875. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  39876. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  39877. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  39878. }
  39879. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  39880. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  39881. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  39882. }
  39883. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  39884. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  39885. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  39886. }
  39887. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  39888. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  39889. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  39890. if (scene._mirroredCameraPosition) {
  39891. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  39892. }
  39893. else {
  39894. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  39895. }
  39896. }
  39897. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  39898. var depth = 1.0;
  39899. if (!this._refractionTexture.isCube) {
  39900. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  39901. if (this._refractionTexture.depth) {
  39902. depth = this._refractionTexture.depth;
  39903. }
  39904. }
  39905. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  39906. }
  39907. }
  39908. // Point size
  39909. if (this.pointsCloud) {
  39910. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  39911. }
  39912. if (defines.SPECULARTERM) {
  39913. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  39914. }
  39915. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  39916. // Diffuse
  39917. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  39918. }
  39919. // Textures
  39920. if (scene.texturesEnabled) {
  39921. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  39922. effect.setTexture("diffuseSampler", this._diffuseTexture);
  39923. }
  39924. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  39925. effect.setTexture("ambientSampler", this._ambientTexture);
  39926. }
  39927. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  39928. effect.setTexture("opacitySampler", this._opacityTexture);
  39929. }
  39930. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  39931. if (this._reflectionTexture.isCube) {
  39932. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  39933. }
  39934. else {
  39935. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  39936. }
  39937. }
  39938. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  39939. effect.setTexture("emissiveSampler", this._emissiveTexture);
  39940. }
  39941. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  39942. effect.setTexture("lightmapSampler", this._lightmapTexture);
  39943. }
  39944. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  39945. effect.setTexture("specularSampler", this._specularTexture);
  39946. }
  39947. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  39948. effect.setTexture("bumpSampler", this._bumpTexture);
  39949. }
  39950. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  39951. var depth = 1.0;
  39952. if (this._refractionTexture.isCube) {
  39953. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  39954. }
  39955. else {
  39956. effect.setTexture("refraction2DSampler", this._refractionTexture);
  39957. }
  39958. }
  39959. }
  39960. // Clip plane
  39961. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  39962. // Colors
  39963. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  39964. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  39965. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  39966. }
  39967. if (mustRebind || !this.isFrozen) {
  39968. // Lights
  39969. if (scene.lightsEnabled && !this._disableLighting) {
  39970. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  39971. }
  39972. // View
  39973. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  39974. this.bindView(effect);
  39975. }
  39976. // Fog
  39977. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  39978. // Morph targets
  39979. if (defines.NUM_MORPH_INFLUENCERS) {
  39980. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  39981. }
  39982. // Log. depth
  39983. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  39984. // image processing
  39985. if (!this._imageProcessingConfiguration.applyByPostProcess) {
  39986. this._imageProcessingConfiguration.bind(this._activeEffect);
  39987. }
  39988. }
  39989. this._uniformBuffer.update();
  39990. this._afterBind(mesh, this._activeEffect);
  39991. };
  39992. StandardMaterial.prototype.getAnimatables = function () {
  39993. var results = [];
  39994. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  39995. results.push(this._diffuseTexture);
  39996. }
  39997. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  39998. results.push(this._ambientTexture);
  39999. }
  40000. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  40001. results.push(this._opacityTexture);
  40002. }
  40003. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  40004. results.push(this._reflectionTexture);
  40005. }
  40006. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  40007. results.push(this._emissiveTexture);
  40008. }
  40009. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  40010. results.push(this._specularTexture);
  40011. }
  40012. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  40013. results.push(this._bumpTexture);
  40014. }
  40015. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  40016. results.push(this._lightmapTexture);
  40017. }
  40018. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  40019. results.push(this._refractionTexture);
  40020. }
  40021. return results;
  40022. };
  40023. StandardMaterial.prototype.getActiveTextures = function () {
  40024. var activeTextures = _super.prototype.getActiveTextures.call(this);
  40025. if (this._diffuseTexture) {
  40026. activeTextures.push(this._diffuseTexture);
  40027. }
  40028. if (this._ambientTexture) {
  40029. activeTextures.push(this._ambientTexture);
  40030. }
  40031. if (this._opacityTexture) {
  40032. activeTextures.push(this._opacityTexture);
  40033. }
  40034. if (this._reflectionTexture) {
  40035. activeTextures.push(this._reflectionTexture);
  40036. }
  40037. if (this._emissiveTexture) {
  40038. activeTextures.push(this._emissiveTexture);
  40039. }
  40040. if (this._specularTexture) {
  40041. activeTextures.push(this._specularTexture);
  40042. }
  40043. if (this._bumpTexture) {
  40044. activeTextures.push(this._bumpTexture);
  40045. }
  40046. if (this._lightmapTexture) {
  40047. activeTextures.push(this._lightmapTexture);
  40048. }
  40049. if (this._refractionTexture) {
  40050. activeTextures.push(this._refractionTexture);
  40051. }
  40052. return activeTextures;
  40053. };
  40054. StandardMaterial.prototype.hasTexture = function (texture) {
  40055. if (_super.prototype.hasTexture.call(this, texture)) {
  40056. return true;
  40057. }
  40058. if (this._diffuseTexture === texture) {
  40059. return true;
  40060. }
  40061. if (this._ambientTexture === texture) {
  40062. return true;
  40063. }
  40064. if (this._opacityTexture === texture) {
  40065. return true;
  40066. }
  40067. if (this._reflectionTexture === texture) {
  40068. return true;
  40069. }
  40070. if (this._emissiveTexture === texture) {
  40071. return true;
  40072. }
  40073. if (this._specularTexture === texture) {
  40074. return true;
  40075. }
  40076. if (this._bumpTexture === texture) {
  40077. return true;
  40078. }
  40079. if (this._lightmapTexture === texture) {
  40080. return true;
  40081. }
  40082. if (this._refractionTexture === texture) {
  40083. return true;
  40084. }
  40085. return false;
  40086. };
  40087. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  40088. if (forceDisposeTextures) {
  40089. if (this._diffuseTexture) {
  40090. this._diffuseTexture.dispose();
  40091. }
  40092. if (this._ambientTexture) {
  40093. this._ambientTexture.dispose();
  40094. }
  40095. if (this._opacityTexture) {
  40096. this._opacityTexture.dispose();
  40097. }
  40098. if (this._reflectionTexture) {
  40099. this._reflectionTexture.dispose();
  40100. }
  40101. if (this._emissiveTexture) {
  40102. this._emissiveTexture.dispose();
  40103. }
  40104. if (this._specularTexture) {
  40105. this._specularTexture.dispose();
  40106. }
  40107. if (this._bumpTexture) {
  40108. this._bumpTexture.dispose();
  40109. }
  40110. if (this._lightmapTexture) {
  40111. this._lightmapTexture.dispose();
  40112. }
  40113. if (this._refractionTexture) {
  40114. this._refractionTexture.dispose();
  40115. }
  40116. }
  40117. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  40118. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  40119. }
  40120. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  40121. };
  40122. StandardMaterial.prototype.clone = function (name) {
  40123. var _this = this;
  40124. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  40125. result.name = name;
  40126. result.id = name;
  40127. return result;
  40128. };
  40129. StandardMaterial.prototype.serialize = function () {
  40130. return BABYLON.SerializationHelper.Serialize(this);
  40131. };
  40132. // Statics
  40133. StandardMaterial.Parse = function (source, scene, rootUrl) {
  40134. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  40135. };
  40136. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  40137. get: function () {
  40138. return StandardMaterial._DiffuseTextureEnabled;
  40139. },
  40140. set: function (value) {
  40141. if (StandardMaterial._DiffuseTextureEnabled === value) {
  40142. return;
  40143. }
  40144. StandardMaterial._DiffuseTextureEnabled = value;
  40145. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40146. },
  40147. enumerable: true,
  40148. configurable: true
  40149. });
  40150. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  40151. get: function () {
  40152. return StandardMaterial._AmbientTextureEnabled;
  40153. },
  40154. set: function (value) {
  40155. if (StandardMaterial._AmbientTextureEnabled === value) {
  40156. return;
  40157. }
  40158. StandardMaterial._AmbientTextureEnabled = value;
  40159. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40160. },
  40161. enumerable: true,
  40162. configurable: true
  40163. });
  40164. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  40165. get: function () {
  40166. return StandardMaterial._OpacityTextureEnabled;
  40167. },
  40168. set: function (value) {
  40169. if (StandardMaterial._OpacityTextureEnabled === value) {
  40170. return;
  40171. }
  40172. StandardMaterial._OpacityTextureEnabled = value;
  40173. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40174. },
  40175. enumerable: true,
  40176. configurable: true
  40177. });
  40178. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  40179. get: function () {
  40180. return StandardMaterial._ReflectionTextureEnabled;
  40181. },
  40182. set: function (value) {
  40183. if (StandardMaterial._ReflectionTextureEnabled === value) {
  40184. return;
  40185. }
  40186. StandardMaterial._ReflectionTextureEnabled = value;
  40187. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40188. },
  40189. enumerable: true,
  40190. configurable: true
  40191. });
  40192. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  40193. get: function () {
  40194. return StandardMaterial._EmissiveTextureEnabled;
  40195. },
  40196. set: function (value) {
  40197. if (StandardMaterial._EmissiveTextureEnabled === value) {
  40198. return;
  40199. }
  40200. StandardMaterial._EmissiveTextureEnabled = value;
  40201. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40202. },
  40203. enumerable: true,
  40204. configurable: true
  40205. });
  40206. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  40207. get: function () {
  40208. return StandardMaterial._SpecularTextureEnabled;
  40209. },
  40210. set: function (value) {
  40211. if (StandardMaterial._SpecularTextureEnabled === value) {
  40212. return;
  40213. }
  40214. StandardMaterial._SpecularTextureEnabled = value;
  40215. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40216. },
  40217. enumerable: true,
  40218. configurable: true
  40219. });
  40220. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  40221. get: function () {
  40222. return StandardMaterial._BumpTextureEnabled;
  40223. },
  40224. set: function (value) {
  40225. if (StandardMaterial._BumpTextureEnabled === value) {
  40226. return;
  40227. }
  40228. StandardMaterial._BumpTextureEnabled = value;
  40229. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40230. },
  40231. enumerable: true,
  40232. configurable: true
  40233. });
  40234. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  40235. get: function () {
  40236. return StandardMaterial._LightmapTextureEnabled;
  40237. },
  40238. set: function (value) {
  40239. if (StandardMaterial._LightmapTextureEnabled === value) {
  40240. return;
  40241. }
  40242. StandardMaterial._LightmapTextureEnabled = value;
  40243. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40244. },
  40245. enumerable: true,
  40246. configurable: true
  40247. });
  40248. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  40249. get: function () {
  40250. return StandardMaterial._RefractionTextureEnabled;
  40251. },
  40252. set: function (value) {
  40253. if (StandardMaterial._RefractionTextureEnabled === value) {
  40254. return;
  40255. }
  40256. StandardMaterial._RefractionTextureEnabled = value;
  40257. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40258. },
  40259. enumerable: true,
  40260. configurable: true
  40261. });
  40262. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  40263. get: function () {
  40264. return StandardMaterial._ColorGradingTextureEnabled;
  40265. },
  40266. set: function (value) {
  40267. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  40268. return;
  40269. }
  40270. StandardMaterial._ColorGradingTextureEnabled = value;
  40271. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40272. },
  40273. enumerable: true,
  40274. configurable: true
  40275. });
  40276. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  40277. get: function () {
  40278. return StandardMaterial._FresnelEnabled;
  40279. },
  40280. set: function (value) {
  40281. if (StandardMaterial._FresnelEnabled === value) {
  40282. return;
  40283. }
  40284. StandardMaterial._FresnelEnabled = value;
  40285. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  40286. },
  40287. enumerable: true,
  40288. configurable: true
  40289. });
  40290. // Flags used to enable or disable a type of texture for all Standard Materials
  40291. StandardMaterial._DiffuseTextureEnabled = true;
  40292. StandardMaterial._AmbientTextureEnabled = true;
  40293. StandardMaterial._OpacityTextureEnabled = true;
  40294. StandardMaterial._ReflectionTextureEnabled = true;
  40295. StandardMaterial._EmissiveTextureEnabled = true;
  40296. StandardMaterial._SpecularTextureEnabled = true;
  40297. StandardMaterial._BumpTextureEnabled = true;
  40298. StandardMaterial._LightmapTextureEnabled = true;
  40299. StandardMaterial._RefractionTextureEnabled = true;
  40300. StandardMaterial._ColorGradingTextureEnabled = true;
  40301. StandardMaterial._FresnelEnabled = true;
  40302. __decorate([
  40303. BABYLON.serializeAsTexture("diffuseTexture")
  40304. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  40305. __decorate([
  40306. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  40307. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  40308. __decorate([
  40309. BABYLON.serializeAsTexture("ambientTexture")
  40310. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  40311. __decorate([
  40312. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40313. ], StandardMaterial.prototype, "ambientTexture", void 0);
  40314. __decorate([
  40315. BABYLON.serializeAsTexture("opacityTexture")
  40316. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  40317. __decorate([
  40318. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  40319. ], StandardMaterial.prototype, "opacityTexture", void 0);
  40320. __decorate([
  40321. BABYLON.serializeAsTexture("reflectionTexture")
  40322. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  40323. __decorate([
  40324. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40325. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  40326. __decorate([
  40327. BABYLON.serializeAsTexture("emissiveTexture")
  40328. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  40329. __decorate([
  40330. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40331. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  40332. __decorate([
  40333. BABYLON.serializeAsTexture("specularTexture")
  40334. ], StandardMaterial.prototype, "_specularTexture", void 0);
  40335. __decorate([
  40336. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40337. ], StandardMaterial.prototype, "specularTexture", void 0);
  40338. __decorate([
  40339. BABYLON.serializeAsTexture("bumpTexture")
  40340. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  40341. __decorate([
  40342. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40343. ], StandardMaterial.prototype, "bumpTexture", void 0);
  40344. __decorate([
  40345. BABYLON.serializeAsTexture("lightmapTexture")
  40346. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  40347. __decorate([
  40348. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40349. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  40350. __decorate([
  40351. BABYLON.serializeAsTexture("refractionTexture")
  40352. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  40353. __decorate([
  40354. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40355. ], StandardMaterial.prototype, "refractionTexture", void 0);
  40356. __decorate([
  40357. BABYLON.serializeAsColor3("ambient")
  40358. ], StandardMaterial.prototype, "ambientColor", void 0);
  40359. __decorate([
  40360. BABYLON.serializeAsColor3("diffuse")
  40361. ], StandardMaterial.prototype, "diffuseColor", void 0);
  40362. __decorate([
  40363. BABYLON.serializeAsColor3("specular")
  40364. ], StandardMaterial.prototype, "specularColor", void 0);
  40365. __decorate([
  40366. BABYLON.serializeAsColor3("emissive")
  40367. ], StandardMaterial.prototype, "emissiveColor", void 0);
  40368. __decorate([
  40369. BABYLON.serialize()
  40370. ], StandardMaterial.prototype, "specularPower", void 0);
  40371. __decorate([
  40372. BABYLON.serialize("useAlphaFromDiffuseTexture")
  40373. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  40374. __decorate([
  40375. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40376. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  40377. __decorate([
  40378. BABYLON.serialize("useEmissiveAsIllumination")
  40379. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  40380. __decorate([
  40381. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40382. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  40383. __decorate([
  40384. BABYLON.serialize("linkEmissiveWithDiffuse")
  40385. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  40386. __decorate([
  40387. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40388. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  40389. __decorate([
  40390. BABYLON.serialize("useSpecularOverAlpha")
  40391. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  40392. __decorate([
  40393. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40394. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  40395. __decorate([
  40396. BABYLON.serialize("useReflectionOverAlpha")
  40397. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  40398. __decorate([
  40399. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40400. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  40401. __decorate([
  40402. BABYLON.serialize("disableLighting")
  40403. ], StandardMaterial.prototype, "_disableLighting", void 0);
  40404. __decorate([
  40405. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  40406. ], StandardMaterial.prototype, "disableLighting", void 0);
  40407. __decorate([
  40408. BABYLON.serialize("useObjectSpaceNormalMap")
  40409. ], StandardMaterial.prototype, "_useObjectSpaceNormalMap", void 0);
  40410. __decorate([
  40411. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40412. ], StandardMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  40413. __decorate([
  40414. BABYLON.serialize("useParallax")
  40415. ], StandardMaterial.prototype, "_useParallax", void 0);
  40416. __decorate([
  40417. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40418. ], StandardMaterial.prototype, "useParallax", void 0);
  40419. __decorate([
  40420. BABYLON.serialize("useParallaxOcclusion")
  40421. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  40422. __decorate([
  40423. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40424. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  40425. __decorate([
  40426. BABYLON.serialize()
  40427. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  40428. __decorate([
  40429. BABYLON.serialize("roughness")
  40430. ], StandardMaterial.prototype, "_roughness", void 0);
  40431. __decorate([
  40432. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40433. ], StandardMaterial.prototype, "roughness", void 0);
  40434. __decorate([
  40435. BABYLON.serialize()
  40436. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  40437. __decorate([
  40438. BABYLON.serialize()
  40439. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  40440. __decorate([
  40441. BABYLON.serialize("useLightmapAsShadowmap")
  40442. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  40443. __decorate([
  40444. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40445. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  40446. __decorate([
  40447. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  40448. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  40449. __decorate([
  40450. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40451. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  40452. __decorate([
  40453. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  40454. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  40455. __decorate([
  40456. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  40457. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  40458. __decorate([
  40459. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  40460. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  40461. __decorate([
  40462. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40463. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  40464. __decorate([
  40465. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  40466. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  40467. __decorate([
  40468. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40469. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  40470. __decorate([
  40471. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  40472. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  40473. __decorate([
  40474. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40475. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  40476. __decorate([
  40477. BABYLON.serialize("useReflectionFresnelFromSpecular")
  40478. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  40479. __decorate([
  40480. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40481. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  40482. __decorate([
  40483. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  40484. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  40485. __decorate([
  40486. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40487. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  40488. __decorate([
  40489. BABYLON.serialize("maxSimultaneousLights")
  40490. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  40491. __decorate([
  40492. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  40493. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  40494. __decorate([
  40495. BABYLON.serialize("invertNormalMapX")
  40496. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  40497. __decorate([
  40498. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40499. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  40500. __decorate([
  40501. BABYLON.serialize("invertNormalMapY")
  40502. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  40503. __decorate([
  40504. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40505. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  40506. __decorate([
  40507. BABYLON.serialize("twoSidedLighting")
  40508. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  40509. __decorate([
  40510. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40511. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  40512. __decorate([
  40513. BABYLON.serialize()
  40514. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  40515. return StandardMaterial;
  40516. }(BABYLON.PushMaterial));
  40517. BABYLON.StandardMaterial = StandardMaterial;
  40518. })(BABYLON || (BABYLON = {}));
  40519. //# sourceMappingURL=babylon.standardMaterial.js.map
  40520. var BABYLON;
  40521. (function (BABYLON) {
  40522. /**
  40523. * Manages the defines for the PBR Material.
  40524. */
  40525. var PBRMaterialDefines = /** @class */ (function (_super) {
  40526. __extends(PBRMaterialDefines, _super);
  40527. /**
  40528. * Initializes the PBR Material defines.
  40529. */
  40530. function PBRMaterialDefines() {
  40531. var _this = _super.call(this) || this;
  40532. _this.PBR = true;
  40533. _this.MAINUV1 = false;
  40534. _this.MAINUV2 = false;
  40535. _this.UV1 = false;
  40536. _this.UV2 = false;
  40537. _this.ALBEDO = false;
  40538. _this.ALBEDODIRECTUV = 0;
  40539. _this.VERTEXCOLOR = false;
  40540. _this.AMBIENT = false;
  40541. _this.AMBIENTDIRECTUV = 0;
  40542. _this.AMBIENTINGRAYSCALE = false;
  40543. _this.OPACITY = false;
  40544. _this.VERTEXALPHA = false;
  40545. _this.OPACITYDIRECTUV = 0;
  40546. _this.OPACITYRGB = false;
  40547. _this.ALPHATEST = false;
  40548. _this.DEPTHPREPASS = false;
  40549. _this.ALPHABLEND = false;
  40550. _this.ALPHAFROMALBEDO = false;
  40551. _this.ALPHATESTVALUE = 0.5;
  40552. _this.SPECULAROVERALPHA = false;
  40553. _this.RADIANCEOVERALPHA = false;
  40554. _this.ALPHAFRESNEL = false;
  40555. _this.LINEARALPHAFRESNEL = false;
  40556. _this.PREMULTIPLYALPHA = false;
  40557. _this.EMISSIVE = false;
  40558. _this.EMISSIVEDIRECTUV = 0;
  40559. _this.REFLECTIVITY = false;
  40560. _this.REFLECTIVITYDIRECTUV = 0;
  40561. _this.SPECULARTERM = false;
  40562. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  40563. _this.MICROSURFACEAUTOMATIC = false;
  40564. _this.LODBASEDMICROSFURACE = false;
  40565. _this.MICROSURFACEMAP = false;
  40566. _this.MICROSURFACEMAPDIRECTUV = 0;
  40567. _this.METALLICWORKFLOW = false;
  40568. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  40569. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  40570. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  40571. _this.AOSTOREINMETALMAPRED = false;
  40572. _this.ENVIRONMENTBRDF = false;
  40573. _this.NORMAL = false;
  40574. _this.TANGENT = false;
  40575. _this.BUMP = false;
  40576. _this.BUMPDIRECTUV = 0;
  40577. _this.OBJECTSPACE_NORMALMAP = false;
  40578. _this.PARALLAX = false;
  40579. _this.PARALLAXOCCLUSION = false;
  40580. _this.NORMALXYSCALE = true;
  40581. _this.LIGHTMAP = false;
  40582. _this.LIGHTMAPDIRECTUV = 0;
  40583. _this.USELIGHTMAPASSHADOWMAP = false;
  40584. _this.REFLECTION = false;
  40585. _this.REFLECTIONMAP_3D = false;
  40586. _this.REFLECTIONMAP_SPHERICAL = false;
  40587. _this.REFLECTIONMAP_PLANAR = false;
  40588. _this.REFLECTIONMAP_CUBIC = false;
  40589. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  40590. _this.REFLECTIONMAP_PROJECTION = false;
  40591. _this.REFLECTIONMAP_SKYBOX = false;
  40592. _this.REFLECTIONMAP_EXPLICIT = false;
  40593. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  40594. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  40595. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  40596. _this.INVERTCUBICMAP = false;
  40597. _this.USESPHERICALFROMREFLECTIONMAP = false;
  40598. _this.USESPHERICALINVERTEX = false;
  40599. _this.REFLECTIONMAP_OPPOSITEZ = false;
  40600. _this.LODINREFLECTIONALPHA = false;
  40601. _this.GAMMAREFLECTION = false;
  40602. _this.RADIANCEOCCLUSION = false;
  40603. _this.HORIZONOCCLUSION = false;
  40604. _this.REFRACTION = false;
  40605. _this.REFRACTIONMAP_3D = false;
  40606. _this.REFRACTIONMAP_OPPOSITEZ = false;
  40607. _this.LODINREFRACTIONALPHA = false;
  40608. _this.GAMMAREFRACTION = false;
  40609. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  40610. _this.INSTANCES = false;
  40611. _this.NUM_BONE_INFLUENCERS = 0;
  40612. _this.BonesPerMesh = 0;
  40613. _this.NONUNIFORMSCALING = false;
  40614. _this.MORPHTARGETS = false;
  40615. _this.MORPHTARGETS_NORMAL = false;
  40616. _this.MORPHTARGETS_TANGENT = false;
  40617. _this.NUM_MORPH_INFLUENCERS = 0;
  40618. _this.IMAGEPROCESSING = false;
  40619. _this.VIGNETTE = false;
  40620. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  40621. _this.VIGNETTEBLENDMODEOPAQUE = false;
  40622. _this.TONEMAPPING = false;
  40623. _this.CONTRAST = false;
  40624. _this.COLORCURVES = false;
  40625. _this.COLORGRADING = false;
  40626. _this.COLORGRADING3D = false;
  40627. _this.SAMPLER3DGREENDEPTH = false;
  40628. _this.SAMPLER3DBGRMAP = false;
  40629. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  40630. _this.EXPOSURE = false;
  40631. _this.GRAIN = false;
  40632. _this.USEPHYSICALLIGHTFALLOFF = false;
  40633. _this.TWOSIDEDLIGHTING = false;
  40634. _this.SHADOWFLOAT = false;
  40635. _this.CLIPPLANE = false;
  40636. _this.POINTSIZE = false;
  40637. _this.FOG = false;
  40638. _this.LOGARITHMICDEPTH = false;
  40639. _this.FORCENORMALFORWARD = false;
  40640. _this.rebuild();
  40641. return _this;
  40642. }
  40643. /**
  40644. * Resets the PBR Material defines.
  40645. */
  40646. PBRMaterialDefines.prototype.reset = function () {
  40647. _super.prototype.reset.call(this);
  40648. this.ALPHATESTVALUE = 0.5;
  40649. this.PBR = true;
  40650. };
  40651. return PBRMaterialDefines;
  40652. }(BABYLON.MaterialDefines));
  40653. /**
  40654. * The Physically based material base class of BJS.
  40655. *
  40656. * This offers the main features of a standard PBR material.
  40657. * For more information, please refer to the documentation :
  40658. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  40659. */
  40660. var PBRBaseMaterial = /** @class */ (function (_super) {
  40661. __extends(PBRBaseMaterial, _super);
  40662. /**
  40663. * Instantiates a new PBRMaterial instance.
  40664. *
  40665. * @param name The material name
  40666. * @param scene The scene the material will be use in.
  40667. */
  40668. function PBRBaseMaterial(name, scene) {
  40669. var _this = _super.call(this, name, scene) || this;
  40670. /**
  40671. * Intensity of the direct lights e.g. the four lights available in your scene.
  40672. * This impacts both the direct diffuse and specular highlights.
  40673. */
  40674. _this._directIntensity = 1.0;
  40675. /**
  40676. * Intensity of the emissive part of the material.
  40677. * This helps controlling the emissive effect without modifying the emissive color.
  40678. */
  40679. _this._emissiveIntensity = 1.0;
  40680. /**
  40681. * Intensity of the environment e.g. how much the environment will light the object
  40682. * either through harmonics for rough material or through the refelction for shiny ones.
  40683. */
  40684. _this._environmentIntensity = 1.0;
  40685. /**
  40686. * This is a special control allowing the reduction of the specular highlights coming from the
  40687. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  40688. */
  40689. _this._specularIntensity = 1.0;
  40690. /**
  40691. * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
  40692. */
  40693. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  40694. /**
  40695. * Debug Control allowing disabling the bump map on this material.
  40696. */
  40697. _this._disableBumpMap = false;
  40698. /**
  40699. * AKA Occlusion Texture Intensity in other nomenclature.
  40700. */
  40701. _this._ambientTextureStrength = 1.0;
  40702. /**
  40703. * The color of a material in ambient lighting.
  40704. */
  40705. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  40706. /**
  40707. * AKA Diffuse Color in other nomenclature.
  40708. */
  40709. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  40710. /**
  40711. * AKA Specular Color in other nomenclature.
  40712. */
  40713. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  40714. /**
  40715. * The color applied when light is reflected from a material.
  40716. */
  40717. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  40718. /**
  40719. * The color applied when light is emitted from a material.
  40720. */
  40721. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  40722. /**
  40723. * AKA Glossiness in other nomenclature.
  40724. */
  40725. _this._microSurface = 0.9;
  40726. /**
  40727. * source material index of refraction (IOR)' / 'destination material IOR.
  40728. */
  40729. _this._indexOfRefraction = 0.66;
  40730. /**
  40731. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  40732. */
  40733. _this._invertRefractionY = false;
  40734. /**
  40735. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  40736. * Materials half opaque for instance using refraction could benefit from this control.
  40737. */
  40738. _this._linkRefractionWithTransparency = false;
  40739. /**
  40740. * Specifies that the material will use the light map as a show map.
  40741. */
  40742. _this._useLightmapAsShadowmap = false;
  40743. /**
  40744. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  40745. * makes the reflect vector face the model (under horizon).
  40746. */
  40747. _this._useHorizonOcclusion = true;
  40748. /**
  40749. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  40750. * too much the area relying on ambient texture to define their ambient occlusion.
  40751. */
  40752. _this._useRadianceOcclusion = true;
  40753. /**
  40754. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  40755. */
  40756. _this._useAlphaFromAlbedoTexture = false;
  40757. /**
  40758. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  40759. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  40760. */
  40761. _this._useSpecularOverAlpha = true;
  40762. /**
  40763. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  40764. */
  40765. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  40766. /**
  40767. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  40768. */
  40769. _this._useRoughnessFromMetallicTextureAlpha = true;
  40770. /**
  40771. * Specifies if the metallic texture contains the roughness information in its green channel.
  40772. */
  40773. _this._useRoughnessFromMetallicTextureGreen = false;
  40774. /**
  40775. * Specifies if the metallic texture contains the metallness information in its blue channel.
  40776. */
  40777. _this._useMetallnessFromMetallicTextureBlue = false;
  40778. /**
  40779. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  40780. */
  40781. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  40782. /**
  40783. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  40784. */
  40785. _this._useAmbientInGrayScale = false;
  40786. /**
  40787. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  40788. * The material will try to infer what glossiness each pixel should be.
  40789. */
  40790. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  40791. /**
  40792. * BJS is using an harcoded light falloff based on a manually sets up range.
  40793. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  40794. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  40795. */
  40796. _this._usePhysicalLightFalloff = true;
  40797. /**
  40798. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  40799. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  40800. */
  40801. _this._useRadianceOverAlpha = true;
  40802. /**
  40803. * Allows using an object space normal map (instead of tangent space).
  40804. */
  40805. _this._useObjectSpaceNormalMap = false;
  40806. /**
  40807. * Allows using the bump map in parallax mode.
  40808. */
  40809. _this._useParallax = false;
  40810. /**
  40811. * Allows using the bump map in parallax occlusion mode.
  40812. */
  40813. _this._useParallaxOcclusion = false;
  40814. /**
  40815. * Controls the scale bias of the parallax mode.
  40816. */
  40817. _this._parallaxScaleBias = 0.05;
  40818. /**
  40819. * If sets to true, disables all the lights affecting the material.
  40820. */
  40821. _this._disableLighting = false;
  40822. /**
  40823. * Number of Simultaneous lights allowed on the material.
  40824. */
  40825. _this._maxSimultaneousLights = 4;
  40826. /**
  40827. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  40828. */
  40829. _this._invertNormalMapX = false;
  40830. /**
  40831. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  40832. */
  40833. _this._invertNormalMapY = false;
  40834. /**
  40835. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  40836. */
  40837. _this._twoSidedLighting = false;
  40838. /**
  40839. * Defines the alpha limits in alpha test mode.
  40840. */
  40841. _this._alphaCutOff = 0.4;
  40842. /**
  40843. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  40844. */
  40845. _this._forceAlphaTest = false;
  40846. /**
  40847. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  40848. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  40849. */
  40850. _this._useAlphaFresnel = false;
  40851. /**
  40852. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  40853. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  40854. */
  40855. _this._useLinearAlphaFresnel = false;
  40856. /**
  40857. * The transparency mode of the material.
  40858. */
  40859. _this._transparencyMode = null;
  40860. /**
  40861. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  40862. * from cos thetav and roughness:
  40863. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  40864. */
  40865. _this._environmentBRDFTexture = null;
  40866. /**
  40867. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  40868. */
  40869. _this._forceIrradianceInFragment = false;
  40870. /**
  40871. * Force normal to face away from face.
  40872. */
  40873. _this._forceNormalForward = false;
  40874. /**
  40875. * Stores the available render targets.
  40876. */
  40877. _this._renderTargets = new BABYLON.SmartArray(16);
  40878. /**
  40879. * Sets the global ambient color for the material used in lighting calculations.
  40880. */
  40881. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  40882. // Setup the default processing configuration to the scene.
  40883. _this._attachImageProcessingConfiguration(null);
  40884. _this.getRenderTargetTextures = function () {
  40885. _this._renderTargets.reset();
  40886. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  40887. _this._renderTargets.push(_this._reflectionTexture);
  40888. }
  40889. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  40890. _this._renderTargets.push(_this._refractionTexture);
  40891. }
  40892. return _this._renderTargets;
  40893. };
  40894. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  40895. return _this;
  40896. }
  40897. /**
  40898. * Attaches a new image processing configuration to the PBR Material.
  40899. * @param configuration
  40900. */
  40901. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  40902. var _this = this;
  40903. if (configuration === this._imageProcessingConfiguration) {
  40904. return;
  40905. }
  40906. // Detaches observer.
  40907. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  40908. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  40909. }
  40910. // Pick the scene configuration if needed.
  40911. if (!configuration) {
  40912. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  40913. }
  40914. else {
  40915. this._imageProcessingConfiguration = configuration;
  40916. }
  40917. // Attaches observer.
  40918. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  40919. _this._markAllSubMeshesAsImageProcessingDirty();
  40920. });
  40921. };
  40922. /**
  40923. * Gets the name of the material class.
  40924. */
  40925. PBRBaseMaterial.prototype.getClassName = function () {
  40926. return "PBRBaseMaterial";
  40927. };
  40928. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  40929. /**
  40930. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  40931. */
  40932. get: function () {
  40933. return this._useLogarithmicDepth;
  40934. },
  40935. /**
  40936. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  40937. */
  40938. set: function (value) {
  40939. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  40940. },
  40941. enumerable: true,
  40942. configurable: true
  40943. });
  40944. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  40945. /**
  40946. * Gets the current transparency mode.
  40947. */
  40948. get: function () {
  40949. return this._transparencyMode;
  40950. },
  40951. /**
  40952. * Sets the transparency mode of the material.
  40953. */
  40954. set: function (value) {
  40955. if (this._transparencyMode === value) {
  40956. return;
  40957. }
  40958. this._transparencyMode = value;
  40959. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  40960. this._markAllSubMeshesAsTexturesAndMiscDirty();
  40961. },
  40962. enumerable: true,
  40963. configurable: true
  40964. });
  40965. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  40966. /**
  40967. * Returns true if alpha blending should be disabled.
  40968. */
  40969. get: function () {
  40970. return (this._linkRefractionWithTransparency ||
  40971. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  40972. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  40973. },
  40974. enumerable: true,
  40975. configurable: true
  40976. });
  40977. /**
  40978. * Specifies whether or not this material should be rendered in alpha blend mode.
  40979. */
  40980. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  40981. if (this._disableAlphaBlending) {
  40982. return false;
  40983. }
  40984. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  40985. };
  40986. /**
  40987. * Specifies if the mesh will require alpha blending.
  40988. * @param mesh - BJS mesh.
  40989. */
  40990. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  40991. if (this._disableAlphaBlending) {
  40992. return false;
  40993. }
  40994. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  40995. };
  40996. /**
  40997. * Specifies whether or not this material should be rendered in alpha test mode.
  40998. */
  40999. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  41000. if (this._forceAlphaTest) {
  41001. return true;
  41002. }
  41003. if (this._linkRefractionWithTransparency) {
  41004. return false;
  41005. }
  41006. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  41007. };
  41008. /**
  41009. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  41010. */
  41011. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  41012. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  41013. };
  41014. /**
  41015. * Gets the texture used for the alpha test.
  41016. */
  41017. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  41018. return this._albedoTexture;
  41019. };
  41020. /**
  41021. * Specifies that the submesh is ready to be used.
  41022. * @param mesh - BJS mesh.
  41023. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  41024. * @param useInstances - Specifies that instances should be used.
  41025. * @returns - boolean indicating that the submesh is ready or not.
  41026. */
  41027. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  41028. if (subMesh.effect && this.isFrozen) {
  41029. if (this._wasPreviouslyReady) {
  41030. return true;
  41031. }
  41032. }
  41033. if (!subMesh._materialDefines) {
  41034. subMesh._materialDefines = new PBRMaterialDefines();
  41035. }
  41036. var defines = subMesh._materialDefines;
  41037. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  41038. if (defines._renderId === this.getScene().getRenderId()) {
  41039. return true;
  41040. }
  41041. }
  41042. var scene = this.getScene();
  41043. var engine = scene.getEngine();
  41044. if (defines._areTexturesDirty) {
  41045. if (scene.texturesEnabled) {
  41046. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  41047. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  41048. return false;
  41049. }
  41050. }
  41051. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  41052. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  41053. return false;
  41054. }
  41055. }
  41056. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  41057. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  41058. return false;
  41059. }
  41060. }
  41061. var reflectionTexture = this._getReflectionTexture();
  41062. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41063. if (!reflectionTexture.isReadyOrNotBlocking()) {
  41064. return false;
  41065. }
  41066. }
  41067. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  41068. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  41069. return false;
  41070. }
  41071. }
  41072. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  41073. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  41074. return false;
  41075. }
  41076. }
  41077. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  41078. if (this._metallicTexture) {
  41079. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  41080. return false;
  41081. }
  41082. }
  41083. else if (this._reflectivityTexture) {
  41084. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  41085. return false;
  41086. }
  41087. }
  41088. if (this._microSurfaceTexture) {
  41089. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  41090. return false;
  41091. }
  41092. }
  41093. }
  41094. if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  41095. // Bump texture cannot be not blocking.
  41096. if (!this._bumpTexture.isReady()) {
  41097. return false;
  41098. }
  41099. }
  41100. var refractionTexture = this._getRefractionTexture();
  41101. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  41102. if (!refractionTexture.isReadyOrNotBlocking()) {
  41103. return false;
  41104. }
  41105. }
  41106. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41107. // This is blocking.
  41108. if (!this._environmentBRDFTexture.isReady()) {
  41109. return false;
  41110. }
  41111. }
  41112. }
  41113. }
  41114. if (defines._areImageProcessingDirty) {
  41115. if (!this._imageProcessingConfiguration.isReady()) {
  41116. return false;
  41117. }
  41118. }
  41119. if (!engine.getCaps().standardDerivatives) {
  41120. var bufferMesh = null;
  41121. if (mesh.getClassName() === "InstancedMesh") {
  41122. bufferMesh = mesh.sourceMesh;
  41123. }
  41124. else if (mesh.getClassName() === "Mesh") {
  41125. bufferMesh = mesh;
  41126. }
  41127. if (bufferMesh && bufferMesh.geometry && bufferMesh.geometry.isReady() && !bufferMesh.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  41128. bufferMesh.createNormals(true);
  41129. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + bufferMesh.name);
  41130. }
  41131. }
  41132. var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);
  41133. if (effect) {
  41134. scene.resetCachedMaterial();
  41135. subMesh.setEffect(effect, defines);
  41136. this.buildUniformLayout();
  41137. }
  41138. if (!subMesh.effect || !subMesh.effect.isReady()) {
  41139. return false;
  41140. }
  41141. defines._renderId = scene.getRenderId();
  41142. this._wasPreviouslyReady = true;
  41143. return true;
  41144. };
  41145. /**
  41146. * Specifies if the material uses metallic roughness workflow.
  41147. * @returns boolean specifiying if the material uses metallic roughness workflow.
  41148. */
  41149. PBRBaseMaterial.prototype.isMetallicWorkflow = function () {
  41150. if (this._metallic != null || this._roughness != null || this._metallicTexture) {
  41151. return true;
  41152. }
  41153. return false;
  41154. };
  41155. PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) {
  41156. if (onCompiled === void 0) { onCompiled = null; }
  41157. if (onError === void 0) { onError = null; }
  41158. if (useInstances === void 0) { useInstances = null; }
  41159. if (useClipPlane === void 0) { useClipPlane = null; }
  41160. this._prepareDefines(mesh, defines, useInstances, useClipPlane);
  41161. if (!defines.isDirty) {
  41162. return null;
  41163. }
  41164. defines.markAsProcessed();
  41165. var scene = this.getScene();
  41166. var engine = scene.getEngine();
  41167. // Fallbacks
  41168. var fallbacks = new BABYLON.EffectFallbacks();
  41169. var fallbackRank = 0;
  41170. if (defines.USESPHERICALINVERTEX) {
  41171. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  41172. }
  41173. if (defines.FOG) {
  41174. fallbacks.addFallback(fallbackRank, "FOG");
  41175. }
  41176. if (defines.POINTSIZE) {
  41177. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  41178. }
  41179. if (defines.LOGARITHMICDEPTH) {
  41180. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  41181. }
  41182. if (defines.PARALLAX) {
  41183. fallbacks.addFallback(fallbackRank, "PARALLAX");
  41184. }
  41185. if (defines.PARALLAXOCCLUSION) {
  41186. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  41187. }
  41188. if (defines.ENVIRONMENTBRDF) {
  41189. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  41190. }
  41191. if (defines.TANGENT) {
  41192. fallbacks.addFallback(fallbackRank++, "TANGENT");
  41193. }
  41194. if (defines.BUMP) {
  41195. fallbacks.addFallback(fallbackRank++, "BUMP");
  41196. }
  41197. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  41198. if (defines.SPECULARTERM) {
  41199. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  41200. }
  41201. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  41202. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  41203. }
  41204. if (defines.LIGHTMAP) {
  41205. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  41206. }
  41207. if (defines.NORMAL) {
  41208. fallbacks.addFallback(fallbackRank++, "NORMAL");
  41209. }
  41210. if (defines.AMBIENT) {
  41211. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  41212. }
  41213. if (defines.EMISSIVE) {
  41214. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  41215. }
  41216. if (defines.VERTEXCOLOR) {
  41217. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  41218. }
  41219. if (defines.NUM_BONE_INFLUENCERS > 0) {
  41220. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  41221. }
  41222. if (defines.MORPHTARGETS) {
  41223. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  41224. }
  41225. //Attributes
  41226. var attribs = [BABYLON.VertexBuffer.PositionKind];
  41227. if (defines.NORMAL) {
  41228. attribs.push(BABYLON.VertexBuffer.NormalKind);
  41229. }
  41230. if (defines.TANGENT) {
  41231. attribs.push(BABYLON.VertexBuffer.TangentKind);
  41232. }
  41233. if (defines.UV1) {
  41234. attribs.push(BABYLON.VertexBuffer.UVKind);
  41235. }
  41236. if (defines.UV2) {
  41237. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  41238. }
  41239. if (defines.VERTEXCOLOR) {
  41240. attribs.push(BABYLON.VertexBuffer.ColorKind);
  41241. }
  41242. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  41243. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  41244. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  41245. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  41246. "vFogInfos", "vFogColor", "pointSize",
  41247. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos",
  41248. "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  41249. "mBones",
  41250. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "normalMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  41251. "vLightingIntensity",
  41252. "logarithmicDepthConstant",
  41253. "vSphericalX", "vSphericalY", "vSphericalZ",
  41254. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  41255. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  41256. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  41257. "vTangentSpaceParams"
  41258. ];
  41259. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  41260. "bumpSampler", "lightmapSampler", "opacitySampler",
  41261. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  41262. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  41263. "microSurfaceSampler", "environmentBrdfSampler"];
  41264. var uniformBuffers = ["Material", "Scene"];
  41265. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  41266. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  41267. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  41268. uniformsNames: uniforms,
  41269. uniformBuffersNames: uniformBuffers,
  41270. samplers: samplers,
  41271. defines: defines,
  41272. maxSimultaneousLights: this._maxSimultaneousLights
  41273. });
  41274. var join = defines.toString();
  41275. return engine.createEffect("pbr", {
  41276. attributes: attribs,
  41277. uniformsNames: uniforms,
  41278. uniformBuffersNames: uniformBuffers,
  41279. samplers: samplers,
  41280. defines: join,
  41281. fallbacks: fallbacks,
  41282. onCompiled: onCompiled,
  41283. onError: onError,
  41284. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  41285. }, engine);
  41286. };
  41287. PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) {
  41288. if (useInstances === void 0) { useInstances = null; }
  41289. if (useClipPlane === void 0) { useClipPlane = null; }
  41290. var scene = this.getScene();
  41291. var engine = scene.getEngine();
  41292. // Lights
  41293. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  41294. defines._needNormals = true;
  41295. // Textures
  41296. defines.METALLICWORKFLOW = this.isMetallicWorkflow();
  41297. if (defines._areTexturesDirty) {
  41298. defines._needUVs = false;
  41299. if (scene.texturesEnabled) {
  41300. if (scene.getEngine().getCaps().textureLOD) {
  41301. defines.LODBASEDMICROSFURACE = true;
  41302. }
  41303. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  41304. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  41305. }
  41306. else {
  41307. defines.ALBEDO = false;
  41308. }
  41309. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  41310. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  41311. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  41312. }
  41313. else {
  41314. defines.AMBIENT = false;
  41315. }
  41316. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  41317. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  41318. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  41319. }
  41320. else {
  41321. defines.OPACITY = false;
  41322. }
  41323. var reflectionTexture = this._getReflectionTexture();
  41324. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41325. defines.REFLECTION = true;
  41326. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  41327. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  41328. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  41329. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  41330. defines.INVERTCUBICMAP = true;
  41331. }
  41332. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  41333. switch (reflectionTexture.coordinatesMode) {
  41334. case BABYLON.Texture.CUBIC_MODE:
  41335. case BABYLON.Texture.INVCUBIC_MODE:
  41336. defines.REFLECTIONMAP_CUBIC = true;
  41337. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
  41338. break;
  41339. case BABYLON.Texture.EXPLICIT_MODE:
  41340. defines.REFLECTIONMAP_EXPLICIT = true;
  41341. break;
  41342. case BABYLON.Texture.PLANAR_MODE:
  41343. defines.REFLECTIONMAP_PLANAR = true;
  41344. break;
  41345. case BABYLON.Texture.PROJECTION_MODE:
  41346. defines.REFLECTIONMAP_PROJECTION = true;
  41347. break;
  41348. case BABYLON.Texture.SKYBOX_MODE:
  41349. defines.REFLECTIONMAP_SKYBOX = true;
  41350. break;
  41351. case BABYLON.Texture.SPHERICAL_MODE:
  41352. defines.REFLECTIONMAP_SPHERICAL = true;
  41353. break;
  41354. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  41355. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  41356. break;
  41357. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  41358. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  41359. break;
  41360. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  41361. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  41362. break;
  41363. }
  41364. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  41365. if (reflectionTexture.sphericalPolynomial) {
  41366. defines.USESPHERICALFROMREFLECTIONMAP = true;
  41367. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  41368. defines.USESPHERICALINVERTEX = false;
  41369. }
  41370. else {
  41371. defines.USESPHERICALINVERTEX = true;
  41372. }
  41373. }
  41374. }
  41375. }
  41376. else {
  41377. defines.REFLECTION = false;
  41378. defines.REFLECTIONMAP_3D = false;
  41379. defines.REFLECTIONMAP_SPHERICAL = false;
  41380. defines.REFLECTIONMAP_PLANAR = false;
  41381. defines.REFLECTIONMAP_CUBIC = false;
  41382. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  41383. defines.REFLECTIONMAP_PROJECTION = false;
  41384. defines.REFLECTIONMAP_SKYBOX = false;
  41385. defines.REFLECTIONMAP_EXPLICIT = false;
  41386. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  41387. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  41388. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  41389. defines.INVERTCUBICMAP = false;
  41390. defines.USESPHERICALFROMREFLECTIONMAP = false;
  41391. defines.USESPHERICALINVERTEX = false;
  41392. defines.REFLECTIONMAP_OPPOSITEZ = false;
  41393. defines.LODINREFLECTIONALPHA = false;
  41394. defines.GAMMAREFLECTION = false;
  41395. }
  41396. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  41397. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  41398. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  41399. }
  41400. else {
  41401. defines.LIGHTMAP = false;
  41402. }
  41403. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  41404. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  41405. }
  41406. else {
  41407. defines.EMISSIVE = false;
  41408. }
  41409. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  41410. if (this._metallicTexture) {
  41411. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  41412. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  41413. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  41414. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  41415. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  41416. }
  41417. else if (this._reflectivityTexture) {
  41418. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  41419. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  41420. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  41421. }
  41422. else {
  41423. defines.REFLECTIVITY = false;
  41424. }
  41425. if (this._microSurfaceTexture) {
  41426. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  41427. }
  41428. else {
  41429. defines.MICROSURFACEMAP = false;
  41430. }
  41431. }
  41432. else {
  41433. defines.REFLECTIVITY = false;
  41434. defines.MICROSURFACEMAP = false;
  41435. }
  41436. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  41437. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  41438. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  41439. defines.PARALLAX = true;
  41440. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  41441. }
  41442. else {
  41443. defines.PARALLAX = false;
  41444. }
  41445. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  41446. }
  41447. else {
  41448. defines.BUMP = false;
  41449. }
  41450. var refractionTexture = this._getRefractionTexture();
  41451. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  41452. defines.REFRACTION = true;
  41453. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  41454. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  41455. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  41456. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  41457. if (this._linkRefractionWithTransparency) {
  41458. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  41459. }
  41460. }
  41461. else {
  41462. defines.REFRACTION = false;
  41463. }
  41464. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41465. defines.ENVIRONMENTBRDF = true;
  41466. }
  41467. else {
  41468. defines.ENVIRONMENTBRDF = false;
  41469. }
  41470. if (this._shouldUseAlphaFromAlbedoTexture()) {
  41471. defines.ALPHAFROMALBEDO = true;
  41472. }
  41473. else {
  41474. defines.ALPHAFROMALBEDO = false;
  41475. }
  41476. }
  41477. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  41478. defines.USEPHYSICALLIGHTFALLOFF = this._usePhysicalLightFalloff;
  41479. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  41480. if (!this.backFaceCulling && this._twoSidedLighting) {
  41481. defines.TWOSIDEDLIGHTING = true;
  41482. }
  41483. else {
  41484. defines.TWOSIDEDLIGHTING = false;
  41485. }
  41486. defines.ALPHATESTVALUE = this._alphaCutOff;
  41487. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  41488. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  41489. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  41490. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  41491. }
  41492. if (defines._areImageProcessingDirty) {
  41493. this._imageProcessingConfiguration.prepareDefines(defines);
  41494. }
  41495. defines.FORCENORMALFORWARD = this._forceNormalForward;
  41496. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  41497. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  41498. // Misc.
  41499. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  41500. // Values that need to be evaluated on every frame
  41501. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);
  41502. // Attribs
  41503. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE);
  41504. };
  41505. /**
  41506. * Force shader compilation
  41507. */
  41508. PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {
  41509. var _this = this;
  41510. var localOptions = __assign({ clipPlane: false }, options);
  41511. var defines = new PBRMaterialDefines();
  41512. var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane);
  41513. if (effect.isReady()) {
  41514. if (onCompiled) {
  41515. onCompiled(this);
  41516. }
  41517. }
  41518. else {
  41519. effect.onCompileObservable.add(function () {
  41520. if (onCompiled) {
  41521. onCompiled(_this);
  41522. }
  41523. });
  41524. }
  41525. };
  41526. /**
  41527. * Initializes the uniform buffer layout for the shader.
  41528. */
  41529. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  41530. // Order is important !
  41531. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  41532. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  41533. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  41534. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  41535. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  41536. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  41537. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  41538. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  41539. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  41540. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  41541. this._uniformBuffer.addUniform("vReflectionSize", 3);
  41542. this._uniformBuffer.addUniform("vBumpInfos", 3);
  41543. this._uniformBuffer.addUniform("albedoMatrix", 16);
  41544. this._uniformBuffer.addUniform("ambientMatrix", 16);
  41545. this._uniformBuffer.addUniform("opacityMatrix", 16);
  41546. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  41547. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  41548. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  41549. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  41550. this._uniformBuffer.addUniform("bumpMatrix", 16);
  41551. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  41552. this._uniformBuffer.addUniform("refractionMatrix", 16);
  41553. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  41554. this._uniformBuffer.addUniform("vReflectionColor", 3);
  41555. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  41556. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  41557. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  41558. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  41559. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  41560. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  41561. this._uniformBuffer.addUniform("pointSize", 1);
  41562. this._uniformBuffer.create();
  41563. };
  41564. /**
  41565. * Unbinds the textures.
  41566. */
  41567. PBRBaseMaterial.prototype.unbind = function () {
  41568. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  41569. this._uniformBuffer.setTexture("reflectionSampler", null);
  41570. }
  41571. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  41572. this._uniformBuffer.setTexture("refractionSampler", null);
  41573. }
  41574. _super.prototype.unbind.call(this);
  41575. };
  41576. /**
  41577. * Binds the submesh data.
  41578. * @param world - The world matrix.
  41579. * @param mesh - The BJS mesh.
  41580. * @param subMesh - A submesh of the BJS mesh.
  41581. */
  41582. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  41583. var scene = this.getScene();
  41584. var defines = subMesh._materialDefines;
  41585. if (!defines) {
  41586. return;
  41587. }
  41588. var effect = subMesh.effect;
  41589. if (!effect) {
  41590. return;
  41591. }
  41592. this._activeEffect = effect;
  41593. // Matrices
  41594. this.bindOnlyWorldMatrix(world);
  41595. // Normal Matrix
  41596. if (defines.OBJECTSPACE_NORMALMAP) {
  41597. world.toNormalMatrix(this._normalMatrix);
  41598. this.bindOnlyNormalMatrix(this._normalMatrix);
  41599. }
  41600. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  41601. // Bones
  41602. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  41603. var reflectionTexture = null;
  41604. if (mustRebind) {
  41605. this._uniformBuffer.bindToEffect(effect, "Material");
  41606. this.bindViewProjection(effect);
  41607. reflectionTexture = this._getReflectionTexture();
  41608. var refractionTexture = this._getRefractionTexture();
  41609. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  41610. // Texture uniforms
  41611. if (scene.texturesEnabled) {
  41612. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  41613. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  41614. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  41615. }
  41616. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  41617. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  41618. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  41619. }
  41620. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  41621. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  41622. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  41623. }
  41624. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41625. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  41626. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  41627. if (reflectionTexture.boundingBoxSize) {
  41628. var cubeTexture = reflectionTexture;
  41629. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  41630. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  41631. }
  41632. var polynomials = reflectionTexture.sphericalPolynomial;
  41633. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  41634. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  41635. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  41636. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  41637. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  41638. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  41639. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  41640. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  41641. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  41642. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  41643. }
  41644. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  41645. }
  41646. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  41647. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  41648. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  41649. }
  41650. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  41651. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  41652. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  41653. }
  41654. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  41655. if (this._metallicTexture) {
  41656. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  41657. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  41658. }
  41659. else if (this._reflectivityTexture) {
  41660. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  41661. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  41662. }
  41663. if (this._microSurfaceTexture) {
  41664. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  41665. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  41666. }
  41667. }
  41668. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  41669. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  41670. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  41671. if (scene._mirroredCameraPosition) {
  41672. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  41673. }
  41674. else {
  41675. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  41676. }
  41677. }
  41678. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  41679. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  41680. var depth = 1.0;
  41681. if (!refractionTexture.isCube) {
  41682. if (refractionTexture.depth) {
  41683. depth = refractionTexture.depth;
  41684. }
  41685. }
  41686. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  41687. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  41688. }
  41689. }
  41690. // Point size
  41691. if (this.pointsCloud) {
  41692. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  41693. }
  41694. // Colors
  41695. if (defines.METALLICWORKFLOW) {
  41696. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  41697. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  41698. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  41699. }
  41700. else {
  41701. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  41702. }
  41703. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  41704. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  41705. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  41706. // Misc
  41707. this._lightingInfos.x = this._directIntensity;
  41708. this._lightingInfos.y = this._emissiveIntensity;
  41709. this._lightingInfos.z = this._environmentIntensity;
  41710. this._lightingInfos.w = this._specularIntensity;
  41711. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  41712. }
  41713. // Textures
  41714. if (scene.texturesEnabled) {
  41715. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  41716. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  41717. }
  41718. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  41719. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  41720. }
  41721. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  41722. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  41723. }
  41724. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41725. if (defines.LODBASEDMICROSFURACE) {
  41726. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  41727. }
  41728. else {
  41729. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  41730. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  41731. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  41732. }
  41733. }
  41734. if (defines.ENVIRONMENTBRDF) {
  41735. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  41736. }
  41737. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  41738. if (defines.LODBASEDMICROSFURACE) {
  41739. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  41740. }
  41741. else {
  41742. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  41743. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  41744. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  41745. }
  41746. }
  41747. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  41748. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  41749. }
  41750. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  41751. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  41752. }
  41753. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  41754. if (this._metallicTexture) {
  41755. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  41756. }
  41757. else if (this._reflectivityTexture) {
  41758. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  41759. }
  41760. if (this._microSurfaceTexture) {
  41761. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  41762. }
  41763. }
  41764. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  41765. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  41766. }
  41767. }
  41768. // Clip plane
  41769. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  41770. // Colors
  41771. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  41772. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  41773. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  41774. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  41775. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  41776. }
  41777. if (mustRebind || !this.isFrozen) {
  41778. // Lights
  41779. if (scene.lightsEnabled && !this._disableLighting) {
  41780. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  41781. }
  41782. // View
  41783. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  41784. this.bindView(effect);
  41785. }
  41786. // Fog
  41787. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  41788. // Morph targets
  41789. if (defines.NUM_MORPH_INFLUENCERS) {
  41790. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  41791. }
  41792. // image processing
  41793. this._imageProcessingConfiguration.bind(this._activeEffect);
  41794. // Log. depth
  41795. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  41796. }
  41797. this._uniformBuffer.update();
  41798. this._afterBind(mesh);
  41799. };
  41800. /**
  41801. * Returns the animatable textures.
  41802. * @returns - Array of animatable textures.
  41803. */
  41804. PBRBaseMaterial.prototype.getAnimatables = function () {
  41805. var results = [];
  41806. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  41807. results.push(this._albedoTexture);
  41808. }
  41809. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  41810. results.push(this._ambientTexture);
  41811. }
  41812. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  41813. results.push(this._opacityTexture);
  41814. }
  41815. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  41816. results.push(this._reflectionTexture);
  41817. }
  41818. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  41819. results.push(this._emissiveTexture);
  41820. }
  41821. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  41822. results.push(this._metallicTexture);
  41823. }
  41824. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  41825. results.push(this._reflectivityTexture);
  41826. }
  41827. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  41828. results.push(this._bumpTexture);
  41829. }
  41830. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  41831. results.push(this._lightmapTexture);
  41832. }
  41833. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  41834. results.push(this._refractionTexture);
  41835. }
  41836. return results;
  41837. };
  41838. /**
  41839. * Returns the texture used for reflections.
  41840. * @returns - Reflection texture if present. Otherwise, returns the environment texture.
  41841. */
  41842. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  41843. if (this._reflectionTexture) {
  41844. return this._reflectionTexture;
  41845. }
  41846. return this.getScene().environmentTexture;
  41847. };
  41848. /**
  41849. * Returns the texture used for refraction or null if none is used.
  41850. * @returns - Refection texture if present. If no refraction texture and refraction
  41851. * is linked with transparency, returns environment texture. Otherwise, returns null.
  41852. */
  41853. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  41854. if (this._refractionTexture) {
  41855. return this._refractionTexture;
  41856. }
  41857. if (this._linkRefractionWithTransparency) {
  41858. return this.getScene().environmentTexture;
  41859. }
  41860. return null;
  41861. };
  41862. /**
  41863. * Disposes the resources of the material.
  41864. * @param forceDisposeEffect - Forces the disposal of effects.
  41865. * @param forceDisposeTextures - Forces the disposal of all textures.
  41866. */
  41867. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  41868. if (forceDisposeTextures) {
  41869. if (this._albedoTexture) {
  41870. this._albedoTexture.dispose();
  41871. }
  41872. if (this._ambientTexture) {
  41873. this._ambientTexture.dispose();
  41874. }
  41875. if (this._opacityTexture) {
  41876. this._opacityTexture.dispose();
  41877. }
  41878. if (this._reflectionTexture) {
  41879. this._reflectionTexture.dispose();
  41880. }
  41881. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  41882. this._environmentBRDFTexture.dispose();
  41883. }
  41884. if (this._emissiveTexture) {
  41885. this._emissiveTexture.dispose();
  41886. }
  41887. if (this._metallicTexture) {
  41888. this._metallicTexture.dispose();
  41889. }
  41890. if (this._reflectivityTexture) {
  41891. this._reflectivityTexture.dispose();
  41892. }
  41893. if (this._bumpTexture) {
  41894. this._bumpTexture.dispose();
  41895. }
  41896. if (this._lightmapTexture) {
  41897. this._lightmapTexture.dispose();
  41898. }
  41899. if (this._refractionTexture) {
  41900. this._refractionTexture.dispose();
  41901. }
  41902. }
  41903. this._renderTargets.dispose();
  41904. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  41905. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  41906. }
  41907. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  41908. };
  41909. /**
  41910. * Stores the reflectivity values based on metallic roughness workflow.
  41911. */
  41912. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  41913. __decorate([
  41914. BABYLON.serializeAsImageProcessingConfiguration()
  41915. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  41916. __decorate([
  41917. BABYLON.serialize()
  41918. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  41919. __decorate([
  41920. BABYLON.serialize()
  41921. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  41922. return PBRBaseMaterial;
  41923. }(BABYLON.PushMaterial));
  41924. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  41925. })(BABYLON || (BABYLON = {}));
  41926. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  41927. var BABYLON;
  41928. (function (BABYLON) {
  41929. /**
  41930. * The Physically based simple base material of BJS.
  41931. *
  41932. * This enables better naming and convention enforcements on top of the pbrMaterial.
  41933. * It is used as the base class for both the specGloss and metalRough conventions.
  41934. */
  41935. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  41936. __extends(PBRBaseSimpleMaterial, _super);
  41937. /**
  41938. * Instantiates a new PBRMaterial instance.
  41939. *
  41940. * @param name The material name
  41941. * @param scene The scene the material will be use in.
  41942. */
  41943. function PBRBaseSimpleMaterial(name, scene) {
  41944. var _this = _super.call(this, name, scene) || this;
  41945. /**
  41946. * Number of Simultaneous lights allowed on the material.
  41947. */
  41948. _this.maxSimultaneousLights = 4;
  41949. /**
  41950. * If sets to true, disables all the lights affecting the material.
  41951. */
  41952. _this.disableLighting = false;
  41953. /**
  41954. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  41955. */
  41956. _this.invertNormalMapX = false;
  41957. /**
  41958. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  41959. */
  41960. _this.invertNormalMapY = false;
  41961. /**
  41962. * Emissivie color used to self-illuminate the model.
  41963. */
  41964. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  41965. /**
  41966. * Occlusion Channel Strenght.
  41967. */
  41968. _this.occlusionStrength = 1.0;
  41969. _this.useLightmapAsShadowmap = false;
  41970. _this._useAlphaFromAlbedoTexture = true;
  41971. _this._useAmbientInGrayScale = true;
  41972. return _this;
  41973. }
  41974. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  41975. /**
  41976. * Gets the current double sided mode.
  41977. */
  41978. get: function () {
  41979. return this._twoSidedLighting;
  41980. },
  41981. /**
  41982. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  41983. */
  41984. set: function (value) {
  41985. if (this._twoSidedLighting === value) {
  41986. return;
  41987. }
  41988. this._twoSidedLighting = value;
  41989. this.backFaceCulling = !value;
  41990. this._markAllSubMeshesAsTexturesDirty();
  41991. },
  41992. enumerable: true,
  41993. configurable: true
  41994. });
  41995. /**
  41996. * Return the active textures of the material.
  41997. */
  41998. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  41999. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42000. if (this.environmentTexture) {
  42001. activeTextures.push(this.environmentTexture);
  42002. }
  42003. if (this.normalTexture) {
  42004. activeTextures.push(this.normalTexture);
  42005. }
  42006. if (this.emissiveTexture) {
  42007. activeTextures.push(this.emissiveTexture);
  42008. }
  42009. if (this.occlusionTexture) {
  42010. activeTextures.push(this.occlusionTexture);
  42011. }
  42012. if (this.lightmapTexture) {
  42013. activeTextures.push(this.lightmapTexture);
  42014. }
  42015. return activeTextures;
  42016. };
  42017. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  42018. if (_super.prototype.hasTexture.call(this, texture)) {
  42019. return true;
  42020. }
  42021. if (this.lightmapTexture === texture) {
  42022. return true;
  42023. }
  42024. return false;
  42025. };
  42026. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  42027. return "PBRBaseSimpleMaterial";
  42028. };
  42029. __decorate([
  42030. BABYLON.serialize(),
  42031. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  42032. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  42033. __decorate([
  42034. BABYLON.serialize(),
  42035. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  42036. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  42037. __decorate([
  42038. BABYLON.serializeAsTexture(),
  42039. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  42040. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  42041. __decorate([
  42042. BABYLON.serialize(),
  42043. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42044. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  42045. __decorate([
  42046. BABYLON.serialize(),
  42047. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42048. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  42049. __decorate([
  42050. BABYLON.serializeAsTexture(),
  42051. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  42052. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  42053. __decorate([
  42054. BABYLON.serializeAsColor3("emissive"),
  42055. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42056. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  42057. __decorate([
  42058. BABYLON.serializeAsTexture(),
  42059. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42060. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  42061. __decorate([
  42062. BABYLON.serialize(),
  42063. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  42064. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  42065. __decorate([
  42066. BABYLON.serializeAsTexture(),
  42067. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  42068. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  42069. __decorate([
  42070. BABYLON.serialize(),
  42071. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  42072. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  42073. __decorate([
  42074. BABYLON.serialize()
  42075. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  42076. __decorate([
  42077. BABYLON.serializeAsTexture(),
  42078. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  42079. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  42080. __decorate([
  42081. BABYLON.serialize(),
  42082. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42083. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  42084. return PBRBaseSimpleMaterial;
  42085. }(BABYLON.PBRBaseMaterial));
  42086. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  42087. })(BABYLON || (BABYLON = {}));
  42088. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  42089. var BABYLON;
  42090. (function (BABYLON) {
  42091. /**
  42092. * The Physically based material of BJS.
  42093. *
  42094. * This offers the main features of a standard PBR material.
  42095. * For more information, please refer to the documentation :
  42096. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  42097. */
  42098. var PBRMaterial = /** @class */ (function (_super) {
  42099. __extends(PBRMaterial, _super);
  42100. /**
  42101. * Instantiates a new PBRMaterial instance.
  42102. *
  42103. * @param name The material name
  42104. * @param scene The scene the material will be use in.
  42105. */
  42106. function PBRMaterial(name, scene) {
  42107. var _this = _super.call(this, name, scene) || this;
  42108. /**
  42109. * Intensity of the direct lights e.g. the four lights available in your scene.
  42110. * This impacts both the direct diffuse and specular highlights.
  42111. */
  42112. _this.directIntensity = 1.0;
  42113. /**
  42114. * Intensity of the emissive part of the material.
  42115. * This helps controlling the emissive effect without modifying the emissive color.
  42116. */
  42117. _this.emissiveIntensity = 1.0;
  42118. /**
  42119. * Intensity of the environment e.g. how much the environment will light the object
  42120. * either through harmonics for rough material or through the refelction for shiny ones.
  42121. */
  42122. _this.environmentIntensity = 1.0;
  42123. /**
  42124. * This is a special control allowing the reduction of the specular highlights coming from the
  42125. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  42126. */
  42127. _this.specularIntensity = 1.0;
  42128. /**
  42129. * Debug Control allowing disabling the bump map on this material.
  42130. */
  42131. _this.disableBumpMap = false;
  42132. /**
  42133. * AKA Occlusion Texture Intensity in other nomenclature.
  42134. */
  42135. _this.ambientTextureStrength = 1.0;
  42136. /**
  42137. * The color of a material in ambient lighting.
  42138. */
  42139. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  42140. /**
  42141. * AKA Diffuse Color in other nomenclature.
  42142. */
  42143. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  42144. /**
  42145. * AKA Specular Color in other nomenclature.
  42146. */
  42147. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  42148. /**
  42149. * The color reflected from the material.
  42150. */
  42151. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  42152. /**
  42153. * The color emitted from the material.
  42154. */
  42155. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  42156. /**
  42157. * AKA Glossiness in other nomenclature.
  42158. */
  42159. _this.microSurface = 1.0;
  42160. /**
  42161. * source material index of refraction (IOR)' / 'destination material IOR.
  42162. */
  42163. _this.indexOfRefraction = 0.66;
  42164. /**
  42165. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  42166. */
  42167. _this.invertRefractionY = false;
  42168. /**
  42169. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  42170. * Materials half opaque for instance using refraction could benefit from this control.
  42171. */
  42172. _this.linkRefractionWithTransparency = false;
  42173. _this.useLightmapAsShadowmap = false;
  42174. /**
  42175. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  42176. */
  42177. _this.useAlphaFromAlbedoTexture = false;
  42178. /**
  42179. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  42180. */
  42181. _this.forceAlphaTest = false;
  42182. /**
  42183. * Defines the alpha limits in alpha test mode.
  42184. */
  42185. _this.alphaCutOff = 0.4;
  42186. /**
  42187. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  42188. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  42189. */
  42190. _this.useSpecularOverAlpha = true;
  42191. /**
  42192. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  42193. */
  42194. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  42195. /**
  42196. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  42197. */
  42198. _this.useRoughnessFromMetallicTextureAlpha = true;
  42199. /**
  42200. * Specifies if the metallic texture contains the roughness information in its green channel.
  42201. */
  42202. _this.useRoughnessFromMetallicTextureGreen = false;
  42203. /**
  42204. * Specifies if the metallic texture contains the metallness information in its blue channel.
  42205. */
  42206. _this.useMetallnessFromMetallicTextureBlue = false;
  42207. /**
  42208. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  42209. */
  42210. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  42211. /**
  42212. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  42213. */
  42214. _this.useAmbientInGrayScale = false;
  42215. /**
  42216. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  42217. * The material will try to infer what glossiness each pixel should be.
  42218. */
  42219. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  42220. /**
  42221. * BJS is using an harcoded light falloff based on a manually sets up range.
  42222. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  42223. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  42224. */
  42225. _this.usePhysicalLightFalloff = true;
  42226. /**
  42227. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  42228. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  42229. */
  42230. _this.useRadianceOverAlpha = true;
  42231. /**
  42232. * Allows using an object space normal map (instead of tangent space).
  42233. */
  42234. _this.useObjectSpaceNormalMap = false;
  42235. /**
  42236. * Allows using the bump map in parallax mode.
  42237. */
  42238. _this.useParallax = false;
  42239. /**
  42240. * Allows using the bump map in parallax occlusion mode.
  42241. */
  42242. _this.useParallaxOcclusion = false;
  42243. /**
  42244. * Controls the scale bias of the parallax mode.
  42245. */
  42246. _this.parallaxScaleBias = 0.05;
  42247. /**
  42248. * If sets to true, disables all the lights affecting the material.
  42249. */
  42250. _this.disableLighting = false;
  42251. /**
  42252. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  42253. */
  42254. _this.forceIrradianceInFragment = false;
  42255. /**
  42256. * Number of Simultaneous lights allowed on the material.
  42257. */
  42258. _this.maxSimultaneousLights = 4;
  42259. /**
  42260. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  42261. */
  42262. _this.invertNormalMapX = false;
  42263. /**
  42264. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  42265. */
  42266. _this.invertNormalMapY = false;
  42267. /**
  42268. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  42269. */
  42270. _this.twoSidedLighting = false;
  42271. /**
  42272. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  42273. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  42274. */
  42275. _this.useAlphaFresnel = false;
  42276. /**
  42277. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  42278. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  42279. */
  42280. _this.useLinearAlphaFresnel = false;
  42281. /**
  42282. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  42283. * And/Or occlude the blended part.
  42284. */
  42285. _this.environmentBRDFTexture = null;
  42286. /**
  42287. * Force normal to face away from face.
  42288. */
  42289. _this.forceNormalForward = false;
  42290. /**
  42291. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  42292. * makes the reflect vector face the model (under horizon).
  42293. */
  42294. _this.useHorizonOcclusion = true;
  42295. /**
  42296. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  42297. * too much the area relying on ambient texture to define their ambient occlusion.
  42298. */
  42299. _this.useRadianceOcclusion = true;
  42300. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  42301. return _this;
  42302. }
  42303. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  42304. /**
  42305. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  42306. */
  42307. get: function () {
  42308. return this._PBRMATERIAL_OPAQUE;
  42309. },
  42310. enumerable: true,
  42311. configurable: true
  42312. });
  42313. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  42314. /**
  42315. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  42316. */
  42317. get: function () {
  42318. return this._PBRMATERIAL_ALPHATEST;
  42319. },
  42320. enumerable: true,
  42321. configurable: true
  42322. });
  42323. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  42324. /**
  42325. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  42326. */
  42327. get: function () {
  42328. return this._PBRMATERIAL_ALPHABLEND;
  42329. },
  42330. enumerable: true,
  42331. configurable: true
  42332. });
  42333. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  42334. /**
  42335. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  42336. * They are also discarded below the alpha cutoff threshold to improve performances.
  42337. */
  42338. get: function () {
  42339. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  42340. },
  42341. enumerable: true,
  42342. configurable: true
  42343. });
  42344. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  42345. /**
  42346. * Gets the image processing configuration used either in this material.
  42347. */
  42348. get: function () {
  42349. return this._imageProcessingConfiguration;
  42350. },
  42351. /**
  42352. * Sets the Default image processing configuration used either in the this material.
  42353. *
  42354. * If sets to null, the scene one is in use.
  42355. */
  42356. set: function (value) {
  42357. this._attachImageProcessingConfiguration(value);
  42358. // Ensure the effect will be rebuilt.
  42359. this._markAllSubMeshesAsTexturesDirty();
  42360. },
  42361. enumerable: true,
  42362. configurable: true
  42363. });
  42364. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  42365. /**
  42366. * Gets wether the color curves effect is enabled.
  42367. */
  42368. get: function () {
  42369. return this.imageProcessingConfiguration.colorCurvesEnabled;
  42370. },
  42371. /**
  42372. * Sets wether the color curves effect is enabled.
  42373. */
  42374. set: function (value) {
  42375. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  42376. },
  42377. enumerable: true,
  42378. configurable: true
  42379. });
  42380. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  42381. /**
  42382. * Gets wether the color grading effect is enabled.
  42383. */
  42384. get: function () {
  42385. return this.imageProcessingConfiguration.colorGradingEnabled;
  42386. },
  42387. /**
  42388. * Gets wether the color grading effect is enabled.
  42389. */
  42390. set: function (value) {
  42391. this.imageProcessingConfiguration.colorGradingEnabled = value;
  42392. },
  42393. enumerable: true,
  42394. configurable: true
  42395. });
  42396. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  42397. /**
  42398. * Gets wether tonemapping is enabled or not.
  42399. */
  42400. get: function () {
  42401. return this._imageProcessingConfiguration.toneMappingEnabled;
  42402. },
  42403. /**
  42404. * Sets wether tonemapping is enabled or not
  42405. */
  42406. set: function (value) {
  42407. this._imageProcessingConfiguration.toneMappingEnabled = value;
  42408. },
  42409. enumerable: true,
  42410. configurable: true
  42411. });
  42412. ;
  42413. ;
  42414. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  42415. /**
  42416. * The camera exposure used on this material.
  42417. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  42418. * This corresponds to a photographic exposure.
  42419. */
  42420. get: function () {
  42421. return this._imageProcessingConfiguration.exposure;
  42422. },
  42423. /**
  42424. * The camera exposure used on this material.
  42425. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  42426. * This corresponds to a photographic exposure.
  42427. */
  42428. set: function (value) {
  42429. this._imageProcessingConfiguration.exposure = value;
  42430. },
  42431. enumerable: true,
  42432. configurable: true
  42433. });
  42434. ;
  42435. ;
  42436. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  42437. /**
  42438. * Gets The camera contrast used on this material.
  42439. */
  42440. get: function () {
  42441. return this._imageProcessingConfiguration.contrast;
  42442. },
  42443. /**
  42444. * Sets The camera contrast used on this material.
  42445. */
  42446. set: function (value) {
  42447. this._imageProcessingConfiguration.contrast = value;
  42448. },
  42449. enumerable: true,
  42450. configurable: true
  42451. });
  42452. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  42453. /**
  42454. * Gets the Color Grading 2D Lookup Texture.
  42455. */
  42456. get: function () {
  42457. return this._imageProcessingConfiguration.colorGradingTexture;
  42458. },
  42459. /**
  42460. * Sets the Color Grading 2D Lookup Texture.
  42461. */
  42462. set: function (value) {
  42463. this._imageProcessingConfiguration.colorGradingTexture = value;
  42464. },
  42465. enumerable: true,
  42466. configurable: true
  42467. });
  42468. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  42469. /**
  42470. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42471. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42472. * 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;
  42473. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42474. */
  42475. get: function () {
  42476. return this._imageProcessingConfiguration.colorCurves;
  42477. },
  42478. /**
  42479. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42480. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42481. * 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;
  42482. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42483. */
  42484. set: function (value) {
  42485. this._imageProcessingConfiguration.colorCurves = value;
  42486. },
  42487. enumerable: true,
  42488. configurable: true
  42489. });
  42490. /**
  42491. * Returns the name of this material class.
  42492. */
  42493. PBRMaterial.prototype.getClassName = function () {
  42494. return "PBRMaterial";
  42495. };
  42496. /**
  42497. * Returns an array of the actively used textures.
  42498. * @returns - Array of BaseTextures
  42499. */
  42500. PBRMaterial.prototype.getActiveTextures = function () {
  42501. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42502. if (this._albedoTexture) {
  42503. activeTextures.push(this._albedoTexture);
  42504. }
  42505. if (this._ambientTexture) {
  42506. activeTextures.push(this._ambientTexture);
  42507. }
  42508. if (this._opacityTexture) {
  42509. activeTextures.push(this._opacityTexture);
  42510. }
  42511. if (this._reflectionTexture) {
  42512. activeTextures.push(this._reflectionTexture);
  42513. }
  42514. if (this._emissiveTexture) {
  42515. activeTextures.push(this._emissiveTexture);
  42516. }
  42517. if (this._reflectivityTexture) {
  42518. activeTextures.push(this._reflectivityTexture);
  42519. }
  42520. if (this._metallicTexture) {
  42521. activeTextures.push(this._metallicTexture);
  42522. }
  42523. if (this._microSurfaceTexture) {
  42524. activeTextures.push(this._microSurfaceTexture);
  42525. }
  42526. if (this._bumpTexture) {
  42527. activeTextures.push(this._bumpTexture);
  42528. }
  42529. if (this._lightmapTexture) {
  42530. activeTextures.push(this._lightmapTexture);
  42531. }
  42532. if (this._refractionTexture) {
  42533. activeTextures.push(this._refractionTexture);
  42534. }
  42535. return activeTextures;
  42536. };
  42537. /**
  42538. * Checks to see if a texture is used in the material.
  42539. * @param texture - Base texture to use.
  42540. * @returns - Boolean specifying if a texture is used in the material.
  42541. */
  42542. PBRMaterial.prototype.hasTexture = function (texture) {
  42543. if (_super.prototype.hasTexture.call(this, texture)) {
  42544. return true;
  42545. }
  42546. if (this._albedoTexture === texture) {
  42547. return true;
  42548. }
  42549. if (this._ambientTexture === texture) {
  42550. return true;
  42551. }
  42552. if (this._opacityTexture === texture) {
  42553. return true;
  42554. }
  42555. if (this._reflectionTexture === texture) {
  42556. return true;
  42557. }
  42558. if (this._reflectivityTexture === texture) {
  42559. return true;
  42560. }
  42561. if (this._metallicTexture === texture) {
  42562. return true;
  42563. }
  42564. if (this._microSurfaceTexture === texture) {
  42565. return true;
  42566. }
  42567. if (this._bumpTexture === texture) {
  42568. return true;
  42569. }
  42570. if (this._lightmapTexture === texture) {
  42571. return true;
  42572. }
  42573. if (this._refractionTexture === texture) {
  42574. return true;
  42575. }
  42576. return false;
  42577. };
  42578. /**
  42579. * Makes a duplicate of the current material.
  42580. * @param name - name to use for the new material.
  42581. */
  42582. PBRMaterial.prototype.clone = function (name) {
  42583. var _this = this;
  42584. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  42585. clone.id = name;
  42586. clone.name = name;
  42587. return clone;
  42588. };
  42589. /**
  42590. * Serializes this PBR Material.
  42591. * @returns - An object with the serialized material.
  42592. */
  42593. PBRMaterial.prototype.serialize = function () {
  42594. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  42595. serializationObject.customType = "BABYLON.PBRMaterial";
  42596. return serializationObject;
  42597. };
  42598. // Statics
  42599. /**
  42600. * Parses a PBR Material from a serialized object.
  42601. * @param source - Serialized object.
  42602. * @param scene - BJS scene instance.
  42603. * @param rootUrl - url for the scene object
  42604. * @returns - PBRMaterial
  42605. */
  42606. PBRMaterial.Parse = function (source, scene, rootUrl) {
  42607. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  42608. };
  42609. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  42610. /**
  42611. * Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  42612. */
  42613. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  42614. /**
  42615. * Represents the value for Alpha Blend. Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  42616. */
  42617. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  42618. /**
  42619. * 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.
  42620. * They are also discarded below the alpha cutoff threshold to improve performances.
  42621. */
  42622. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  42623. __decorate([
  42624. BABYLON.serialize(),
  42625. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42626. ], PBRMaterial.prototype, "directIntensity", void 0);
  42627. __decorate([
  42628. BABYLON.serialize(),
  42629. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42630. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  42631. __decorate([
  42632. BABYLON.serialize(),
  42633. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42634. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  42635. __decorate([
  42636. BABYLON.serialize(),
  42637. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42638. ], PBRMaterial.prototype, "specularIntensity", void 0);
  42639. __decorate([
  42640. BABYLON.serialize(),
  42641. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42642. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  42643. __decorate([
  42644. BABYLON.serializeAsTexture(),
  42645. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42646. ], PBRMaterial.prototype, "albedoTexture", void 0);
  42647. __decorate([
  42648. BABYLON.serializeAsTexture(),
  42649. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42650. ], PBRMaterial.prototype, "ambientTexture", void 0);
  42651. __decorate([
  42652. BABYLON.serialize(),
  42653. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42654. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  42655. __decorate([
  42656. BABYLON.serializeAsTexture(),
  42657. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42658. ], PBRMaterial.prototype, "opacityTexture", void 0);
  42659. __decorate([
  42660. BABYLON.serializeAsTexture(),
  42661. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42662. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  42663. __decorate([
  42664. BABYLON.serializeAsTexture(),
  42665. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42666. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  42667. __decorate([
  42668. BABYLON.serializeAsTexture(),
  42669. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42670. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  42671. __decorate([
  42672. BABYLON.serializeAsTexture(),
  42673. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42674. ], PBRMaterial.prototype, "metallicTexture", void 0);
  42675. __decorate([
  42676. BABYLON.serialize(),
  42677. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42678. ], PBRMaterial.prototype, "metallic", void 0);
  42679. __decorate([
  42680. BABYLON.serialize(),
  42681. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42682. ], PBRMaterial.prototype, "roughness", void 0);
  42683. __decorate([
  42684. BABYLON.serializeAsTexture(),
  42685. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42686. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  42687. __decorate([
  42688. BABYLON.serializeAsTexture(),
  42689. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42690. ], PBRMaterial.prototype, "bumpTexture", void 0);
  42691. __decorate([
  42692. BABYLON.serializeAsTexture(),
  42693. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  42694. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  42695. __decorate([
  42696. BABYLON.serializeAsTexture(),
  42697. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42698. ], PBRMaterial.prototype, "refractionTexture", void 0);
  42699. __decorate([
  42700. BABYLON.serializeAsColor3("ambient"),
  42701. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42702. ], PBRMaterial.prototype, "ambientColor", void 0);
  42703. __decorate([
  42704. BABYLON.serializeAsColor3("albedo"),
  42705. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42706. ], PBRMaterial.prototype, "albedoColor", void 0);
  42707. __decorate([
  42708. BABYLON.serializeAsColor3("reflectivity"),
  42709. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42710. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  42711. __decorate([
  42712. BABYLON.serializeAsColor3("reflection"),
  42713. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42714. ], PBRMaterial.prototype, "reflectionColor", void 0);
  42715. __decorate([
  42716. BABYLON.serializeAsColor3("emissive"),
  42717. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42718. ], PBRMaterial.prototype, "emissiveColor", void 0);
  42719. __decorate([
  42720. BABYLON.serialize(),
  42721. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42722. ], PBRMaterial.prototype, "microSurface", void 0);
  42723. __decorate([
  42724. BABYLON.serialize(),
  42725. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42726. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  42727. __decorate([
  42728. BABYLON.serialize(),
  42729. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42730. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  42731. __decorate([
  42732. BABYLON.serialize(),
  42733. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42734. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  42735. __decorate([
  42736. BABYLON.serialize(),
  42737. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42738. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  42739. __decorate([
  42740. BABYLON.serialize(),
  42741. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42742. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  42743. __decorate([
  42744. BABYLON.serialize(),
  42745. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42746. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  42747. __decorate([
  42748. BABYLON.serialize(),
  42749. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42750. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  42751. __decorate([
  42752. BABYLON.serialize(),
  42753. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42754. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  42755. __decorate([
  42756. BABYLON.serialize(),
  42757. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42758. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  42759. __decorate([
  42760. BABYLON.serialize(),
  42761. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42762. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  42763. __decorate([
  42764. BABYLON.serialize(),
  42765. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42766. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  42767. __decorate([
  42768. BABYLON.serialize(),
  42769. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42770. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  42771. __decorate([
  42772. BABYLON.serialize(),
  42773. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42774. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  42775. __decorate([
  42776. BABYLON.serialize(),
  42777. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42778. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  42779. __decorate([
  42780. BABYLON.serialize(),
  42781. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42782. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  42783. __decorate([
  42784. BABYLON.serialize(),
  42785. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42786. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  42787. __decorate([
  42788. BABYLON.serialize(),
  42789. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42790. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  42791. __decorate([
  42792. BABYLON.serialize(),
  42793. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42794. ], PBRMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  42795. __decorate([
  42796. BABYLON.serialize(),
  42797. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42798. ], PBRMaterial.prototype, "useParallax", void 0);
  42799. __decorate([
  42800. BABYLON.serialize(),
  42801. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42802. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  42803. __decorate([
  42804. BABYLON.serialize(),
  42805. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42806. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  42807. __decorate([
  42808. BABYLON.serialize(),
  42809. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  42810. ], PBRMaterial.prototype, "disableLighting", void 0);
  42811. __decorate([
  42812. BABYLON.serialize(),
  42813. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42814. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  42815. __decorate([
  42816. BABYLON.serialize(),
  42817. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  42818. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  42819. __decorate([
  42820. BABYLON.serialize(),
  42821. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42822. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  42823. __decorate([
  42824. BABYLON.serialize(),
  42825. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42826. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  42827. __decorate([
  42828. BABYLON.serialize(),
  42829. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42830. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  42831. __decorate([
  42832. BABYLON.serialize(),
  42833. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42834. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  42835. __decorate([
  42836. BABYLON.serialize(),
  42837. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42838. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  42839. __decorate([
  42840. BABYLON.serializeAsTexture(),
  42841. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42842. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  42843. __decorate([
  42844. BABYLON.serialize(),
  42845. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42846. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  42847. __decorate([
  42848. BABYLON.serialize(),
  42849. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42850. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  42851. __decorate([
  42852. BABYLON.serialize(),
  42853. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42854. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  42855. return PBRMaterial;
  42856. }(BABYLON.PBRBaseMaterial));
  42857. BABYLON.PBRMaterial = PBRMaterial;
  42858. })(BABYLON || (BABYLON = {}));
  42859. //# sourceMappingURL=babylon.pbrMaterial.js.map
  42860. var BABYLON;
  42861. (function (BABYLON) {
  42862. /**
  42863. * The PBR material of BJS following the metal roughness convention.
  42864. *
  42865. * This fits to the PBR convention in the GLTF definition:
  42866. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  42867. */
  42868. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  42869. __extends(PBRMetallicRoughnessMaterial, _super);
  42870. /**
  42871. * Instantiates a new PBRMetalRoughnessMaterial instance.
  42872. *
  42873. * @param name The material name
  42874. * @param scene The scene the material will be use in.
  42875. */
  42876. function PBRMetallicRoughnessMaterial(name, scene) {
  42877. var _this = _super.call(this, name, scene) || this;
  42878. _this._useRoughnessFromMetallicTextureAlpha = false;
  42879. _this._useRoughnessFromMetallicTextureGreen = true;
  42880. _this._useMetallnessFromMetallicTextureBlue = true;
  42881. _this.metallic = 1.0;
  42882. _this.roughness = 1.0;
  42883. return _this;
  42884. }
  42885. /**
  42886. * Return the currrent class name of the material.
  42887. */
  42888. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  42889. return "PBRMetallicRoughnessMaterial";
  42890. };
  42891. /**
  42892. * Return the active textures of the material.
  42893. */
  42894. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  42895. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42896. if (this.baseTexture) {
  42897. activeTextures.push(this.baseTexture);
  42898. }
  42899. if (this.metallicRoughnessTexture) {
  42900. activeTextures.push(this.metallicRoughnessTexture);
  42901. }
  42902. return activeTextures;
  42903. };
  42904. /**
  42905. * Checks to see if a texture is used in the material.
  42906. * @param texture - Base texture to use.
  42907. * @returns - Boolean specifying if a texture is used in the material.
  42908. */
  42909. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  42910. if (_super.prototype.hasTexture.call(this, texture)) {
  42911. return true;
  42912. }
  42913. if (this.baseTexture === texture) {
  42914. return true;
  42915. }
  42916. if (this.metallicRoughnessTexture === texture) {
  42917. return true;
  42918. }
  42919. return false;
  42920. };
  42921. /**
  42922. * Makes a duplicate of the current material.
  42923. * @param name - name to use for the new material.
  42924. */
  42925. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  42926. var _this = this;
  42927. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  42928. clone.id = name;
  42929. clone.name = name;
  42930. return clone;
  42931. };
  42932. /**
  42933. * Serialize the material to a parsable JSON object.
  42934. */
  42935. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  42936. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  42937. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  42938. return serializationObject;
  42939. };
  42940. /**
  42941. * Parses a JSON object correponding to the serialize function.
  42942. */
  42943. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  42944. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  42945. };
  42946. __decorate([
  42947. BABYLON.serializeAsColor3(),
  42948. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  42949. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  42950. __decorate([
  42951. BABYLON.serializeAsTexture(),
  42952. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  42953. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  42954. __decorate([
  42955. BABYLON.serialize(),
  42956. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42957. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  42958. __decorate([
  42959. BABYLON.serialize(),
  42960. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42961. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  42962. __decorate([
  42963. BABYLON.serializeAsTexture(),
  42964. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  42965. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  42966. return PBRMetallicRoughnessMaterial;
  42967. }(BABYLON.PBRBaseSimpleMaterial));
  42968. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  42969. })(BABYLON || (BABYLON = {}));
  42970. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  42971. var BABYLON;
  42972. (function (BABYLON) {
  42973. /**
  42974. * The PBR material of BJS following the specular glossiness convention.
  42975. *
  42976. * This fits to the PBR convention in the GLTF definition:
  42977. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  42978. */
  42979. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  42980. __extends(PBRSpecularGlossinessMaterial, _super);
  42981. /**
  42982. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  42983. *
  42984. * @param name The material name
  42985. * @param scene The scene the material will be use in.
  42986. */
  42987. function PBRSpecularGlossinessMaterial(name, scene) {
  42988. var _this = _super.call(this, name, scene) || this;
  42989. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  42990. return _this;
  42991. }
  42992. /**
  42993. * Return the currrent class name of the material.
  42994. */
  42995. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  42996. return "PBRSpecularGlossinessMaterial";
  42997. };
  42998. /**
  42999. * Return the active textures of the material.
  43000. */
  43001. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  43002. var activeTextures = _super.prototype.getActiveTextures.call(this);
  43003. if (this.diffuseTexture) {
  43004. activeTextures.push(this.diffuseTexture);
  43005. }
  43006. if (this.specularGlossinessTexture) {
  43007. activeTextures.push(this.specularGlossinessTexture);
  43008. }
  43009. return activeTextures;
  43010. };
  43011. /**
  43012. * Checks to see if a texture is used in the material.
  43013. * @param texture - Base texture to use.
  43014. * @returns - Boolean specifying if a texture is used in the material.
  43015. */
  43016. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  43017. if (_super.prototype.hasTexture.call(this, texture)) {
  43018. return true;
  43019. }
  43020. if (this.diffuseTexture === texture) {
  43021. return true;
  43022. }
  43023. if (this.specularGlossinessTexture === texture) {
  43024. return true;
  43025. }
  43026. return false;
  43027. };
  43028. /**
  43029. * Makes a duplicate of the current material.
  43030. * @param name - name to use for the new material.
  43031. */
  43032. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  43033. var _this = this;
  43034. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  43035. clone.id = name;
  43036. clone.name = name;
  43037. return clone;
  43038. };
  43039. /**
  43040. * Serialize the material to a parsable JSON object.
  43041. */
  43042. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  43043. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  43044. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  43045. return serializationObject;
  43046. };
  43047. /**
  43048. * Parses a JSON object correponding to the serialize function.
  43049. */
  43050. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  43051. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  43052. };
  43053. __decorate([
  43054. BABYLON.serializeAsColor3("diffuse"),
  43055. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  43056. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  43057. __decorate([
  43058. BABYLON.serializeAsTexture(),
  43059. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  43060. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  43061. __decorate([
  43062. BABYLON.serializeAsColor3("specular"),
  43063. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  43064. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  43065. __decorate([
  43066. BABYLON.serialize(),
  43067. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  43068. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  43069. __decorate([
  43070. BABYLON.serializeAsTexture(),
  43071. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  43072. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  43073. return PBRSpecularGlossinessMaterial;
  43074. }(BABYLON.PBRBaseSimpleMaterial));
  43075. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  43076. })(BABYLON || (BABYLON = {}));
  43077. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  43078. var BABYLON;
  43079. (function (BABYLON) {
  43080. BABYLON.CameraInputTypes = {};
  43081. var CameraInputsManager = /** @class */ (function () {
  43082. function CameraInputsManager(camera) {
  43083. this.attached = {};
  43084. this.camera = camera;
  43085. this.checkInputs = function () { };
  43086. }
  43087. /**
  43088. * Add an input method to a camera.
  43089. * builtin inputs example: camera.inputs.addGamepad();
  43090. * custom inputs example: camera.inputs.add(new BABYLON.FreeCameraGamepadInput());
  43091. * @param input camera input method
  43092. */
  43093. CameraInputsManager.prototype.add = function (input) {
  43094. var type = input.getSimpleName();
  43095. if (this.attached[type]) {
  43096. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  43097. return;
  43098. }
  43099. this.attached[type] = input;
  43100. input.camera = this.camera;
  43101. //for checkInputs, we are dynamically creating a function
  43102. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  43103. if (input.checkInputs) {
  43104. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  43105. }
  43106. if (this.attachedElement) {
  43107. input.attachControl(this.attachedElement);
  43108. }
  43109. };
  43110. /**
  43111. * Remove a specific input method from a camera
  43112. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  43113. * @param inputToRemove camera input method
  43114. */
  43115. CameraInputsManager.prototype.remove = function (inputToRemove) {
  43116. for (var cam in this.attached) {
  43117. var input = this.attached[cam];
  43118. if (input === inputToRemove) {
  43119. input.detachControl(this.attachedElement);
  43120. input.camera = null;
  43121. delete this.attached[cam];
  43122. this.rebuildInputCheck();
  43123. }
  43124. }
  43125. };
  43126. CameraInputsManager.prototype.removeByType = function (inputType) {
  43127. for (var cam in this.attached) {
  43128. var input = this.attached[cam];
  43129. if (input.getClassName() === inputType) {
  43130. input.detachControl(this.attachedElement);
  43131. input.camera = null;
  43132. delete this.attached[cam];
  43133. this.rebuildInputCheck();
  43134. }
  43135. }
  43136. };
  43137. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  43138. var current = this.checkInputs;
  43139. return function () {
  43140. current();
  43141. fn();
  43142. };
  43143. };
  43144. CameraInputsManager.prototype.attachInput = function (input) {
  43145. if (this.attachedElement) {
  43146. input.attachControl(this.attachedElement, this.noPreventDefault);
  43147. }
  43148. };
  43149. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  43150. if (noPreventDefault === void 0) { noPreventDefault = false; }
  43151. if (this.attachedElement) {
  43152. return;
  43153. }
  43154. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  43155. this.attachedElement = element;
  43156. this.noPreventDefault = noPreventDefault;
  43157. for (var cam in this.attached) {
  43158. this.attached[cam].attachControl(element, noPreventDefault);
  43159. }
  43160. };
  43161. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  43162. if (disconnect === void 0) { disconnect = false; }
  43163. if (this.attachedElement !== element) {
  43164. return;
  43165. }
  43166. for (var cam in this.attached) {
  43167. this.attached[cam].detachControl(element);
  43168. if (disconnect) {
  43169. this.attached[cam].camera = null;
  43170. }
  43171. }
  43172. this.attachedElement = null;
  43173. };
  43174. CameraInputsManager.prototype.rebuildInputCheck = function () {
  43175. this.checkInputs = function () { };
  43176. for (var cam in this.attached) {
  43177. var input = this.attached[cam];
  43178. if (input.checkInputs) {
  43179. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  43180. }
  43181. }
  43182. };
  43183. /**
  43184. * Remove all attached input methods from a camera
  43185. */
  43186. CameraInputsManager.prototype.clear = function () {
  43187. if (this.attachedElement) {
  43188. this.detachElement(this.attachedElement, true);
  43189. }
  43190. this.attached = {};
  43191. this.attachedElement = null;
  43192. this.checkInputs = function () { };
  43193. };
  43194. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  43195. var inputs = {};
  43196. for (var cam in this.attached) {
  43197. var input = this.attached[cam];
  43198. var res = BABYLON.SerializationHelper.Serialize(input);
  43199. inputs[input.getClassName()] = res;
  43200. }
  43201. serializedCamera.inputsmgr = inputs;
  43202. };
  43203. CameraInputsManager.prototype.parse = function (parsedCamera) {
  43204. var parsedInputs = parsedCamera.inputsmgr;
  43205. if (parsedInputs) {
  43206. this.clear();
  43207. for (var n in parsedInputs) {
  43208. var construct = BABYLON.CameraInputTypes[n];
  43209. if (construct) {
  43210. var parsedinput = parsedInputs[n];
  43211. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  43212. this.add(input);
  43213. }
  43214. }
  43215. }
  43216. else {
  43217. //2016-03-08 this part is for managing backward compatibility
  43218. for (var n in this.attached) {
  43219. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  43220. if (construct) {
  43221. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  43222. this.remove(this.attached[n]);
  43223. this.add(input);
  43224. }
  43225. }
  43226. }
  43227. };
  43228. return CameraInputsManager;
  43229. }());
  43230. BABYLON.CameraInputsManager = CameraInputsManager;
  43231. })(BABYLON || (BABYLON = {}));
  43232. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  43233. var BABYLON;
  43234. (function (BABYLON) {
  43235. var TargetCamera = /** @class */ (function (_super) {
  43236. __extends(TargetCamera, _super);
  43237. function TargetCamera(name, position, scene) {
  43238. var _this = _super.call(this, name, position, scene) || this;
  43239. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  43240. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  43241. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  43242. _this.speed = 2.0;
  43243. _this.noRotationConstraint = false;
  43244. _this.lockedTarget = null;
  43245. _this._currentTarget = BABYLON.Vector3.Zero();
  43246. _this._viewMatrix = BABYLON.Matrix.Zero();
  43247. _this._camMatrix = BABYLON.Matrix.Zero();
  43248. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  43249. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  43250. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  43251. _this._currentUpVector = new BABYLON.Vector3(0, 1, 0);
  43252. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  43253. _this._lookAtTemp = BABYLON.Matrix.Zero();
  43254. _this._tempMatrix = BABYLON.Matrix.Zero();
  43255. return _this;
  43256. }
  43257. TargetCamera.prototype.getFrontPosition = function (distance) {
  43258. this.getWorldMatrix();
  43259. var direction = this.getTarget().subtract(this.position);
  43260. direction.normalize();
  43261. direction.scaleInPlace(distance);
  43262. return this.globalPosition.add(direction);
  43263. };
  43264. TargetCamera.prototype._getLockedTargetPosition = function () {
  43265. if (!this.lockedTarget) {
  43266. return null;
  43267. }
  43268. if (this.lockedTarget.absolutePosition) {
  43269. this.lockedTarget.computeWorldMatrix();
  43270. }
  43271. return this.lockedTarget.absolutePosition || this.lockedTarget;
  43272. };
  43273. TargetCamera.prototype.storeState = function () {
  43274. this._storedPosition = this.position.clone();
  43275. this._storedRotation = this.rotation.clone();
  43276. if (this.rotationQuaternion) {
  43277. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  43278. }
  43279. return _super.prototype.storeState.call(this);
  43280. };
  43281. /**
  43282. * Restored camera state. You must call storeState() first
  43283. */
  43284. TargetCamera.prototype._restoreStateValues = function () {
  43285. if (!_super.prototype._restoreStateValues.call(this)) {
  43286. return false;
  43287. }
  43288. this.position = this._storedPosition.clone();
  43289. this.rotation = this._storedRotation.clone();
  43290. if (this.rotationQuaternion) {
  43291. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  43292. }
  43293. this.cameraDirection.copyFromFloats(0, 0, 0);
  43294. this.cameraRotation.copyFromFloats(0, 0);
  43295. return true;
  43296. };
  43297. // Cache
  43298. TargetCamera.prototype._initCache = function () {
  43299. _super.prototype._initCache.call(this);
  43300. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  43301. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  43302. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  43303. };
  43304. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  43305. if (!ignoreParentClass) {
  43306. _super.prototype._updateCache.call(this);
  43307. }
  43308. var lockedTargetPosition = this._getLockedTargetPosition();
  43309. if (!lockedTargetPosition) {
  43310. this._cache.lockedTarget = null;
  43311. }
  43312. else {
  43313. if (!this._cache.lockedTarget) {
  43314. this._cache.lockedTarget = lockedTargetPosition.clone();
  43315. }
  43316. else {
  43317. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  43318. }
  43319. }
  43320. this._cache.rotation.copyFrom(this.rotation);
  43321. if (this.rotationQuaternion)
  43322. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  43323. };
  43324. // Synchronized
  43325. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  43326. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  43327. return false;
  43328. }
  43329. var lockedTargetPosition = this._getLockedTargetPosition();
  43330. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  43331. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  43332. };
  43333. // Methods
  43334. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  43335. var engine = this.getEngine();
  43336. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  43337. };
  43338. // Target
  43339. TargetCamera.prototype.setTarget = function (target) {
  43340. this.upVector.normalize();
  43341. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  43342. this._camMatrix.invert();
  43343. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  43344. var vDir = target.subtract(this.position);
  43345. if (vDir.x >= 0.0) {
  43346. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  43347. }
  43348. else {
  43349. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  43350. }
  43351. this.rotation.z = 0;
  43352. if (isNaN(this.rotation.x)) {
  43353. this.rotation.x = 0;
  43354. }
  43355. if (isNaN(this.rotation.y)) {
  43356. this.rotation.y = 0;
  43357. }
  43358. if (isNaN(this.rotation.z)) {
  43359. this.rotation.z = 0;
  43360. }
  43361. if (this.rotationQuaternion) {
  43362. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  43363. }
  43364. };
  43365. /**
  43366. * Return the current target position of the camera. This value is expressed in local space.
  43367. */
  43368. TargetCamera.prototype.getTarget = function () {
  43369. return this._currentTarget;
  43370. };
  43371. TargetCamera.prototype._decideIfNeedsToMove = function () {
  43372. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  43373. };
  43374. TargetCamera.prototype._updatePosition = function () {
  43375. if (this.parent) {
  43376. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  43377. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  43378. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  43379. return;
  43380. }
  43381. this.position.addInPlace(this.cameraDirection);
  43382. };
  43383. TargetCamera.prototype._checkInputs = function () {
  43384. var needToMove = this._decideIfNeedsToMove();
  43385. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  43386. // Move
  43387. if (needToMove) {
  43388. this._updatePosition();
  43389. }
  43390. // Rotate
  43391. if (needToRotate) {
  43392. this.rotation.x += this.cameraRotation.x;
  43393. this.rotation.y += this.cameraRotation.y;
  43394. //rotate, if quaternion is set and rotation was used
  43395. if (this.rotationQuaternion) {
  43396. var len = this.rotation.lengthSquared();
  43397. if (len) {
  43398. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  43399. }
  43400. }
  43401. if (!this.noRotationConstraint) {
  43402. var limit = (Math.PI / 2) * 0.95;
  43403. if (this.rotation.x > limit)
  43404. this.rotation.x = limit;
  43405. if (this.rotation.x < -limit)
  43406. this.rotation.x = -limit;
  43407. }
  43408. }
  43409. // Inertia
  43410. if (needToMove) {
  43411. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  43412. this.cameraDirection.x = 0;
  43413. }
  43414. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  43415. this.cameraDirection.y = 0;
  43416. }
  43417. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  43418. this.cameraDirection.z = 0;
  43419. }
  43420. this.cameraDirection.scaleInPlace(this.inertia);
  43421. }
  43422. if (needToRotate) {
  43423. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  43424. this.cameraRotation.x = 0;
  43425. }
  43426. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  43427. this.cameraRotation.y = 0;
  43428. }
  43429. this.cameraRotation.scaleInPlace(this.inertia);
  43430. }
  43431. _super.prototype._checkInputs.call(this);
  43432. };
  43433. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  43434. if (this.rotationQuaternion) {
  43435. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  43436. }
  43437. else {
  43438. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  43439. }
  43440. //update the up vector!
  43441. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._currentUpVector);
  43442. };
  43443. TargetCamera.prototype._getViewMatrix = function () {
  43444. if (this.lockedTarget) {
  43445. this.setTarget(this._getLockedTargetPosition());
  43446. }
  43447. // Compute
  43448. this._updateCameraRotationMatrix();
  43449. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  43450. // Computing target and final matrix
  43451. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  43452. if (this.getScene().useRightHandedSystem) {
  43453. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  43454. }
  43455. else {
  43456. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  43457. }
  43458. return this._viewMatrix;
  43459. };
  43460. /**
  43461. * @override
  43462. * Override Camera.createRigCamera
  43463. */
  43464. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  43465. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  43466. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  43467. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  43468. if (!this.rotationQuaternion) {
  43469. this.rotationQuaternion = new BABYLON.Quaternion();
  43470. }
  43471. rigCamera._cameraRigParams = {};
  43472. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  43473. }
  43474. return rigCamera;
  43475. }
  43476. return null;
  43477. };
  43478. /**
  43479. * @override
  43480. * Override Camera._updateRigCameras
  43481. */
  43482. TargetCamera.prototype._updateRigCameras = function () {
  43483. var camLeft = this._rigCameras[0];
  43484. var camRight = this._rigCameras[1];
  43485. switch (this.cameraRigMode) {
  43486. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  43487. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  43488. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  43489. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  43490. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  43491. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  43492. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  43493. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  43494. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  43495. camLeft.setTarget(this.getTarget());
  43496. camRight.setTarget(this.getTarget());
  43497. break;
  43498. case BABYLON.Camera.RIG_MODE_VR:
  43499. if (camLeft.rotationQuaternion) {
  43500. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  43501. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  43502. }
  43503. else {
  43504. camLeft.rotation.copyFrom(this.rotation);
  43505. camRight.rotation.copyFrom(this.rotation);
  43506. }
  43507. camLeft.position.copyFrom(this.position);
  43508. camRight.position.copyFrom(this.position);
  43509. break;
  43510. }
  43511. _super.prototype._updateRigCameras.call(this);
  43512. };
  43513. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  43514. if (!this._rigCamTransformMatrix) {
  43515. this._rigCamTransformMatrix = new BABYLON.Matrix();
  43516. }
  43517. var target = this.getTarget();
  43518. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  43519. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  43520. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  43521. };
  43522. TargetCamera.prototype.getClassName = function () {
  43523. return "TargetCamera";
  43524. };
  43525. __decorate([
  43526. BABYLON.serializeAsVector3()
  43527. ], TargetCamera.prototype, "rotation", void 0);
  43528. __decorate([
  43529. BABYLON.serialize()
  43530. ], TargetCamera.prototype, "speed", void 0);
  43531. __decorate([
  43532. BABYLON.serializeAsMeshReference("lockedTargetId")
  43533. ], TargetCamera.prototype, "lockedTarget", void 0);
  43534. return TargetCamera;
  43535. }(BABYLON.Camera));
  43536. BABYLON.TargetCamera = TargetCamera;
  43537. })(BABYLON || (BABYLON = {}));
  43538. //# sourceMappingURL=babylon.targetCamera.js.map
  43539. var BABYLON;
  43540. (function (BABYLON) {
  43541. var FreeCameraMouseInput = /** @class */ (function () {
  43542. function FreeCameraMouseInput(touchEnabled) {
  43543. if (touchEnabled === void 0) { touchEnabled = true; }
  43544. this.touchEnabled = touchEnabled;
  43545. this.buttons = [0, 1, 2];
  43546. this.angularSensibility = 2000.0;
  43547. this.previousPosition = null;
  43548. }
  43549. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  43550. var _this = this;
  43551. var engine = this.camera.getEngine();
  43552. if (!this._pointerInput) {
  43553. this._pointerInput = function (p, s) {
  43554. var evt = p.event;
  43555. if (engine.isInVRExclusivePointerMode) {
  43556. return;
  43557. }
  43558. if (!_this.touchEnabled && evt.pointerType === "touch") {
  43559. return;
  43560. }
  43561. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  43562. return;
  43563. }
  43564. var srcElement = (evt.srcElement || evt.target);
  43565. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  43566. try {
  43567. srcElement.setPointerCapture(evt.pointerId);
  43568. }
  43569. catch (e) {
  43570. //Nothing to do with the error. Execution will continue.
  43571. }
  43572. _this.previousPosition = {
  43573. x: evt.clientX,
  43574. y: evt.clientY
  43575. };
  43576. if (!noPreventDefault) {
  43577. evt.preventDefault();
  43578. element.focus();
  43579. }
  43580. }
  43581. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  43582. try {
  43583. srcElement.releasePointerCapture(evt.pointerId);
  43584. }
  43585. catch (e) {
  43586. //Nothing to do with the error.
  43587. }
  43588. _this.previousPosition = null;
  43589. if (!noPreventDefault) {
  43590. evt.preventDefault();
  43591. }
  43592. }
  43593. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  43594. if (!_this.previousPosition || engine.isPointerLock) {
  43595. return;
  43596. }
  43597. var offsetX = evt.clientX - _this.previousPosition.x;
  43598. var offsetY = evt.clientY - _this.previousPosition.y;
  43599. if (_this.camera.getScene().useRightHandedSystem) {
  43600. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  43601. }
  43602. else {
  43603. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  43604. }
  43605. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  43606. _this.previousPosition = {
  43607. x: evt.clientX,
  43608. y: evt.clientY
  43609. };
  43610. if (!noPreventDefault) {
  43611. evt.preventDefault();
  43612. }
  43613. }
  43614. };
  43615. }
  43616. this._onMouseMove = function (evt) {
  43617. if (!engine.isPointerLock) {
  43618. return;
  43619. }
  43620. if (engine.isInVRExclusivePointerMode) {
  43621. return;
  43622. }
  43623. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  43624. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  43625. if (_this.camera.getScene().useRightHandedSystem) {
  43626. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  43627. }
  43628. else {
  43629. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  43630. }
  43631. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  43632. _this.previousPosition = null;
  43633. if (!noPreventDefault) {
  43634. evt.preventDefault();
  43635. }
  43636. };
  43637. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  43638. element.addEventListener("mousemove", this._onMouseMove, false);
  43639. };
  43640. FreeCameraMouseInput.prototype.detachControl = function (element) {
  43641. if (this._observer && element) {
  43642. this.camera.getScene().onPointerObservable.remove(this._observer);
  43643. if (this._onMouseMove) {
  43644. element.removeEventListener("mousemove", this._onMouseMove);
  43645. }
  43646. this._observer = null;
  43647. this._onMouseMove = null;
  43648. this.previousPosition = null;
  43649. }
  43650. };
  43651. FreeCameraMouseInput.prototype.getClassName = function () {
  43652. return "FreeCameraMouseInput";
  43653. };
  43654. FreeCameraMouseInput.prototype.getSimpleName = function () {
  43655. return "mouse";
  43656. };
  43657. __decorate([
  43658. BABYLON.serialize()
  43659. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  43660. __decorate([
  43661. BABYLON.serialize()
  43662. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  43663. return FreeCameraMouseInput;
  43664. }());
  43665. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  43666. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  43667. })(BABYLON || (BABYLON = {}));
  43668. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  43669. var BABYLON;
  43670. (function (BABYLON) {
  43671. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  43672. function FreeCameraKeyboardMoveInput() {
  43673. this._keys = new Array();
  43674. this.keysUp = [38];
  43675. this.keysDown = [40];
  43676. this.keysLeft = [37];
  43677. this.keysRight = [39];
  43678. }
  43679. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  43680. var _this = this;
  43681. if (this._onCanvasBlurObserver) {
  43682. return;
  43683. }
  43684. this._scene = this.camera.getScene();
  43685. this._engine = this._scene.getEngine();
  43686. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  43687. _this._keys = [];
  43688. });
  43689. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  43690. var evt = info.event;
  43691. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  43692. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  43693. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  43694. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  43695. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  43696. var index = _this._keys.indexOf(evt.keyCode);
  43697. if (index === -1) {
  43698. _this._keys.push(evt.keyCode);
  43699. }
  43700. if (!noPreventDefault) {
  43701. evt.preventDefault();
  43702. }
  43703. }
  43704. }
  43705. else {
  43706. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  43707. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  43708. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  43709. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  43710. var index = _this._keys.indexOf(evt.keyCode);
  43711. if (index >= 0) {
  43712. _this._keys.splice(index, 1);
  43713. }
  43714. if (!noPreventDefault) {
  43715. evt.preventDefault();
  43716. }
  43717. }
  43718. }
  43719. });
  43720. };
  43721. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  43722. if (this._scene) {
  43723. if (this._onKeyboardObserver) {
  43724. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  43725. }
  43726. if (this._onCanvasBlurObserver) {
  43727. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  43728. }
  43729. this._onKeyboardObserver = null;
  43730. this._onCanvasBlurObserver = null;
  43731. }
  43732. this._keys = [];
  43733. };
  43734. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  43735. if (this._onKeyboardObserver) {
  43736. var camera = this.camera;
  43737. // Keyboard
  43738. for (var index = 0; index < this._keys.length; index++) {
  43739. var keyCode = this._keys[index];
  43740. var speed = camera._computeLocalCameraSpeed();
  43741. if (this.keysLeft.indexOf(keyCode) !== -1) {
  43742. camera._localDirection.copyFromFloats(-speed, 0, 0);
  43743. }
  43744. else if (this.keysUp.indexOf(keyCode) !== -1) {
  43745. camera._localDirection.copyFromFloats(0, 0, speed);
  43746. }
  43747. else if (this.keysRight.indexOf(keyCode) !== -1) {
  43748. camera._localDirection.copyFromFloats(speed, 0, 0);
  43749. }
  43750. else if (this.keysDown.indexOf(keyCode) !== -1) {
  43751. camera._localDirection.copyFromFloats(0, 0, -speed);
  43752. }
  43753. if (camera.getScene().useRightHandedSystem) {
  43754. camera._localDirection.z *= -1;
  43755. }
  43756. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  43757. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  43758. camera.cameraDirection.addInPlace(camera._transformedDirection);
  43759. }
  43760. }
  43761. };
  43762. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  43763. return "FreeCameraKeyboardMoveInput";
  43764. };
  43765. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  43766. this._keys = [];
  43767. };
  43768. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  43769. return "keyboard";
  43770. };
  43771. __decorate([
  43772. BABYLON.serialize()
  43773. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  43774. __decorate([
  43775. BABYLON.serialize()
  43776. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  43777. __decorate([
  43778. BABYLON.serialize()
  43779. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  43780. __decorate([
  43781. BABYLON.serialize()
  43782. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  43783. return FreeCameraKeyboardMoveInput;
  43784. }());
  43785. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  43786. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  43787. })(BABYLON || (BABYLON = {}));
  43788. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  43789. var BABYLON;
  43790. (function (BABYLON) {
  43791. var FreeCameraInputsManager = /** @class */ (function (_super) {
  43792. __extends(FreeCameraInputsManager, _super);
  43793. function FreeCameraInputsManager(camera) {
  43794. return _super.call(this, camera) || this;
  43795. }
  43796. FreeCameraInputsManager.prototype.addKeyboard = function () {
  43797. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  43798. return this;
  43799. };
  43800. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  43801. if (touchEnabled === void 0) { touchEnabled = true; }
  43802. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  43803. return this;
  43804. };
  43805. FreeCameraInputsManager.prototype.addGamepad = function () {
  43806. this.add(new BABYLON.FreeCameraGamepadInput());
  43807. return this;
  43808. };
  43809. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  43810. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  43811. return this;
  43812. };
  43813. FreeCameraInputsManager.prototype.addTouch = function () {
  43814. this.add(new BABYLON.FreeCameraTouchInput());
  43815. return this;
  43816. };
  43817. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  43818. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  43819. return this;
  43820. };
  43821. return FreeCameraInputsManager;
  43822. }(BABYLON.CameraInputsManager));
  43823. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  43824. })(BABYLON || (BABYLON = {}));
  43825. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  43826. var BABYLON;
  43827. (function (BABYLON) {
  43828. var FreeCamera = /** @class */ (function (_super) {
  43829. __extends(FreeCamera, _super);
  43830. function FreeCamera(name, position, scene) {
  43831. var _this = _super.call(this, name, position, scene) || this;
  43832. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  43833. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  43834. _this.checkCollisions = false;
  43835. _this.applyGravity = false;
  43836. _this._needMoveForGravity = false;
  43837. _this._oldPosition = BABYLON.Vector3.Zero();
  43838. _this._diffPosition = BABYLON.Vector3.Zero();
  43839. _this._newPosition = BABYLON.Vector3.Zero();
  43840. // Collisions
  43841. _this._collisionMask = -1;
  43842. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  43843. if (collidedMesh === void 0) { collidedMesh = null; }
  43844. //TODO move this to the collision coordinator!
  43845. if (_this.getScene().workerCollisions)
  43846. newPosition.multiplyInPlace(_this._collider._radius);
  43847. var updatePosition = function (newPos) {
  43848. _this._newPosition.copyFrom(newPos);
  43849. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  43850. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  43851. _this.position.addInPlace(_this._diffPosition);
  43852. if (_this.onCollide && collidedMesh) {
  43853. _this.onCollide(collidedMesh);
  43854. }
  43855. }
  43856. };
  43857. updatePosition(newPosition);
  43858. };
  43859. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  43860. _this.inputs.addKeyboard().addMouse();
  43861. return _this;
  43862. }
  43863. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  43864. //-- begin properties for backward compatibility for inputs
  43865. /**
  43866. * Gets the input sensibility for a mouse input. (default is 2000.0)
  43867. * Higher values reduce sensitivity.
  43868. */
  43869. get: function () {
  43870. var mouse = this.inputs.attached["mouse"];
  43871. if (mouse)
  43872. return mouse.angularSensibility;
  43873. return 0;
  43874. },
  43875. /**
  43876. * Sets the input sensibility for a mouse input. (default is 2000.0)
  43877. * Higher values reduce sensitivity.
  43878. */
  43879. set: function (value) {
  43880. var mouse = this.inputs.attached["mouse"];
  43881. if (mouse)
  43882. mouse.angularSensibility = value;
  43883. },
  43884. enumerable: true,
  43885. configurable: true
  43886. });
  43887. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  43888. get: function () {
  43889. var keyboard = this.inputs.attached["keyboard"];
  43890. if (keyboard)
  43891. return keyboard.keysUp;
  43892. return [];
  43893. },
  43894. set: function (value) {
  43895. var keyboard = this.inputs.attached["keyboard"];
  43896. if (keyboard)
  43897. keyboard.keysUp = value;
  43898. },
  43899. enumerable: true,
  43900. configurable: true
  43901. });
  43902. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  43903. get: function () {
  43904. var keyboard = this.inputs.attached["keyboard"];
  43905. if (keyboard)
  43906. return keyboard.keysDown;
  43907. return [];
  43908. },
  43909. set: function (value) {
  43910. var keyboard = this.inputs.attached["keyboard"];
  43911. if (keyboard)
  43912. keyboard.keysDown = value;
  43913. },
  43914. enumerable: true,
  43915. configurable: true
  43916. });
  43917. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  43918. get: function () {
  43919. var keyboard = this.inputs.attached["keyboard"];
  43920. if (keyboard)
  43921. return keyboard.keysLeft;
  43922. return [];
  43923. },
  43924. set: function (value) {
  43925. var keyboard = this.inputs.attached["keyboard"];
  43926. if (keyboard)
  43927. keyboard.keysLeft = value;
  43928. },
  43929. enumerable: true,
  43930. configurable: true
  43931. });
  43932. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  43933. get: function () {
  43934. var keyboard = this.inputs.attached["keyboard"];
  43935. if (keyboard)
  43936. return keyboard.keysRight;
  43937. return [];
  43938. },
  43939. set: function (value) {
  43940. var keyboard = this.inputs.attached["keyboard"];
  43941. if (keyboard)
  43942. keyboard.keysRight = value;
  43943. },
  43944. enumerable: true,
  43945. configurable: true
  43946. });
  43947. // Controls
  43948. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  43949. this.inputs.attachElement(element, noPreventDefault);
  43950. };
  43951. FreeCamera.prototype.detachControl = function (element) {
  43952. this.inputs.detachElement(element);
  43953. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  43954. this.cameraRotation = new BABYLON.Vector2(0, 0);
  43955. };
  43956. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  43957. get: function () {
  43958. return this._collisionMask;
  43959. },
  43960. set: function (mask) {
  43961. this._collisionMask = !isNaN(mask) ? mask : -1;
  43962. },
  43963. enumerable: true,
  43964. configurable: true
  43965. });
  43966. FreeCamera.prototype._collideWithWorld = function (displacement) {
  43967. var globalPosition;
  43968. if (this.parent) {
  43969. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  43970. }
  43971. else {
  43972. globalPosition = this.position;
  43973. }
  43974. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  43975. this._oldPosition.addInPlace(this.ellipsoidOffset);
  43976. if (!this._collider) {
  43977. this._collider = new BABYLON.Collider();
  43978. }
  43979. this._collider._radius = this.ellipsoid;
  43980. this._collider.collisionMask = this._collisionMask;
  43981. //no need for clone, as long as gravity is not on.
  43982. var actualDisplacement = displacement;
  43983. //add gravity to the direction to prevent the dual-collision checking
  43984. if (this.applyGravity) {
  43985. //this prevents mending with cameraDirection, a global variable of the free camera class.
  43986. actualDisplacement = displacement.add(this.getScene().gravity);
  43987. }
  43988. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  43989. };
  43990. FreeCamera.prototype._checkInputs = function () {
  43991. if (!this._localDirection) {
  43992. this._localDirection = BABYLON.Vector3.Zero();
  43993. this._transformedDirection = BABYLON.Vector3.Zero();
  43994. }
  43995. this.inputs.checkInputs();
  43996. _super.prototype._checkInputs.call(this);
  43997. };
  43998. FreeCamera.prototype._decideIfNeedsToMove = function () {
  43999. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  44000. };
  44001. FreeCamera.prototype._updatePosition = function () {
  44002. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  44003. this._collideWithWorld(this.cameraDirection);
  44004. }
  44005. else {
  44006. _super.prototype._updatePosition.call(this);
  44007. }
  44008. };
  44009. FreeCamera.prototype.dispose = function () {
  44010. this.inputs.clear();
  44011. _super.prototype.dispose.call(this);
  44012. };
  44013. FreeCamera.prototype.getClassName = function () {
  44014. return "FreeCamera";
  44015. };
  44016. __decorate([
  44017. BABYLON.serializeAsVector3()
  44018. ], FreeCamera.prototype, "ellipsoid", void 0);
  44019. __decorate([
  44020. BABYLON.serializeAsVector3()
  44021. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  44022. __decorate([
  44023. BABYLON.serialize()
  44024. ], FreeCamera.prototype, "checkCollisions", void 0);
  44025. __decorate([
  44026. BABYLON.serialize()
  44027. ], FreeCamera.prototype, "applyGravity", void 0);
  44028. return FreeCamera;
  44029. }(BABYLON.TargetCamera));
  44030. BABYLON.FreeCamera = FreeCamera;
  44031. })(BABYLON || (BABYLON = {}));
  44032. //# sourceMappingURL=babylon.freeCamera.js.map
  44033. var BABYLON;
  44034. (function (BABYLON) {
  44035. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  44036. function ArcRotateCameraKeyboardMoveInput() {
  44037. this._keys = new Array();
  44038. this.keysUp = [38];
  44039. this.keysDown = [40];
  44040. this.keysLeft = [37];
  44041. this.keysRight = [39];
  44042. this.keysReset = [220];
  44043. this.panningSensibility = 50.0;
  44044. this.zoomingSensibility = 25.0;
  44045. this.useAltToZoom = true;
  44046. }
  44047. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  44048. var _this = this;
  44049. if (this._onCanvasBlurObserver) {
  44050. return;
  44051. }
  44052. this._scene = this.camera.getScene();
  44053. this._engine = this._scene.getEngine();
  44054. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  44055. _this._keys = [];
  44056. });
  44057. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  44058. var evt = info.event;
  44059. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  44060. _this._ctrlPressed = evt.ctrlKey;
  44061. _this._altPressed = evt.altKey;
  44062. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  44063. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  44064. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  44065. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  44066. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  44067. var index = _this._keys.indexOf(evt.keyCode);
  44068. if (index === -1) {
  44069. _this._keys.push(evt.keyCode);
  44070. }
  44071. if (evt.preventDefault) {
  44072. if (!noPreventDefault) {
  44073. evt.preventDefault();
  44074. }
  44075. }
  44076. }
  44077. }
  44078. else {
  44079. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  44080. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  44081. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  44082. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  44083. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  44084. var index = _this._keys.indexOf(evt.keyCode);
  44085. if (index >= 0) {
  44086. _this._keys.splice(index, 1);
  44087. }
  44088. if (evt.preventDefault) {
  44089. if (!noPreventDefault) {
  44090. evt.preventDefault();
  44091. }
  44092. }
  44093. }
  44094. }
  44095. });
  44096. };
  44097. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  44098. if (this._scene) {
  44099. if (this._onKeyboardObserver) {
  44100. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  44101. }
  44102. if (this._onCanvasBlurObserver) {
  44103. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  44104. }
  44105. this._onKeyboardObserver = null;
  44106. this._onCanvasBlurObserver = null;
  44107. }
  44108. this._keys = [];
  44109. };
  44110. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  44111. if (this._onKeyboardObserver) {
  44112. var camera = this.camera;
  44113. for (var index = 0; index < this._keys.length; index++) {
  44114. var keyCode = this._keys[index];
  44115. if (this.keysLeft.indexOf(keyCode) !== -1) {
  44116. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  44117. camera.inertialPanningX -= 1 / this.panningSensibility;
  44118. }
  44119. else {
  44120. camera.inertialAlphaOffset -= 0.01;
  44121. }
  44122. }
  44123. else if (this.keysUp.indexOf(keyCode) !== -1) {
  44124. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  44125. camera.inertialPanningY += 1 / this.panningSensibility;
  44126. }
  44127. else if (this._altPressed && this.useAltToZoom) {
  44128. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  44129. }
  44130. else {
  44131. camera.inertialBetaOffset -= 0.01;
  44132. }
  44133. }
  44134. else if (this.keysRight.indexOf(keyCode) !== -1) {
  44135. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  44136. camera.inertialPanningX += 1 / this.panningSensibility;
  44137. }
  44138. else {
  44139. camera.inertialAlphaOffset += 0.01;
  44140. }
  44141. }
  44142. else if (this.keysDown.indexOf(keyCode) !== -1) {
  44143. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  44144. camera.inertialPanningY -= 1 / this.panningSensibility;
  44145. }
  44146. else if (this._altPressed && this.useAltToZoom) {
  44147. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  44148. }
  44149. else {
  44150. camera.inertialBetaOffset += 0.01;
  44151. }
  44152. }
  44153. else if (this.keysReset.indexOf(keyCode) !== -1) {
  44154. camera.restoreState();
  44155. }
  44156. }
  44157. }
  44158. };
  44159. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  44160. return "ArcRotateCameraKeyboardMoveInput";
  44161. };
  44162. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  44163. return "keyboard";
  44164. };
  44165. __decorate([
  44166. BABYLON.serialize()
  44167. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  44168. __decorate([
  44169. BABYLON.serialize()
  44170. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  44171. __decorate([
  44172. BABYLON.serialize()
  44173. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  44174. __decorate([
  44175. BABYLON.serialize()
  44176. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  44177. __decorate([
  44178. BABYLON.serialize()
  44179. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  44180. __decorate([
  44181. BABYLON.serialize()
  44182. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  44183. __decorate([
  44184. BABYLON.serialize()
  44185. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  44186. __decorate([
  44187. BABYLON.serialize()
  44188. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  44189. return ArcRotateCameraKeyboardMoveInput;
  44190. }());
  44191. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  44192. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  44193. })(BABYLON || (BABYLON = {}));
  44194. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  44195. var BABYLON;
  44196. (function (BABYLON) {
  44197. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  44198. function ArcRotateCameraMouseWheelInput() {
  44199. this.wheelPrecision = 3.0;
  44200. /**
  44201. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  44202. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  44203. */
  44204. this.wheelDeltaPercentage = 0;
  44205. }
  44206. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  44207. var _this = this;
  44208. this._wheel = function (p, s) {
  44209. //sanity check - this should be a PointerWheel event.
  44210. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  44211. return;
  44212. var event = p.event;
  44213. var delta = 0;
  44214. if (event.wheelDelta) {
  44215. delta = _this.wheelDeltaPercentage ? (event.wheelDelta * 0.01) * _this.camera.radius * _this.wheelDeltaPercentage : event.wheelDelta / (_this.wheelPrecision * 40);
  44216. }
  44217. else if (event.detail) {
  44218. delta = -event.detail / _this.wheelPrecision;
  44219. }
  44220. if (delta)
  44221. _this.camera.inertialRadiusOffset += delta;
  44222. if (event.preventDefault) {
  44223. if (!noPreventDefault) {
  44224. event.preventDefault();
  44225. }
  44226. }
  44227. };
  44228. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  44229. };
  44230. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  44231. if (this._observer && element) {
  44232. this.camera.getScene().onPointerObservable.remove(this._observer);
  44233. this._observer = null;
  44234. this._wheel = null;
  44235. }
  44236. };
  44237. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  44238. return "ArcRotateCameraMouseWheelInput";
  44239. };
  44240. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  44241. return "mousewheel";
  44242. };
  44243. __decorate([
  44244. BABYLON.serialize()
  44245. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  44246. __decorate([
  44247. BABYLON.serialize()
  44248. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  44249. return ArcRotateCameraMouseWheelInput;
  44250. }());
  44251. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  44252. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  44253. })(BABYLON || (BABYLON = {}));
  44254. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  44255. var BABYLON;
  44256. (function (BABYLON) {
  44257. var ArcRotateCameraPointersInput = /** @class */ (function () {
  44258. function ArcRotateCameraPointersInput() {
  44259. this.buttons = [0, 1, 2];
  44260. this.angularSensibilityX = 1000.0;
  44261. this.angularSensibilityY = 1000.0;
  44262. this.pinchPrecision = 12.0;
  44263. /**
  44264. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  44265. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  44266. */
  44267. this.pinchDeltaPercentage = 0;
  44268. this.panningSensibility = 1000.0;
  44269. this.multiTouchPanning = true;
  44270. this.multiTouchPanAndZoom = true;
  44271. this._isPanClick = false;
  44272. this.pinchInwards = true;
  44273. }
  44274. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  44275. var _this = this;
  44276. var engine = this.camera.getEngine();
  44277. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  44278. var pointA = null;
  44279. var pointB = null;
  44280. var previousPinchSquaredDistance = 0;
  44281. var initialDistance = 0;
  44282. var twoFingerActivityCount = 0;
  44283. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  44284. this._pointerInput = function (p, s) {
  44285. var evt = p.event;
  44286. var isTouch = p.event.pointerType === "touch";
  44287. if (engine.isInVRExclusivePointerMode) {
  44288. return;
  44289. }
  44290. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  44291. return;
  44292. }
  44293. var srcElement = (evt.srcElement || evt.target);
  44294. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  44295. try {
  44296. srcElement.setPointerCapture(evt.pointerId);
  44297. }
  44298. catch (e) {
  44299. //Nothing to do with the error. Execution will continue.
  44300. }
  44301. // Manage panning with pan button click
  44302. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  44303. // manage pointers
  44304. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  44305. if (pointA === null) {
  44306. pointA = cacheSoloPointer;
  44307. }
  44308. else if (pointB === null) {
  44309. pointB = cacheSoloPointer;
  44310. }
  44311. if (!noPreventDefault) {
  44312. evt.preventDefault();
  44313. element.focus();
  44314. }
  44315. }
  44316. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  44317. _this.camera.restoreState();
  44318. }
  44319. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  44320. try {
  44321. srcElement.releasePointerCapture(evt.pointerId);
  44322. }
  44323. catch (e) {
  44324. //Nothing to do with the error.
  44325. }
  44326. cacheSoloPointer = null;
  44327. previousPinchSquaredDistance = 0;
  44328. previousMultiTouchPanPosition.isPaning = false;
  44329. previousMultiTouchPanPosition.isPinching = false;
  44330. twoFingerActivityCount = 0;
  44331. initialDistance = 0;
  44332. if (!isTouch) {
  44333. pointB = null; // Mouse and pen are mono pointer
  44334. }
  44335. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  44336. //but emptying completly pointers collection is required to fix a bug on iPhone :
  44337. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  44338. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  44339. if (engine.badOS) {
  44340. pointA = pointB = null;
  44341. }
  44342. else {
  44343. //only remove the impacted pointer in case of multitouch allowing on most
  44344. //platforms switching from rotate to zoom and pan seamlessly.
  44345. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  44346. pointA = pointB;
  44347. pointB = null;
  44348. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  44349. }
  44350. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  44351. pointB = null;
  44352. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  44353. }
  44354. else {
  44355. pointA = pointB = null;
  44356. }
  44357. }
  44358. if (!noPreventDefault) {
  44359. evt.preventDefault();
  44360. }
  44361. }
  44362. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  44363. if (!noPreventDefault) {
  44364. evt.preventDefault();
  44365. }
  44366. // One button down
  44367. if (pointA && pointB === null && cacheSoloPointer) {
  44368. if (_this.panningSensibility !== 0 &&
  44369. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  44370. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  44371. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  44372. }
  44373. else {
  44374. var offsetX = evt.clientX - cacheSoloPointer.x;
  44375. var offsetY = evt.clientY - cacheSoloPointer.y;
  44376. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  44377. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  44378. }
  44379. cacheSoloPointer.x = evt.clientX;
  44380. cacheSoloPointer.y = evt.clientY;
  44381. }
  44382. else if (pointA && pointB) {
  44383. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  44384. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  44385. ed.x = evt.clientX;
  44386. ed.y = evt.clientY;
  44387. var direction = _this.pinchInwards ? 1 : -1;
  44388. var distX = pointA.x - pointB.x;
  44389. var distY = pointA.y - pointB.y;
  44390. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  44391. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  44392. if (previousPinchSquaredDistance === 0) {
  44393. initialDistance = pinchDistance;
  44394. previousPinchSquaredDistance = pinchSquaredDistance;
  44395. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  44396. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  44397. return;
  44398. }
  44399. if (_this.multiTouchPanAndZoom) {
  44400. if (_this.pinchDeltaPercentage) {
  44401. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  44402. }
  44403. else {
  44404. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  44405. (_this.pinchPrecision *
  44406. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  44407. direction);
  44408. }
  44409. if (_this.panningSensibility !== 0) {
  44410. var pointersCenterX = (pointA.x + pointB.x) / 2;
  44411. var pointersCenterY = (pointA.y + pointB.y) / 2;
  44412. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  44413. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  44414. previousMultiTouchPanPosition.x = pointersCenterX;
  44415. previousMultiTouchPanPosition.y = pointersCenterY;
  44416. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  44417. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  44418. }
  44419. }
  44420. else {
  44421. twoFingerActivityCount++;
  44422. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  44423. if (_this.pinchDeltaPercentage) {
  44424. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  44425. }
  44426. else {
  44427. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  44428. (_this.pinchPrecision *
  44429. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  44430. direction);
  44431. }
  44432. previousMultiTouchPanPosition.isPaning = false;
  44433. previousMultiTouchPanPosition.isPinching = true;
  44434. }
  44435. else {
  44436. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  44437. if (!previousMultiTouchPanPosition.isPaning) {
  44438. previousMultiTouchPanPosition.isPaning = true;
  44439. previousMultiTouchPanPosition.isPinching = false;
  44440. previousMultiTouchPanPosition.x = ed.x;
  44441. previousMultiTouchPanPosition.y = ed.y;
  44442. return;
  44443. }
  44444. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  44445. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  44446. }
  44447. }
  44448. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  44449. previousMultiTouchPanPosition.x = ed.x;
  44450. previousMultiTouchPanPosition.y = ed.y;
  44451. }
  44452. }
  44453. previousPinchSquaredDistance = pinchSquaredDistance;
  44454. }
  44455. }
  44456. };
  44457. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  44458. this._onContextMenu = function (evt) {
  44459. evt.preventDefault();
  44460. };
  44461. if (!this.camera._useCtrlForPanning) {
  44462. element.addEventListener("contextmenu", this._onContextMenu, false);
  44463. }
  44464. this._onLostFocus = function () {
  44465. //this._keys = [];
  44466. pointA = pointB = null;
  44467. previousPinchSquaredDistance = 0;
  44468. previousMultiTouchPanPosition.isPaning = false;
  44469. previousMultiTouchPanPosition.isPinching = false;
  44470. twoFingerActivityCount = 0;
  44471. cacheSoloPointer = null;
  44472. initialDistance = 0;
  44473. };
  44474. this._onMouseMove = function (evt) {
  44475. if (!engine.isPointerLock) {
  44476. return;
  44477. }
  44478. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  44479. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  44480. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  44481. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  44482. if (!noPreventDefault) {
  44483. evt.preventDefault();
  44484. }
  44485. };
  44486. this._onGestureStart = function (e) {
  44487. if (window.MSGesture === undefined) {
  44488. return;
  44489. }
  44490. if (!_this._MSGestureHandler) {
  44491. _this._MSGestureHandler = new MSGesture();
  44492. _this._MSGestureHandler.target = element;
  44493. }
  44494. _this._MSGestureHandler.addPointer(e.pointerId);
  44495. };
  44496. this._onGesture = function (e) {
  44497. _this.camera.radius *= e.scale;
  44498. if (e.preventDefault) {
  44499. if (!noPreventDefault) {
  44500. e.stopPropagation();
  44501. e.preventDefault();
  44502. }
  44503. }
  44504. };
  44505. element.addEventListener("mousemove", this._onMouseMove, false);
  44506. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  44507. element.addEventListener("MSGestureChange", this._onGesture, false);
  44508. BABYLON.Tools.RegisterTopRootEvents([
  44509. { name: "blur", handler: this._onLostFocus }
  44510. ]);
  44511. };
  44512. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  44513. if (this._onLostFocus) {
  44514. BABYLON.Tools.UnregisterTopRootEvents([
  44515. { name: "blur", handler: this._onLostFocus }
  44516. ]);
  44517. }
  44518. if (element && this._observer) {
  44519. this.camera.getScene().onPointerObservable.remove(this._observer);
  44520. this._observer = null;
  44521. if (this._onContextMenu) {
  44522. element.removeEventListener("contextmenu", this._onContextMenu);
  44523. }
  44524. if (this._onMouseMove) {
  44525. element.removeEventListener("mousemove", this._onMouseMove);
  44526. }
  44527. if (this._onGestureStart) {
  44528. element.removeEventListener("MSPointerDown", this._onGestureStart);
  44529. }
  44530. if (this._onGesture) {
  44531. element.removeEventListener("MSGestureChange", this._onGesture);
  44532. }
  44533. this._isPanClick = false;
  44534. this.pinchInwards = true;
  44535. this._onMouseMove = null;
  44536. this._onGestureStart = null;
  44537. this._onGesture = null;
  44538. this._MSGestureHandler = null;
  44539. this._onLostFocus = null;
  44540. this._onContextMenu = null;
  44541. }
  44542. };
  44543. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  44544. return "ArcRotateCameraPointersInput";
  44545. };
  44546. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  44547. return "pointers";
  44548. };
  44549. __decorate([
  44550. BABYLON.serialize()
  44551. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  44552. __decorate([
  44553. BABYLON.serialize()
  44554. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  44555. __decorate([
  44556. BABYLON.serialize()
  44557. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  44558. __decorate([
  44559. BABYLON.serialize()
  44560. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  44561. __decorate([
  44562. BABYLON.serialize()
  44563. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  44564. __decorate([
  44565. BABYLON.serialize()
  44566. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  44567. __decorate([
  44568. BABYLON.serialize()
  44569. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  44570. __decorate([
  44571. BABYLON.serialize()
  44572. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  44573. return ArcRotateCameraPointersInput;
  44574. }());
  44575. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  44576. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  44577. })(BABYLON || (BABYLON = {}));
  44578. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  44579. var BABYLON;
  44580. (function (BABYLON) {
  44581. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  44582. __extends(ArcRotateCameraInputsManager, _super);
  44583. function ArcRotateCameraInputsManager(camera) {
  44584. return _super.call(this, camera) || this;
  44585. }
  44586. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  44587. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  44588. return this;
  44589. };
  44590. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  44591. this.add(new BABYLON.ArcRotateCameraPointersInput());
  44592. return this;
  44593. };
  44594. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  44595. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  44596. return this;
  44597. };
  44598. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  44599. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  44600. return this;
  44601. };
  44602. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  44603. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  44604. return this;
  44605. };
  44606. return ArcRotateCameraInputsManager;
  44607. }(BABYLON.CameraInputsManager));
  44608. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  44609. })(BABYLON || (BABYLON = {}));
  44610. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  44611. var BABYLON;
  44612. (function (BABYLON) {
  44613. var ArcRotateCamera = /** @class */ (function (_super) {
  44614. __extends(ArcRotateCamera, _super);
  44615. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  44616. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  44617. _this.inertialAlphaOffset = 0;
  44618. _this.inertialBetaOffset = 0;
  44619. _this.inertialRadiusOffset = 0;
  44620. _this.lowerAlphaLimit = null;
  44621. _this.upperAlphaLimit = null;
  44622. _this.lowerBetaLimit = 0.01;
  44623. _this.upperBetaLimit = Math.PI;
  44624. _this.lowerRadiusLimit = null;
  44625. _this.upperRadiusLimit = null;
  44626. _this.inertialPanningX = 0;
  44627. _this.inertialPanningY = 0;
  44628. _this.pinchToPanMaxDistance = 20;
  44629. _this.panningDistanceLimit = null;
  44630. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  44631. _this.panningInertia = 0.9;
  44632. //-- end properties for backward compatibility for inputs
  44633. _this.zoomOnFactor = 1;
  44634. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  44635. _this.allowUpsideDown = true;
  44636. _this._viewMatrix = new BABYLON.Matrix();
  44637. // Panning
  44638. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  44639. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  44640. _this.checkCollisions = false;
  44641. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  44642. _this._previousPosition = BABYLON.Vector3.Zero();
  44643. _this._collisionVelocity = BABYLON.Vector3.Zero();
  44644. _this._newPosition = BABYLON.Vector3.Zero();
  44645. _this._computationVector = BABYLON.Vector3.Zero();
  44646. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  44647. if (collidedMesh === void 0) { collidedMesh = null; }
  44648. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  44649. newPosition.multiplyInPlace(_this._collider._radius);
  44650. }
  44651. if (!collidedMesh) {
  44652. _this._previousPosition.copyFrom(_this.position);
  44653. }
  44654. else {
  44655. _this.setPosition(newPosition);
  44656. if (_this.onCollide) {
  44657. _this.onCollide(collidedMesh);
  44658. }
  44659. }
  44660. // Recompute because of constraints
  44661. var cosa = Math.cos(_this.alpha);
  44662. var sina = Math.sin(_this.alpha);
  44663. var cosb = Math.cos(_this.beta);
  44664. var sinb = Math.sin(_this.beta);
  44665. if (sinb === 0) {
  44666. sinb = 0.0001;
  44667. }
  44668. var target = _this._getTargetPosition();
  44669. _this._computationVector.copyFromFloats(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb);
  44670. target.addToRef(_this._computationVector, _this._newPosition);
  44671. _this.position.copyFrom(_this._newPosition);
  44672. var up = _this.upVector;
  44673. if (_this.allowUpsideDown && _this.beta < 0) {
  44674. up = up.clone();
  44675. up = up.negate();
  44676. }
  44677. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  44678. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  44679. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  44680. _this._collisionTriggered = false;
  44681. };
  44682. _this._target = BABYLON.Vector3.Zero();
  44683. if (target) {
  44684. _this.setTarget(target);
  44685. }
  44686. _this.alpha = alpha;
  44687. _this.beta = beta;
  44688. _this.radius = radius;
  44689. _this.getViewMatrix();
  44690. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  44691. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  44692. return _this;
  44693. }
  44694. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  44695. get: function () {
  44696. return this._target;
  44697. },
  44698. set: function (value) {
  44699. this.setTarget(value);
  44700. },
  44701. enumerable: true,
  44702. configurable: true
  44703. });
  44704. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  44705. //-- begin properties for backward compatibility for inputs
  44706. get: function () {
  44707. var pointers = this.inputs.attached["pointers"];
  44708. if (pointers)
  44709. return pointers.angularSensibilityX;
  44710. return 0;
  44711. },
  44712. set: function (value) {
  44713. var pointers = this.inputs.attached["pointers"];
  44714. if (pointers) {
  44715. pointers.angularSensibilityX = value;
  44716. }
  44717. },
  44718. enumerable: true,
  44719. configurable: true
  44720. });
  44721. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  44722. get: function () {
  44723. var pointers = this.inputs.attached["pointers"];
  44724. if (pointers)
  44725. return pointers.angularSensibilityY;
  44726. return 0;
  44727. },
  44728. set: function (value) {
  44729. var pointers = this.inputs.attached["pointers"];
  44730. if (pointers) {
  44731. pointers.angularSensibilityY = value;
  44732. }
  44733. },
  44734. enumerable: true,
  44735. configurable: true
  44736. });
  44737. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  44738. get: function () {
  44739. var pointers = this.inputs.attached["pointers"];
  44740. if (pointers)
  44741. return pointers.pinchPrecision;
  44742. return 0;
  44743. },
  44744. set: function (value) {
  44745. var pointers = this.inputs.attached["pointers"];
  44746. if (pointers) {
  44747. pointers.pinchPrecision = value;
  44748. }
  44749. },
  44750. enumerable: true,
  44751. configurable: true
  44752. });
  44753. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  44754. get: function () {
  44755. var pointers = this.inputs.attached["pointers"];
  44756. if (pointers)
  44757. return pointers.pinchDeltaPercentage;
  44758. return 0;
  44759. },
  44760. set: function (value) {
  44761. var pointers = this.inputs.attached["pointers"];
  44762. if (pointers) {
  44763. pointers.pinchDeltaPercentage = value;
  44764. }
  44765. },
  44766. enumerable: true,
  44767. configurable: true
  44768. });
  44769. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  44770. get: function () {
  44771. var pointers = this.inputs.attached["pointers"];
  44772. if (pointers)
  44773. return pointers.panningSensibility;
  44774. return 0;
  44775. },
  44776. set: function (value) {
  44777. var pointers = this.inputs.attached["pointers"];
  44778. if (pointers) {
  44779. pointers.panningSensibility = value;
  44780. }
  44781. },
  44782. enumerable: true,
  44783. configurable: true
  44784. });
  44785. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  44786. get: function () {
  44787. var keyboard = this.inputs.attached["keyboard"];
  44788. if (keyboard)
  44789. return keyboard.keysUp;
  44790. return [];
  44791. },
  44792. set: function (value) {
  44793. var keyboard = this.inputs.attached["keyboard"];
  44794. if (keyboard)
  44795. keyboard.keysUp = value;
  44796. },
  44797. enumerable: true,
  44798. configurable: true
  44799. });
  44800. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  44801. get: function () {
  44802. var keyboard = this.inputs.attached["keyboard"];
  44803. if (keyboard)
  44804. return keyboard.keysDown;
  44805. return [];
  44806. },
  44807. set: function (value) {
  44808. var keyboard = this.inputs.attached["keyboard"];
  44809. if (keyboard)
  44810. keyboard.keysDown = value;
  44811. },
  44812. enumerable: true,
  44813. configurable: true
  44814. });
  44815. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  44816. get: function () {
  44817. var keyboard = this.inputs.attached["keyboard"];
  44818. if (keyboard)
  44819. return keyboard.keysLeft;
  44820. return [];
  44821. },
  44822. set: function (value) {
  44823. var keyboard = this.inputs.attached["keyboard"];
  44824. if (keyboard)
  44825. keyboard.keysLeft = value;
  44826. },
  44827. enumerable: true,
  44828. configurable: true
  44829. });
  44830. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  44831. get: function () {
  44832. var keyboard = this.inputs.attached["keyboard"];
  44833. if (keyboard)
  44834. return keyboard.keysRight;
  44835. return [];
  44836. },
  44837. set: function (value) {
  44838. var keyboard = this.inputs.attached["keyboard"];
  44839. if (keyboard)
  44840. keyboard.keysRight = value;
  44841. },
  44842. enumerable: true,
  44843. configurable: true
  44844. });
  44845. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  44846. get: function () {
  44847. var mousewheel = this.inputs.attached["mousewheel"];
  44848. if (mousewheel)
  44849. return mousewheel.wheelPrecision;
  44850. return 0;
  44851. },
  44852. set: function (value) {
  44853. var mousewheel = this.inputs.attached["mousewheel"];
  44854. if (mousewheel)
  44855. mousewheel.wheelPrecision = value;
  44856. },
  44857. enumerable: true,
  44858. configurable: true
  44859. });
  44860. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  44861. get: function () {
  44862. var mousewheel = this.inputs.attached["mousewheel"];
  44863. if (mousewheel)
  44864. return mousewheel.wheelDeltaPercentage;
  44865. return 0;
  44866. },
  44867. set: function (value) {
  44868. var mousewheel = this.inputs.attached["mousewheel"];
  44869. if (mousewheel)
  44870. mousewheel.wheelDeltaPercentage = value;
  44871. },
  44872. enumerable: true,
  44873. configurable: true
  44874. });
  44875. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  44876. get: function () {
  44877. return this._bouncingBehavior;
  44878. },
  44879. enumerable: true,
  44880. configurable: true
  44881. });
  44882. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  44883. get: function () {
  44884. return this._bouncingBehavior != null;
  44885. },
  44886. set: function (value) {
  44887. if (value === this.useBouncingBehavior) {
  44888. return;
  44889. }
  44890. if (value) {
  44891. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  44892. this.addBehavior(this._bouncingBehavior);
  44893. }
  44894. else if (this._bouncingBehavior) {
  44895. this.removeBehavior(this._bouncingBehavior);
  44896. this._bouncingBehavior = null;
  44897. }
  44898. },
  44899. enumerable: true,
  44900. configurable: true
  44901. });
  44902. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  44903. get: function () {
  44904. return this._framingBehavior;
  44905. },
  44906. enumerable: true,
  44907. configurable: true
  44908. });
  44909. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  44910. get: function () {
  44911. return this._framingBehavior != null;
  44912. },
  44913. set: function (value) {
  44914. if (value === this.useFramingBehavior) {
  44915. return;
  44916. }
  44917. if (value) {
  44918. this._framingBehavior = new BABYLON.FramingBehavior();
  44919. this.addBehavior(this._framingBehavior);
  44920. }
  44921. else if (this._framingBehavior) {
  44922. this.removeBehavior(this._framingBehavior);
  44923. this._framingBehavior = null;
  44924. }
  44925. },
  44926. enumerable: true,
  44927. configurable: true
  44928. });
  44929. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  44930. get: function () {
  44931. return this._autoRotationBehavior;
  44932. },
  44933. enumerable: true,
  44934. configurable: true
  44935. });
  44936. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  44937. get: function () {
  44938. return this._autoRotationBehavior != null;
  44939. },
  44940. set: function (value) {
  44941. if (value === this.useAutoRotationBehavior) {
  44942. return;
  44943. }
  44944. if (value) {
  44945. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  44946. this.addBehavior(this._autoRotationBehavior);
  44947. }
  44948. else if (this._autoRotationBehavior) {
  44949. this.removeBehavior(this._autoRotationBehavior);
  44950. this._autoRotationBehavior = null;
  44951. }
  44952. },
  44953. enumerable: true,
  44954. configurable: true
  44955. });
  44956. // Cache
  44957. ArcRotateCamera.prototype._initCache = function () {
  44958. _super.prototype._initCache.call(this);
  44959. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  44960. this._cache.alpha = undefined;
  44961. this._cache.beta = undefined;
  44962. this._cache.radius = undefined;
  44963. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  44964. };
  44965. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  44966. if (!ignoreParentClass) {
  44967. _super.prototype._updateCache.call(this);
  44968. }
  44969. this._cache._target.copyFrom(this._getTargetPosition());
  44970. this._cache.alpha = this.alpha;
  44971. this._cache.beta = this.beta;
  44972. this._cache.radius = this.radius;
  44973. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  44974. };
  44975. ArcRotateCamera.prototype._getTargetPosition = function () {
  44976. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  44977. var pos = this._targetHost.getAbsolutePosition();
  44978. if (this._targetBoundingCenter) {
  44979. pos.addToRef(this._targetBoundingCenter, this._target);
  44980. }
  44981. else {
  44982. this._target.copyFrom(pos);
  44983. }
  44984. }
  44985. var lockedTargetPosition = this._getLockedTargetPosition();
  44986. if (lockedTargetPosition) {
  44987. return lockedTargetPosition;
  44988. }
  44989. return this._target;
  44990. };
  44991. ArcRotateCamera.prototype.storeState = function () {
  44992. this._storedAlpha = this.alpha;
  44993. this._storedBeta = this.beta;
  44994. this._storedRadius = this.radius;
  44995. this._storedTarget = this._getTargetPosition().clone();
  44996. return _super.prototype.storeState.call(this);
  44997. };
  44998. /**
  44999. * Restored camera state. You must call storeState() first
  45000. */
  45001. ArcRotateCamera.prototype._restoreStateValues = function () {
  45002. if (!_super.prototype._restoreStateValues.call(this)) {
  45003. return false;
  45004. }
  45005. this.alpha = this._storedAlpha;
  45006. this.beta = this._storedBeta;
  45007. this.radius = this._storedRadius;
  45008. this.setTarget(this._storedTarget.clone());
  45009. this.inertialAlphaOffset = 0;
  45010. this.inertialBetaOffset = 0;
  45011. this.inertialRadiusOffset = 0;
  45012. this.inertialPanningX = 0;
  45013. this.inertialPanningY = 0;
  45014. return true;
  45015. };
  45016. // Synchronized
  45017. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  45018. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  45019. return false;
  45020. return this._cache._target.equals(this._getTargetPosition())
  45021. && this._cache.alpha === this.alpha
  45022. && this._cache.beta === this.beta
  45023. && this._cache.radius === this.radius
  45024. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  45025. };
  45026. // Methods
  45027. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  45028. var _this = this;
  45029. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  45030. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  45031. this._useCtrlForPanning = useCtrlForPanning;
  45032. this._panningMouseButton = panningMouseButton;
  45033. this.inputs.attachElement(element, noPreventDefault);
  45034. this._reset = function () {
  45035. _this.inertialAlphaOffset = 0;
  45036. _this.inertialBetaOffset = 0;
  45037. _this.inertialRadiusOffset = 0;
  45038. _this.inertialPanningX = 0;
  45039. _this.inertialPanningY = 0;
  45040. };
  45041. };
  45042. ArcRotateCamera.prototype.detachControl = function (element) {
  45043. this.inputs.detachElement(element);
  45044. if (this._reset) {
  45045. this._reset();
  45046. }
  45047. };
  45048. ArcRotateCamera.prototype._checkInputs = function () {
  45049. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  45050. if (this._collisionTriggered) {
  45051. return;
  45052. }
  45053. this.inputs.checkInputs();
  45054. // Inertia
  45055. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  45056. if (this.getScene().useRightHandedSystem) {
  45057. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  45058. }
  45059. else {
  45060. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  45061. }
  45062. this.beta += this.inertialBetaOffset;
  45063. this.radius -= this.inertialRadiusOffset;
  45064. this.inertialAlphaOffset *= this.inertia;
  45065. this.inertialBetaOffset *= this.inertia;
  45066. this.inertialRadiusOffset *= this.inertia;
  45067. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  45068. this.inertialAlphaOffset = 0;
  45069. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  45070. this.inertialBetaOffset = 0;
  45071. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  45072. this.inertialRadiusOffset = 0;
  45073. }
  45074. // Panning inertia
  45075. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  45076. if (!this._localDirection) {
  45077. this._localDirection = BABYLON.Vector3.Zero();
  45078. this._transformedDirection = BABYLON.Vector3.Zero();
  45079. }
  45080. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  45081. this._localDirection.multiplyInPlace(this.panningAxis);
  45082. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  45083. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  45084. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  45085. if (!this.panningAxis.y) {
  45086. this._transformedDirection.y = 0;
  45087. }
  45088. if (!this._targetHost) {
  45089. if (this.panningDistanceLimit) {
  45090. this._transformedDirection.addInPlace(this._target);
  45091. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  45092. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  45093. this._target.copyFrom(this._transformedDirection);
  45094. }
  45095. }
  45096. else {
  45097. this._target.addInPlace(this._transformedDirection);
  45098. }
  45099. }
  45100. this.inertialPanningX *= this.panningInertia;
  45101. this.inertialPanningY *= this.panningInertia;
  45102. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  45103. this.inertialPanningX = 0;
  45104. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  45105. this.inertialPanningY = 0;
  45106. }
  45107. // Limits
  45108. this._checkLimits();
  45109. _super.prototype._checkInputs.call(this);
  45110. };
  45111. ArcRotateCamera.prototype._checkLimits = function () {
  45112. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  45113. if (this.allowUpsideDown && this.beta > Math.PI) {
  45114. this.beta = this.beta - (2 * Math.PI);
  45115. }
  45116. }
  45117. else {
  45118. if (this.beta < this.lowerBetaLimit) {
  45119. this.beta = this.lowerBetaLimit;
  45120. }
  45121. }
  45122. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  45123. if (this.allowUpsideDown && this.beta < -Math.PI) {
  45124. this.beta = this.beta + (2 * Math.PI);
  45125. }
  45126. }
  45127. else {
  45128. if (this.beta > this.upperBetaLimit) {
  45129. this.beta = this.upperBetaLimit;
  45130. }
  45131. }
  45132. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  45133. this.alpha = this.lowerAlphaLimit;
  45134. }
  45135. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  45136. this.alpha = this.upperAlphaLimit;
  45137. }
  45138. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  45139. this.radius = this.lowerRadiusLimit;
  45140. }
  45141. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  45142. this.radius = this.upperRadiusLimit;
  45143. }
  45144. };
  45145. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  45146. this.position.subtractToRef(this._getTargetPosition(), this._computationVector);
  45147. this.radius = this._computationVector.length();
  45148. if (this.radius === 0) {
  45149. this.radius = 0.0001; // Just to avoid division by zero
  45150. }
  45151. // Alpha
  45152. this.alpha = Math.acos(this._computationVector.x / Math.sqrt(Math.pow(this._computationVector.x, 2) + Math.pow(this._computationVector.z, 2)));
  45153. if (this._computationVector.z < 0) {
  45154. this.alpha = 2 * Math.PI - this.alpha;
  45155. }
  45156. // Beta
  45157. this.beta = Math.acos(this._computationVector.y / this.radius);
  45158. this._checkLimits();
  45159. };
  45160. ArcRotateCamera.prototype.setPosition = function (position) {
  45161. if (this.position.equals(position)) {
  45162. return;
  45163. }
  45164. this.position.copyFrom(position);
  45165. this.rebuildAnglesAndRadius();
  45166. };
  45167. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  45168. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  45169. if (allowSamePosition === void 0) { allowSamePosition = false; }
  45170. if (target.getBoundingInfo) {
  45171. if (toBoundingCenter) {
  45172. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  45173. }
  45174. else {
  45175. this._targetBoundingCenter = null;
  45176. }
  45177. this._targetHost = target;
  45178. this._target = this._getTargetPosition();
  45179. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  45180. }
  45181. else {
  45182. var newTarget = target;
  45183. var currentTarget = this._getTargetPosition();
  45184. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  45185. return;
  45186. }
  45187. this._targetHost = null;
  45188. this._target = newTarget;
  45189. this._targetBoundingCenter = null;
  45190. this.onMeshTargetChangedObservable.notifyObservers(null);
  45191. }
  45192. this.rebuildAnglesAndRadius();
  45193. };
  45194. ArcRotateCamera.prototype._getViewMatrix = function () {
  45195. // Compute
  45196. var cosa = Math.cos(this.alpha);
  45197. var sina = Math.sin(this.alpha);
  45198. var cosb = Math.cos(this.beta);
  45199. var sinb = Math.sin(this.beta);
  45200. if (sinb === 0) {
  45201. sinb = 0.0001;
  45202. }
  45203. var target = this._getTargetPosition();
  45204. this._computationVector.copyFromFloats(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb);
  45205. target.addToRef(this._computationVector, this._newPosition);
  45206. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  45207. if (!this._collider) {
  45208. this._collider = new BABYLON.Collider();
  45209. }
  45210. this._collider._radius = this.collisionRadius;
  45211. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  45212. this._collisionTriggered = true;
  45213. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  45214. }
  45215. else {
  45216. this.position.copyFrom(this._newPosition);
  45217. var up = this.upVector;
  45218. if (this.allowUpsideDown && sinb < 0) {
  45219. up = up.clone();
  45220. up = up.negate();
  45221. }
  45222. if (this.getScene().useRightHandedSystem) {
  45223. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  45224. }
  45225. else {
  45226. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  45227. }
  45228. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  45229. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  45230. }
  45231. this._currentTarget = target;
  45232. return this._viewMatrix;
  45233. };
  45234. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  45235. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  45236. meshes = meshes || this.getScene().meshes;
  45237. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  45238. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  45239. this.radius = distance * this.zoomOnFactor;
  45240. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  45241. };
  45242. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  45243. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  45244. var meshesOrMinMaxVector;
  45245. var distance;
  45246. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  45247. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  45248. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  45249. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  45250. }
  45251. else {
  45252. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  45253. meshesOrMinMaxVector = minMaxVectorAndDistance;
  45254. distance = minMaxVectorAndDistance.distance;
  45255. }
  45256. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  45257. if (!doNotUpdateMaxZ) {
  45258. this.maxZ = distance * 2;
  45259. }
  45260. };
  45261. /**
  45262. * @override
  45263. * Override Camera.createRigCamera
  45264. */
  45265. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  45266. var alphaShift = 0;
  45267. switch (this.cameraRigMode) {
  45268. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  45269. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  45270. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  45271. case BABYLON.Camera.RIG_MODE_VR:
  45272. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  45273. break;
  45274. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  45275. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  45276. break;
  45277. }
  45278. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  45279. rigCam._cameraRigParams = {};
  45280. return rigCam;
  45281. };
  45282. /**
  45283. * @override
  45284. * Override Camera._updateRigCameras
  45285. */
  45286. ArcRotateCamera.prototype._updateRigCameras = function () {
  45287. var camLeft = this._rigCameras[0];
  45288. var camRight = this._rigCameras[1];
  45289. camLeft.beta = camRight.beta = this.beta;
  45290. camLeft.radius = camRight.radius = this.radius;
  45291. switch (this.cameraRigMode) {
  45292. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  45293. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  45294. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  45295. case BABYLON.Camera.RIG_MODE_VR:
  45296. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  45297. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  45298. break;
  45299. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  45300. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  45301. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  45302. break;
  45303. }
  45304. _super.prototype._updateRigCameras.call(this);
  45305. };
  45306. ArcRotateCamera.prototype.dispose = function () {
  45307. this.inputs.clear();
  45308. _super.prototype.dispose.call(this);
  45309. };
  45310. ArcRotateCamera.prototype.getClassName = function () {
  45311. return "ArcRotateCamera";
  45312. };
  45313. __decorate([
  45314. BABYLON.serialize()
  45315. ], ArcRotateCamera.prototype, "alpha", void 0);
  45316. __decorate([
  45317. BABYLON.serialize()
  45318. ], ArcRotateCamera.prototype, "beta", void 0);
  45319. __decorate([
  45320. BABYLON.serialize()
  45321. ], ArcRotateCamera.prototype, "radius", void 0);
  45322. __decorate([
  45323. BABYLON.serializeAsVector3("target")
  45324. ], ArcRotateCamera.prototype, "_target", void 0);
  45325. __decorate([
  45326. BABYLON.serialize()
  45327. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  45328. __decorate([
  45329. BABYLON.serialize()
  45330. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  45331. __decorate([
  45332. BABYLON.serialize()
  45333. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  45334. __decorate([
  45335. BABYLON.serialize()
  45336. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  45337. __decorate([
  45338. BABYLON.serialize()
  45339. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  45340. __decorate([
  45341. BABYLON.serialize()
  45342. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  45343. __decorate([
  45344. BABYLON.serialize()
  45345. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  45346. __decorate([
  45347. BABYLON.serialize()
  45348. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  45349. __decorate([
  45350. BABYLON.serialize()
  45351. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  45352. __decorate([
  45353. BABYLON.serialize()
  45354. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  45355. __decorate([
  45356. BABYLON.serialize()
  45357. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  45358. __decorate([
  45359. BABYLON.serialize()
  45360. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  45361. __decorate([
  45362. BABYLON.serialize()
  45363. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  45364. __decorate([
  45365. BABYLON.serializeAsVector3()
  45366. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  45367. __decorate([
  45368. BABYLON.serialize()
  45369. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  45370. __decorate([
  45371. BABYLON.serialize()
  45372. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  45373. __decorate([
  45374. BABYLON.serialize()
  45375. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  45376. return ArcRotateCamera;
  45377. }(BABYLON.TargetCamera));
  45378. BABYLON.ArcRotateCamera = ArcRotateCamera;
  45379. })(BABYLON || (BABYLON = {}));
  45380. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  45381. var BABYLON;
  45382. (function (BABYLON) {
  45383. /**
  45384. * The HemisphericLight simulates the ambient environment light,
  45385. * so the passed direction is the light reflection direction, not the incoming direction.
  45386. */
  45387. var HemisphericLight = /** @class */ (function (_super) {
  45388. __extends(HemisphericLight, _super);
  45389. /**
  45390. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  45391. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  45392. * The HemisphericLight can't cast shadows.
  45393. * Documentation : http://doc.babylonjs.com/tutorials/lights
  45394. * @param name The friendly name of the light
  45395. * @param direction The direction of the light reflection
  45396. * @param scene The scene the light belongs to
  45397. */
  45398. function HemisphericLight(name, direction, scene) {
  45399. var _this = _super.call(this, name, scene) || this;
  45400. /**
  45401. * The groundColor is the light in the opposite direction to the one specified during creation.
  45402. * 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.
  45403. */
  45404. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  45405. _this.direction = direction || BABYLON.Vector3.Up();
  45406. return _this;
  45407. }
  45408. HemisphericLight.prototype._buildUniformLayout = function () {
  45409. this._uniformBuffer.addUniform("vLightData", 4);
  45410. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  45411. this._uniformBuffer.addUniform("vLightSpecular", 3);
  45412. this._uniformBuffer.addUniform("vLightGround", 3);
  45413. this._uniformBuffer.addUniform("shadowsInfo", 3);
  45414. this._uniformBuffer.addUniform("depthValues", 2);
  45415. this._uniformBuffer.create();
  45416. };
  45417. /**
  45418. * Returns the string "HemisphericLight".
  45419. * @return The class name
  45420. */
  45421. HemisphericLight.prototype.getClassName = function () {
  45422. return "HemisphericLight";
  45423. };
  45424. /**
  45425. * Sets the HemisphericLight direction towards the passed target (Vector3).
  45426. * Returns the updated direction.
  45427. * @param target The target the direction should point to
  45428. * @return The computed direction
  45429. */
  45430. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  45431. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  45432. return this.direction;
  45433. };
  45434. /**
  45435. * Returns the shadow generator associated to the light.
  45436. * @returns Always null for hemispheric lights because it does not support shadows.
  45437. */
  45438. HemisphericLight.prototype.getShadowGenerator = function () {
  45439. return null;
  45440. };
  45441. /**
  45442. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  45443. * @param effect The effect to update
  45444. * @param lightIndex The index of the light in the effect to update
  45445. * @returns The hemispheric light
  45446. */
  45447. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  45448. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  45449. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  45450. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  45451. return this;
  45452. };
  45453. /**
  45454. * @ignore internal use only.
  45455. */
  45456. HemisphericLight.prototype._getWorldMatrix = function () {
  45457. if (!this._worldMatrix) {
  45458. this._worldMatrix = BABYLON.Matrix.Identity();
  45459. }
  45460. return this._worldMatrix;
  45461. };
  45462. /**
  45463. * Returns the integer 3.
  45464. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  45465. */
  45466. HemisphericLight.prototype.getTypeID = function () {
  45467. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  45468. };
  45469. __decorate([
  45470. BABYLON.serializeAsColor3()
  45471. ], HemisphericLight.prototype, "groundColor", void 0);
  45472. __decorate([
  45473. BABYLON.serializeAsVector3()
  45474. ], HemisphericLight.prototype, "direction", void 0);
  45475. return HemisphericLight;
  45476. }(BABYLON.Light));
  45477. BABYLON.HemisphericLight = HemisphericLight;
  45478. })(BABYLON || (BABYLON = {}));
  45479. //# sourceMappingURL=babylon.hemisphericLight.js.map
  45480. var BABYLON;
  45481. (function (BABYLON) {
  45482. /**
  45483. * Base implementation of @see IShadowLight
  45484. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  45485. */
  45486. var ShadowLight = /** @class */ (function (_super) {
  45487. __extends(ShadowLight, _super);
  45488. function ShadowLight() {
  45489. var _this = _super !== null && _super.apply(this, arguments) || this;
  45490. _this._needProjectionMatrixCompute = true;
  45491. return _this;
  45492. }
  45493. ShadowLight.prototype._setPosition = function (value) {
  45494. this._position = value;
  45495. };
  45496. Object.defineProperty(ShadowLight.prototype, "position", {
  45497. /**
  45498. * Sets the position the shadow will be casted from. Also use as the light position for both
  45499. * point and spot lights.
  45500. */
  45501. get: function () {
  45502. return this._position;
  45503. },
  45504. /**
  45505. * Sets the position the shadow will be casted from. Also use as the light position for both
  45506. * point and spot lights.
  45507. */
  45508. set: function (value) {
  45509. this._setPosition(value);
  45510. },
  45511. enumerable: true,
  45512. configurable: true
  45513. });
  45514. ShadowLight.prototype._setDirection = function (value) {
  45515. this._direction = value;
  45516. };
  45517. Object.defineProperty(ShadowLight.prototype, "direction", {
  45518. /**
  45519. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  45520. * Also use as the light direction on spot and directional lights.
  45521. */
  45522. get: function () {
  45523. return this._direction;
  45524. },
  45525. /**
  45526. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  45527. * Also use as the light direction on spot and directional lights.
  45528. */
  45529. set: function (value) {
  45530. this._setDirection(value);
  45531. },
  45532. enumerable: true,
  45533. configurable: true
  45534. });
  45535. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  45536. /**
  45537. * Gets the shadow projection clipping minimum z value.
  45538. */
  45539. get: function () {
  45540. return this._shadowMinZ;
  45541. },
  45542. /**
  45543. * Sets the shadow projection clipping minimum z value.
  45544. */
  45545. set: function (value) {
  45546. this._shadowMinZ = value;
  45547. this.forceProjectionMatrixCompute();
  45548. },
  45549. enumerable: true,
  45550. configurable: true
  45551. });
  45552. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  45553. /**
  45554. * Sets the shadow projection clipping maximum z value.
  45555. */
  45556. get: function () {
  45557. return this._shadowMaxZ;
  45558. },
  45559. /**
  45560. * Gets the shadow projection clipping maximum z value.
  45561. */
  45562. set: function (value) {
  45563. this._shadowMaxZ = value;
  45564. this.forceProjectionMatrixCompute();
  45565. },
  45566. enumerable: true,
  45567. configurable: true
  45568. });
  45569. /**
  45570. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  45571. * @returns true if the information has been computed, false if it does not need to (no parenting)
  45572. */
  45573. ShadowLight.prototype.computeTransformedInformation = function () {
  45574. if (this.parent && this.parent.getWorldMatrix) {
  45575. if (!this.transformedPosition) {
  45576. this.transformedPosition = BABYLON.Vector3.Zero();
  45577. }
  45578. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  45579. // In case the direction is present.
  45580. if (this.direction) {
  45581. if (!this.transformedDirection) {
  45582. this.transformedDirection = BABYLON.Vector3.Zero();
  45583. }
  45584. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  45585. }
  45586. return true;
  45587. }
  45588. return false;
  45589. };
  45590. /**
  45591. * Return the depth scale used for the shadow map.
  45592. * @returns the depth scale.
  45593. */
  45594. ShadowLight.prototype.getDepthScale = function () {
  45595. return 50.0;
  45596. };
  45597. /**
  45598. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  45599. * @param faceIndex The index of the face we are computed the direction to generate shadow
  45600. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  45601. */
  45602. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  45603. return this.transformedDirection ? this.transformedDirection : this.direction;
  45604. };
  45605. /**
  45606. * Returns the ShadowLight absolute position in the World.
  45607. * @returns the position vector in world space
  45608. */
  45609. ShadowLight.prototype.getAbsolutePosition = function () {
  45610. return this.transformedPosition ? this.transformedPosition : this.position;
  45611. };
  45612. /**
  45613. * Sets the ShadowLight direction toward the passed target.
  45614. * @param target The point tot target in local space
  45615. * @returns the updated ShadowLight direction
  45616. */
  45617. ShadowLight.prototype.setDirectionToTarget = function (target) {
  45618. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  45619. return this.direction;
  45620. };
  45621. /**
  45622. * Returns the light rotation in euler definition.
  45623. * @returns the x y z rotation in local space.
  45624. */
  45625. ShadowLight.prototype.getRotation = function () {
  45626. this.direction.normalize();
  45627. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  45628. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  45629. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  45630. };
  45631. /**
  45632. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  45633. * @returns true if a cube texture needs to be use
  45634. */
  45635. ShadowLight.prototype.needCube = function () {
  45636. return false;
  45637. };
  45638. /**
  45639. * Detects if the projection matrix requires to be recomputed this frame.
  45640. * @returns true if it requires to be recomputed otherwise, false.
  45641. */
  45642. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  45643. return this._needProjectionMatrixCompute;
  45644. };
  45645. /**
  45646. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  45647. */
  45648. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  45649. this._needProjectionMatrixCompute = true;
  45650. };
  45651. /**
  45652. * Get the world matrix of the sahdow lights.
  45653. * @ignore Internal Use Only
  45654. */
  45655. ShadowLight.prototype._getWorldMatrix = function () {
  45656. if (!this._worldMatrix) {
  45657. this._worldMatrix = BABYLON.Matrix.Identity();
  45658. }
  45659. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  45660. return this._worldMatrix;
  45661. };
  45662. /**
  45663. * Gets the minZ used for shadow according to both the scene and the light.
  45664. * @param activeCamera The camera we are returning the min for
  45665. * @returns the depth min z
  45666. */
  45667. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  45668. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  45669. };
  45670. /**
  45671. * Gets the maxZ used for shadow according to both the scene and the light.
  45672. * @param activeCamera The camera we are returning the max for
  45673. * @returns the depth max z
  45674. */
  45675. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  45676. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  45677. };
  45678. /**
  45679. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  45680. * @param matrix The materix to updated with the projection information
  45681. * @param viewMatrix The transform matrix of the light
  45682. * @param renderList The list of mesh to render in the map
  45683. * @returns The current light
  45684. */
  45685. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  45686. if (this.customProjectionMatrixBuilder) {
  45687. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  45688. }
  45689. else {
  45690. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  45691. }
  45692. return this;
  45693. };
  45694. __decorate([
  45695. BABYLON.serializeAsVector3()
  45696. ], ShadowLight.prototype, "position", null);
  45697. __decorate([
  45698. BABYLON.serializeAsVector3()
  45699. ], ShadowLight.prototype, "direction", null);
  45700. __decorate([
  45701. BABYLON.serialize()
  45702. ], ShadowLight.prototype, "shadowMinZ", null);
  45703. __decorate([
  45704. BABYLON.serialize()
  45705. ], ShadowLight.prototype, "shadowMaxZ", null);
  45706. return ShadowLight;
  45707. }(BABYLON.Light));
  45708. BABYLON.ShadowLight = ShadowLight;
  45709. })(BABYLON || (BABYLON = {}));
  45710. //# sourceMappingURL=babylon.shadowLight.js.map
  45711. var BABYLON;
  45712. (function (BABYLON) {
  45713. /**
  45714. * A point light is a light defined by an unique point in world space.
  45715. * The light is emitted in every direction from this point.
  45716. * A good example of a point light is a standard light bulb.
  45717. * Documentation: https://doc.babylonjs.com/babylon101/lights
  45718. */
  45719. var PointLight = /** @class */ (function (_super) {
  45720. __extends(PointLight, _super);
  45721. /**
  45722. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  45723. * A PointLight emits the light in every direction.
  45724. * It can cast shadows.
  45725. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  45726. * ```javascript
  45727. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  45728. * ```
  45729. * Documentation : http://doc.babylonjs.com/tutorials/lights
  45730. * @param name The light friendly name
  45731. * @param position The position of the point light in the scene
  45732. * @param scene The scene the lights belongs to
  45733. */
  45734. function PointLight(name, position, scene) {
  45735. var _this = _super.call(this, name, scene) || this;
  45736. _this._shadowAngle = Math.PI / 2;
  45737. _this.position = position;
  45738. return _this;
  45739. }
  45740. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  45741. /**
  45742. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  45743. * This specifies what angle the shadow will use to be created.
  45744. *
  45745. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  45746. */
  45747. get: function () {
  45748. return this._shadowAngle;
  45749. },
  45750. /**
  45751. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  45752. * This specifies what angle the shadow will use to be created.
  45753. *
  45754. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  45755. */
  45756. set: function (value) {
  45757. this._shadowAngle = value;
  45758. this.forceProjectionMatrixCompute();
  45759. },
  45760. enumerable: true,
  45761. configurable: true
  45762. });
  45763. Object.defineProperty(PointLight.prototype, "direction", {
  45764. /**
  45765. * Gets the direction if it has been set.
  45766. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  45767. */
  45768. get: function () {
  45769. return this._direction;
  45770. },
  45771. /**
  45772. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  45773. */
  45774. set: function (value) {
  45775. var previousNeedCube = this.needCube();
  45776. this._direction = value;
  45777. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  45778. this._shadowGenerator.recreateShadowMap();
  45779. }
  45780. },
  45781. enumerable: true,
  45782. configurable: true
  45783. });
  45784. /**
  45785. * Returns the string "PointLight"
  45786. * @returns the class name
  45787. */
  45788. PointLight.prototype.getClassName = function () {
  45789. return "PointLight";
  45790. };
  45791. /**
  45792. * Returns the integer 0.
  45793. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  45794. */
  45795. PointLight.prototype.getTypeID = function () {
  45796. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  45797. };
  45798. /**
  45799. * Specifies wether or not the shadowmap should be a cube texture.
  45800. * @returns true if the shadowmap needs to be a cube texture.
  45801. */
  45802. PointLight.prototype.needCube = function () {
  45803. return !this.direction;
  45804. };
  45805. /**
  45806. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  45807. * @param faceIndex The index of the face we are computed the direction to generate shadow
  45808. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  45809. */
  45810. PointLight.prototype.getShadowDirection = function (faceIndex) {
  45811. if (this.direction) {
  45812. return _super.prototype.getShadowDirection.call(this, faceIndex);
  45813. }
  45814. else {
  45815. switch (faceIndex) {
  45816. case 0:
  45817. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  45818. case 1:
  45819. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  45820. case 2:
  45821. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  45822. case 3:
  45823. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  45824. case 4:
  45825. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  45826. case 5:
  45827. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  45828. }
  45829. }
  45830. return BABYLON.Vector3.Zero();
  45831. };
  45832. /**
  45833. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  45834. * - fov = PI / 2
  45835. * - aspect ratio : 1.0
  45836. * - z-near and far equal to the active camera minZ and maxZ.
  45837. * Returns the PointLight.
  45838. */
  45839. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  45840. var activeCamera = this.getScene().activeCamera;
  45841. if (!activeCamera) {
  45842. return;
  45843. }
  45844. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  45845. };
  45846. PointLight.prototype._buildUniformLayout = function () {
  45847. this._uniformBuffer.addUniform("vLightData", 4);
  45848. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  45849. this._uniformBuffer.addUniform("vLightSpecular", 3);
  45850. this._uniformBuffer.addUniform("shadowsInfo", 3);
  45851. this._uniformBuffer.addUniform("depthValues", 2);
  45852. this._uniformBuffer.create();
  45853. };
  45854. /**
  45855. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  45856. * @param effect The effect to update
  45857. * @param lightIndex The index of the light in the effect to update
  45858. * @returns The point light
  45859. */
  45860. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  45861. if (this.computeTransformedInformation()) {
  45862. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  45863. return this;
  45864. }
  45865. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  45866. return this;
  45867. };
  45868. __decorate([
  45869. BABYLON.serialize()
  45870. ], PointLight.prototype, "shadowAngle", null);
  45871. return PointLight;
  45872. }(BABYLON.ShadowLight));
  45873. BABYLON.PointLight = PointLight;
  45874. })(BABYLON || (BABYLON = {}));
  45875. //# sourceMappingURL=babylon.pointLight.js.map
  45876. var BABYLON;
  45877. (function (BABYLON) {
  45878. /**
  45879. * A directional light is defined by a direction (what a surprise!).
  45880. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  45881. * 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.
  45882. * Documentation: https://doc.babylonjs.com/babylon101/lights
  45883. */
  45884. var DirectionalLight = /** @class */ (function (_super) {
  45885. __extends(DirectionalLight, _super);
  45886. /**
  45887. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  45888. * The directional light is emitted from everywhere in the given direction.
  45889. * It can cast shawdows.
  45890. * Documentation : http://doc.babylonjs.com/tutorials/lights
  45891. * @param name The friendly name of the light
  45892. * @param direction The direction of the light
  45893. * @param scene The scene the light belongs to
  45894. */
  45895. function DirectionalLight(name, direction, scene) {
  45896. var _this = _super.call(this, name, scene) || this;
  45897. _this._shadowFrustumSize = 0;
  45898. _this._shadowOrthoScale = 0.5;
  45899. /**
  45900. * Automatically compute the projection matrix to best fit (including all the casters)
  45901. * on each frame.
  45902. */
  45903. _this.autoUpdateExtends = true;
  45904. // Cache
  45905. _this._orthoLeft = Number.MAX_VALUE;
  45906. _this._orthoRight = Number.MIN_VALUE;
  45907. _this._orthoTop = Number.MIN_VALUE;
  45908. _this._orthoBottom = Number.MAX_VALUE;
  45909. _this.position = direction.scale(-1.0);
  45910. _this.direction = direction;
  45911. return _this;
  45912. }
  45913. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  45914. /**
  45915. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  45916. */
  45917. get: function () {
  45918. return this._shadowFrustumSize;
  45919. },
  45920. /**
  45921. * Specifies a fix frustum size for the shadow generation.
  45922. */
  45923. set: function (value) {
  45924. this._shadowFrustumSize = value;
  45925. this.forceProjectionMatrixCompute();
  45926. },
  45927. enumerable: true,
  45928. configurable: true
  45929. });
  45930. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  45931. /**
  45932. * Gets the shadow projection scale against the optimal computed one.
  45933. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  45934. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  45935. */
  45936. get: function () {
  45937. return this._shadowOrthoScale;
  45938. },
  45939. /**
  45940. * Sets the shadow projection scale against the optimal computed one.
  45941. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  45942. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  45943. */
  45944. set: function (value) {
  45945. this._shadowOrthoScale = value;
  45946. this.forceProjectionMatrixCompute();
  45947. },
  45948. enumerable: true,
  45949. configurable: true
  45950. });
  45951. /**
  45952. * Returns the string "DirectionalLight".
  45953. * @return The class name
  45954. */
  45955. DirectionalLight.prototype.getClassName = function () {
  45956. return "DirectionalLight";
  45957. };
  45958. /**
  45959. * Returns the integer 1.
  45960. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  45961. */
  45962. DirectionalLight.prototype.getTypeID = function () {
  45963. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  45964. };
  45965. /**
  45966. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  45967. * Returns the DirectionalLight Shadow projection matrix.
  45968. */
  45969. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  45970. if (this.shadowFrustumSize > 0) {
  45971. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  45972. }
  45973. else {
  45974. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  45975. }
  45976. };
  45977. /**
  45978. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  45979. * Returns the DirectionalLight Shadow projection matrix.
  45980. */
  45981. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  45982. var activeCamera = this.getScene().activeCamera;
  45983. if (!activeCamera) {
  45984. return;
  45985. }
  45986. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  45987. };
  45988. /**
  45989. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  45990. * Returns the DirectionalLight Shadow projection matrix.
  45991. */
  45992. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  45993. var activeCamera = this.getScene().activeCamera;
  45994. if (!activeCamera) {
  45995. return;
  45996. }
  45997. // Check extends
  45998. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  45999. var tempVector3 = BABYLON.Vector3.Zero();
  46000. this._orthoLeft = Number.MAX_VALUE;
  46001. this._orthoRight = Number.MIN_VALUE;
  46002. this._orthoTop = Number.MIN_VALUE;
  46003. this._orthoBottom = Number.MAX_VALUE;
  46004. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  46005. var mesh = renderList[meshIndex];
  46006. if (!mesh) {
  46007. continue;
  46008. }
  46009. var boundingInfo = mesh.getBoundingInfo();
  46010. var boundingBox = boundingInfo.boundingBox;
  46011. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  46012. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  46013. if (tempVector3.x < this._orthoLeft)
  46014. this._orthoLeft = tempVector3.x;
  46015. if (tempVector3.y < this._orthoBottom)
  46016. this._orthoBottom = tempVector3.y;
  46017. if (tempVector3.x > this._orthoRight)
  46018. this._orthoRight = tempVector3.x;
  46019. if (tempVector3.y > this._orthoTop)
  46020. this._orthoTop = tempVector3.y;
  46021. }
  46022. }
  46023. }
  46024. var xOffset = this._orthoRight - this._orthoLeft;
  46025. var yOffset = this._orthoTop - this._orthoBottom;
  46026. 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);
  46027. };
  46028. DirectionalLight.prototype._buildUniformLayout = function () {
  46029. this._uniformBuffer.addUniform("vLightData", 4);
  46030. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  46031. this._uniformBuffer.addUniform("vLightSpecular", 3);
  46032. this._uniformBuffer.addUniform("shadowsInfo", 3);
  46033. this._uniformBuffer.addUniform("depthValues", 2);
  46034. this._uniformBuffer.create();
  46035. };
  46036. /**
  46037. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  46038. * @param effect The effect to update
  46039. * @param lightIndex The index of the light in the effect to update
  46040. * @returns The directional light
  46041. */
  46042. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  46043. if (this.computeTransformedInformation()) {
  46044. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  46045. return this;
  46046. }
  46047. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  46048. return this;
  46049. };
  46050. /**
  46051. * Gets the minZ used for shadow according to both the scene and the light.
  46052. *
  46053. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  46054. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  46055. * @param activeCamera The camera we are returning the min for
  46056. * @returns the depth min z
  46057. */
  46058. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  46059. return 1;
  46060. };
  46061. /**
  46062. * Gets the maxZ used for shadow according to both the scene and the light.
  46063. *
  46064. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  46065. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  46066. * @param activeCamera The camera we are returning the max for
  46067. * @returns the depth max z
  46068. */
  46069. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  46070. return 1;
  46071. };
  46072. __decorate([
  46073. BABYLON.serialize()
  46074. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  46075. __decorate([
  46076. BABYLON.serialize()
  46077. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  46078. __decorate([
  46079. BABYLON.serialize()
  46080. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  46081. return DirectionalLight;
  46082. }(BABYLON.ShadowLight));
  46083. BABYLON.DirectionalLight = DirectionalLight;
  46084. })(BABYLON || (BABYLON = {}));
  46085. //# sourceMappingURL=babylon.directionalLight.js.map
  46086. var BABYLON;
  46087. (function (BABYLON) {
  46088. /**
  46089. * A spot light is defined by a position, a direction, an angle, and an exponent.
  46090. * These values define a cone of light starting from the position, emitting toward the direction.
  46091. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  46092. * and the exponent defines the speed of the decay of the light with distance (reach).
  46093. * Documentation: https://doc.babylonjs.com/babylon101/lights
  46094. */
  46095. var SpotLight = /** @class */ (function (_super) {
  46096. __extends(SpotLight, _super);
  46097. /**
  46098. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  46099. * It can cast shadows.
  46100. * Documentation : http://doc.babylonjs.com/tutorials/lights
  46101. * @param name The light friendly name
  46102. * @param position The position of the spot light in the scene
  46103. * @param direction The direction of the light in the scene
  46104. * @param angle The cone angle of the light in Radians
  46105. * @param exponent The light decay speed with the distance from the emission spot
  46106. * @param scene The scene the lights belongs to
  46107. */
  46108. function SpotLight(name, position, direction, angle, exponent, scene) {
  46109. var _this = _super.call(this, name, scene) || this;
  46110. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  46111. _this._projectionTextureLightNear = 1e-6;
  46112. _this._projectionTextureLightFar = 1000.0;
  46113. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  46114. _this._projectionTextureViewLightDirty = true;
  46115. _this._projectionTextureProjectionLightDirty = true;
  46116. _this._projectionTextureDirty = true;
  46117. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  46118. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  46119. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  46120. _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);
  46121. _this.position = position;
  46122. _this.direction = direction;
  46123. _this.angle = angle;
  46124. _this.exponent = exponent;
  46125. return _this;
  46126. }
  46127. Object.defineProperty(SpotLight.prototype, "angle", {
  46128. /**
  46129. * Gets the cone angle of the spot light in Radians.
  46130. */
  46131. get: function () {
  46132. return this._angle;
  46133. },
  46134. /**
  46135. * Sets the cone angle of the spot light in Radians.
  46136. */
  46137. set: function (value) {
  46138. this._angle = value;
  46139. this._projectionTextureProjectionLightDirty = true;
  46140. this.forceProjectionMatrixCompute();
  46141. },
  46142. enumerable: true,
  46143. configurable: true
  46144. });
  46145. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  46146. /**
  46147. * Allows scaling the angle of the light for shadow generation only.
  46148. */
  46149. get: function () {
  46150. return this._shadowAngleScale;
  46151. },
  46152. /**
  46153. * Allows scaling the angle of the light for shadow generation only.
  46154. */
  46155. set: function (value) {
  46156. this._shadowAngleScale = value;
  46157. this.forceProjectionMatrixCompute();
  46158. },
  46159. enumerable: true,
  46160. configurable: true
  46161. });
  46162. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  46163. /**
  46164. * Allows reading the projecton texture
  46165. */
  46166. get: function () {
  46167. return this._projectionTextureMatrix;
  46168. },
  46169. enumerable: true,
  46170. configurable: true
  46171. });
  46172. ;
  46173. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  46174. /**
  46175. * Gets the near clip of the Spotlight for texture projection.
  46176. */
  46177. get: function () {
  46178. return this._projectionTextureLightNear;
  46179. },
  46180. /**
  46181. * Sets the near clip of the Spotlight for texture projection.
  46182. */
  46183. set: function (value) {
  46184. this._projectionTextureLightNear = value;
  46185. this._projectionTextureProjectionLightDirty = true;
  46186. },
  46187. enumerable: true,
  46188. configurable: true
  46189. });
  46190. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  46191. /**
  46192. * Gets the far clip of the Spotlight for texture projection.
  46193. */
  46194. get: function () {
  46195. return this._projectionTextureLightFar;
  46196. },
  46197. /**
  46198. * Sets the far clip of the Spotlight for texture projection.
  46199. */
  46200. set: function (value) {
  46201. this._projectionTextureLightFar = value;
  46202. this._projectionTextureProjectionLightDirty = true;
  46203. },
  46204. enumerable: true,
  46205. configurable: true
  46206. });
  46207. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  46208. /**
  46209. * Gets the Up vector of the Spotlight for texture projection.
  46210. */
  46211. get: function () {
  46212. return this._projectionTextureUpDirection;
  46213. },
  46214. /**
  46215. * Sets the Up vector of the Spotlight for texture projection.
  46216. */
  46217. set: function (value) {
  46218. this._projectionTextureUpDirection = value;
  46219. this._projectionTextureProjectionLightDirty = true;
  46220. },
  46221. enumerable: true,
  46222. configurable: true
  46223. });
  46224. ;
  46225. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  46226. /**
  46227. * Gets the projection texture of the light.
  46228. */
  46229. get: function () {
  46230. return this._projectionTexture;
  46231. },
  46232. /**
  46233. * Sets the projection texture of the light.
  46234. */
  46235. set: function (value) {
  46236. this._projectionTexture = value;
  46237. this._projectionTextureDirty = true;
  46238. },
  46239. enumerable: true,
  46240. configurable: true
  46241. });
  46242. /**
  46243. * Returns the string "SpotLight".
  46244. * @returns the class name
  46245. */
  46246. SpotLight.prototype.getClassName = function () {
  46247. return "SpotLight";
  46248. };
  46249. /**
  46250. * Returns the integer 2.
  46251. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  46252. */
  46253. SpotLight.prototype.getTypeID = function () {
  46254. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  46255. };
  46256. /**
  46257. * Overrides the direction setter to recompute the projection texture view light Matrix.
  46258. */
  46259. SpotLight.prototype._setDirection = function (value) {
  46260. _super.prototype._setDirection.call(this, value);
  46261. this._projectionTextureViewLightDirty = true;
  46262. };
  46263. /**
  46264. * Overrides the position setter to recompute the projection texture view light Matrix.
  46265. */
  46266. SpotLight.prototype._setPosition = function (value) {
  46267. _super.prototype._setPosition.call(this, value);
  46268. this._projectionTextureViewLightDirty = true;
  46269. };
  46270. /**
  46271. * 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.
  46272. * Returns the SpotLight.
  46273. */
  46274. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  46275. var activeCamera = this.getScene().activeCamera;
  46276. if (!activeCamera) {
  46277. return;
  46278. }
  46279. this._shadowAngleScale = this._shadowAngleScale || 1;
  46280. var angle = this._shadowAngleScale * this._angle;
  46281. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  46282. };
  46283. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  46284. this._projectionTextureViewLightDirty = false;
  46285. this._projectionTextureDirty = true;
  46286. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  46287. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  46288. };
  46289. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  46290. this._projectionTextureProjectionLightDirty = false;
  46291. this._projectionTextureDirty = true;
  46292. var light_far = this.projectionTextureLightFar;
  46293. var light_near = this.projectionTextureLightNear;
  46294. var P = light_far / (light_far - light_near);
  46295. var Q = -P * light_near;
  46296. var S = 1.0 / Math.tan(this._angle / 2.0);
  46297. var A = 1.0;
  46298. 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);
  46299. };
  46300. /**
  46301. * Main function for light texture projection matrix computing.
  46302. */
  46303. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  46304. this._projectionTextureDirty = false;
  46305. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  46306. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  46307. };
  46308. SpotLight.prototype._buildUniformLayout = function () {
  46309. this._uniformBuffer.addUniform("vLightData", 4);
  46310. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  46311. this._uniformBuffer.addUniform("vLightSpecular", 3);
  46312. this._uniformBuffer.addUniform("vLightDirection", 3);
  46313. this._uniformBuffer.addUniform("shadowsInfo", 3);
  46314. this._uniformBuffer.addUniform("depthValues", 2);
  46315. this._uniformBuffer.create();
  46316. };
  46317. /**
  46318. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  46319. * @param effect The effect to update
  46320. * @param lightIndex The index of the light in the effect to update
  46321. * @returns The spot light
  46322. */
  46323. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  46324. var normalizeDirection;
  46325. if (this.computeTransformedInformation()) {
  46326. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  46327. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  46328. }
  46329. else {
  46330. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  46331. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  46332. }
  46333. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  46334. if (this.projectionTexture && this.projectionTexture.isReady()) {
  46335. if (this._projectionTextureViewLightDirty) {
  46336. this._computeProjectionTextureViewLightMatrix();
  46337. }
  46338. if (this._projectionTextureProjectionLightDirty) {
  46339. this._computeProjectionTextureProjectionLightMatrix();
  46340. }
  46341. if (this._projectionTextureDirty) {
  46342. this._computeProjectionTextureMatrix();
  46343. }
  46344. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  46345. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  46346. }
  46347. return this;
  46348. };
  46349. /**
  46350. * Disposes the light and the associated resources.
  46351. */
  46352. SpotLight.prototype.dispose = function () {
  46353. _super.prototype.dispose.call(this);
  46354. if (this._projectionTexture) {
  46355. this._projectionTexture.dispose();
  46356. }
  46357. };
  46358. __decorate([
  46359. BABYLON.serialize()
  46360. ], SpotLight.prototype, "angle", null);
  46361. __decorate([
  46362. BABYLON.serialize()
  46363. ], SpotLight.prototype, "shadowAngleScale", null);
  46364. __decorate([
  46365. BABYLON.serialize()
  46366. ], SpotLight.prototype, "exponent", void 0);
  46367. __decorate([
  46368. BABYLON.serialize()
  46369. ], SpotLight.prototype, "projectionTextureLightNear", null);
  46370. __decorate([
  46371. BABYLON.serialize()
  46372. ], SpotLight.prototype, "projectionTextureLightFar", null);
  46373. __decorate([
  46374. BABYLON.serialize()
  46375. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  46376. __decorate([
  46377. BABYLON.serializeAsTexture("projectedLightTexture")
  46378. ], SpotLight.prototype, "_projectionTexture", void 0);
  46379. return SpotLight;
  46380. }(BABYLON.ShadowLight));
  46381. BABYLON.SpotLight = SpotLight;
  46382. })(BABYLON || (BABYLON = {}));
  46383. //# sourceMappingURL=babylon.spotLight.js.map
  46384. var BABYLON;
  46385. (function (BABYLON) {
  46386. /**
  46387. * Class used to override all child animations of a given target
  46388. */
  46389. var AnimationPropertiesOverride = /** @class */ (function () {
  46390. function AnimationPropertiesOverride() {
  46391. /**
  46392. * Gets or sets a value indicating if animation blending must be used
  46393. */
  46394. this.enableBlending = false;
  46395. /**
  46396. * Gets or sets the blending speed to use when enableBlending is true
  46397. */
  46398. this.blendingSpeed = 0.01;
  46399. /**
  46400. * Gets or sets the default loop mode to use
  46401. */
  46402. this.loopMode = BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE;
  46403. }
  46404. return AnimationPropertiesOverride;
  46405. }());
  46406. BABYLON.AnimationPropertiesOverride = AnimationPropertiesOverride;
  46407. })(BABYLON || (BABYLON = {}));
  46408. //# sourceMappingURL=babylon.animationPropertiesOverride.js.map
  46409. var BABYLON;
  46410. (function (BABYLON) {
  46411. var AnimationRange = /** @class */ (function () {
  46412. function AnimationRange(name, from, to) {
  46413. this.name = name;
  46414. this.from = from;
  46415. this.to = to;
  46416. }
  46417. AnimationRange.prototype.clone = function () {
  46418. return new AnimationRange(this.name, this.from, this.to);
  46419. };
  46420. return AnimationRange;
  46421. }());
  46422. BABYLON.AnimationRange = AnimationRange;
  46423. /**
  46424. * Composed of a frame, and an action function
  46425. */
  46426. var AnimationEvent = /** @class */ (function () {
  46427. function AnimationEvent(frame, action, onlyOnce) {
  46428. this.frame = frame;
  46429. this.action = action;
  46430. this.onlyOnce = onlyOnce;
  46431. this.isDone = false;
  46432. }
  46433. return AnimationEvent;
  46434. }());
  46435. BABYLON.AnimationEvent = AnimationEvent;
  46436. var PathCursor = /** @class */ (function () {
  46437. function PathCursor(path) {
  46438. this.path = path;
  46439. this._onchange = new Array();
  46440. this.value = 0;
  46441. this.animations = new Array();
  46442. }
  46443. PathCursor.prototype.getPoint = function () {
  46444. var point = this.path.getPointAtLengthPosition(this.value);
  46445. return new BABYLON.Vector3(point.x, 0, point.y);
  46446. };
  46447. PathCursor.prototype.moveAhead = function (step) {
  46448. if (step === void 0) { step = 0.002; }
  46449. this.move(step);
  46450. return this;
  46451. };
  46452. PathCursor.prototype.moveBack = function (step) {
  46453. if (step === void 0) { step = 0.002; }
  46454. this.move(-step);
  46455. return this;
  46456. };
  46457. PathCursor.prototype.move = function (step) {
  46458. if (Math.abs(step) > 1) {
  46459. throw "step size should be less than 1.";
  46460. }
  46461. this.value += step;
  46462. this.ensureLimits();
  46463. this.raiseOnChange();
  46464. return this;
  46465. };
  46466. PathCursor.prototype.ensureLimits = function () {
  46467. while (this.value > 1) {
  46468. this.value -= 1;
  46469. }
  46470. while (this.value < 0) {
  46471. this.value += 1;
  46472. }
  46473. return this;
  46474. };
  46475. // used by animation engine
  46476. PathCursor.prototype.raiseOnChange = function () {
  46477. var _this = this;
  46478. this._onchange.forEach(function (f) { return f(_this); });
  46479. return this;
  46480. };
  46481. PathCursor.prototype.onchange = function (f) {
  46482. this._onchange.push(f);
  46483. return this;
  46484. };
  46485. return PathCursor;
  46486. }());
  46487. BABYLON.PathCursor = PathCursor;
  46488. var AnimationKeyInterpolation;
  46489. (function (AnimationKeyInterpolation) {
  46490. /**
  46491. * Do not interpolate between keys and use the start key value only. Tangents are ignored.
  46492. */
  46493. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  46494. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  46495. var Animation = /** @class */ (function () {
  46496. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  46497. this.name = name;
  46498. this.targetProperty = targetProperty;
  46499. this.framePerSecond = framePerSecond;
  46500. this.dataType = dataType;
  46501. this.loopMode = loopMode;
  46502. this.enableBlending = enableBlending;
  46503. this._runtimeAnimations = new Array();
  46504. // The set of event that will be linked to this animation
  46505. this._events = new Array();
  46506. this.blendingSpeed = 0.01;
  46507. this._ranges = {};
  46508. this.targetPropertyPath = targetProperty.split(".");
  46509. this.dataType = dataType;
  46510. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  46511. }
  46512. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  46513. var dataType = undefined;
  46514. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  46515. dataType = Animation.ANIMATIONTYPE_FLOAT;
  46516. }
  46517. else if (from instanceof BABYLON.Quaternion) {
  46518. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  46519. }
  46520. else if (from instanceof BABYLON.Vector3) {
  46521. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  46522. }
  46523. else if (from instanceof BABYLON.Vector2) {
  46524. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  46525. }
  46526. else if (from instanceof BABYLON.Color3) {
  46527. dataType = Animation.ANIMATIONTYPE_COLOR3;
  46528. }
  46529. else if (from instanceof BABYLON.Size) {
  46530. dataType = Animation.ANIMATIONTYPE_SIZE;
  46531. }
  46532. if (dataType == undefined) {
  46533. return null;
  46534. }
  46535. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  46536. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  46537. animation.setKeys(keys);
  46538. if (easingFunction !== undefined) {
  46539. animation.setEasingFunction(easingFunction);
  46540. }
  46541. return animation;
  46542. };
  46543. /**
  46544. * Sets up an animation.
  46545. * @param property the property to animate
  46546. * @param animationType the animation type to apply
  46547. * @param easingFunction the easing function used in the animation
  46548. * @returns The created animation
  46549. */
  46550. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  46551. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  46552. animation.setEasingFunction(easingFunction);
  46553. return animation;
  46554. };
  46555. /**
  46556. * Create and start an animation on a node
  46557. * @param {string} name defines the name of the global animation that will be run on all nodes
  46558. * @param {BABYLON.Node} node defines the root node where the animation will take place
  46559. * @param {string} targetProperty defines property to animate
  46560. * @param {number} framePerSecond defines the number of frame per second yo use
  46561. * @param {number} totalFrame defines the number of frames in total
  46562. * @param {any} from defines the initial value
  46563. * @param {any} to defines the final value
  46564. * @param {number} loopMode defines which loop mode you want to use (off by default)
  46565. * @param {BABYLON.EasingFunction} easingFunction defines the easing function to use (linear by default)
  46566. * @param onAnimationEnd defines the callback to call when animation end
  46567. * @returns the animatable created for this animation
  46568. */
  46569. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  46570. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  46571. if (!animation) {
  46572. return null;
  46573. }
  46574. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  46575. };
  46576. /**
  46577. * Create and start an animation on a node and its descendants
  46578. * @param {string} name defines the name of the global animation that will be run on all nodes
  46579. * @param {BABYLON.Node} node defines the root node where the animation will take place
  46580. * @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.
  46581. * @param {string} targetProperty defines property to animate
  46582. * @param {number} framePerSecond defines the number of frame per second yo use
  46583. * @param {number} totalFrame defines the number of frames in total
  46584. * @param {any} from defines the initial value
  46585. * @param {any} to defines the final value
  46586. * @param {number} loopMode defines which loop mode you want to use (off by default)
  46587. * @param {BABYLON.EasingFunction} easingFunction defines the easing function to use (linear by default)
  46588. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  46589. * @returns the list of animatables created for all nodes
  46590. * @example https://www.babylonjs-playground.com/#MH0VLI
  46591. */
  46592. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  46593. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  46594. if (!animation) {
  46595. return null;
  46596. }
  46597. var scene = node.getScene();
  46598. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  46599. };
  46600. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  46601. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  46602. if (!animation) {
  46603. return null;
  46604. }
  46605. node.animations.push(animation);
  46606. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  46607. };
  46608. /**
  46609. * Transition property of the Camera to the target Value.
  46610. * @param property The property to transition
  46611. * @param targetValue The target Value of the property
  46612. * @param host The object where the property to animate belongs
  46613. * @param scene Scene used to run the animation
  46614. * @param frameRate Framerate (in frame/s) to use
  46615. * @param transition The transition type we want to use
  46616. * @param duration The duration of the animation, in milliseconds
  46617. * @param onAnimationEnd Call back trigger at the end of the animation.
  46618. */
  46619. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  46620. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  46621. if (duration <= 0) {
  46622. host[property] = targetValue;
  46623. if (onAnimationEnd) {
  46624. onAnimationEnd();
  46625. }
  46626. return null;
  46627. }
  46628. var endFrame = frameRate * (duration / 1000);
  46629. transition.setKeys([{
  46630. frame: 0,
  46631. value: host[property].clone ? host[property].clone() : host[property]
  46632. },
  46633. {
  46634. frame: endFrame,
  46635. value: targetValue
  46636. }]);
  46637. if (!host.animations) {
  46638. host.animations = [];
  46639. }
  46640. host.animations.push(transition);
  46641. var animation = scene.beginAnimation(host, 0, endFrame, false);
  46642. animation.onAnimationEnd = onAnimationEnd;
  46643. return animation;
  46644. };
  46645. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  46646. /**
  46647. * Return the array of runtime animations currently using this animation
  46648. */
  46649. get: function () {
  46650. return this._runtimeAnimations;
  46651. },
  46652. enumerable: true,
  46653. configurable: true
  46654. });
  46655. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  46656. get: function () {
  46657. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  46658. var runtimeAnimation = _a[_i];
  46659. if (!runtimeAnimation.isStopped) {
  46660. return true;
  46661. }
  46662. }
  46663. return false;
  46664. },
  46665. enumerable: true,
  46666. configurable: true
  46667. });
  46668. // Methods
  46669. /**
  46670. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  46671. */
  46672. Animation.prototype.toString = function (fullDetails) {
  46673. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  46674. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  46675. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  46676. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  46677. if (fullDetails) {
  46678. ret += ", Ranges: {";
  46679. var first = true;
  46680. for (var name in this._ranges) {
  46681. if (first) {
  46682. ret += ", ";
  46683. first = false;
  46684. }
  46685. ret += name;
  46686. }
  46687. ret += "}";
  46688. }
  46689. return ret;
  46690. };
  46691. /**
  46692. * Add an event to this animation.
  46693. */
  46694. Animation.prototype.addEvent = function (event) {
  46695. this._events.push(event);
  46696. };
  46697. /**
  46698. * Remove all events found at the given frame
  46699. * @param frame
  46700. */
  46701. Animation.prototype.removeEvents = function (frame) {
  46702. for (var index = 0; index < this._events.length; index++) {
  46703. if (this._events[index].frame === frame) {
  46704. this._events.splice(index, 1);
  46705. index--;
  46706. }
  46707. }
  46708. };
  46709. Animation.prototype.getEvents = function () {
  46710. return this._events;
  46711. };
  46712. Animation.prototype.createRange = function (name, from, to) {
  46713. // check name not already in use; could happen for bones after serialized
  46714. if (!this._ranges[name]) {
  46715. this._ranges[name] = new AnimationRange(name, from, to);
  46716. }
  46717. };
  46718. Animation.prototype.deleteRange = function (name, deleteFrames) {
  46719. if (deleteFrames === void 0) { deleteFrames = true; }
  46720. var range = this._ranges[name];
  46721. if (!range) {
  46722. return;
  46723. }
  46724. if (deleteFrames) {
  46725. var from = range.from;
  46726. var to = range.to;
  46727. // this loop MUST go high to low for multiple splices to work
  46728. for (var key = this._keys.length - 1; key >= 0; key--) {
  46729. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  46730. this._keys.splice(key, 1);
  46731. }
  46732. }
  46733. }
  46734. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  46735. };
  46736. Animation.prototype.getRange = function (name) {
  46737. return this._ranges[name];
  46738. };
  46739. Animation.prototype.getKeys = function () {
  46740. return this._keys;
  46741. };
  46742. Animation.prototype.getHighestFrame = function () {
  46743. var ret = 0;
  46744. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  46745. if (ret < this._keys[key].frame) {
  46746. ret = this._keys[key].frame;
  46747. }
  46748. }
  46749. return ret;
  46750. };
  46751. Animation.prototype.getEasingFunction = function () {
  46752. return this._easingFunction;
  46753. };
  46754. Animation.prototype.setEasingFunction = function (easingFunction) {
  46755. this._easingFunction = easingFunction;
  46756. };
  46757. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  46758. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  46759. };
  46760. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  46761. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  46762. };
  46763. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  46764. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  46765. };
  46766. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  46767. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  46768. };
  46769. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  46770. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  46771. };
  46772. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  46773. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  46774. };
  46775. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  46776. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  46777. };
  46778. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  46779. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  46780. };
  46781. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  46782. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  46783. };
  46784. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  46785. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  46786. };
  46787. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  46788. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  46789. };
  46790. Animation.prototype.clone = function () {
  46791. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  46792. clone.enableBlending = this.enableBlending;
  46793. clone.blendingSpeed = this.blendingSpeed;
  46794. if (this._keys) {
  46795. clone.setKeys(this._keys);
  46796. }
  46797. if (this._ranges) {
  46798. clone._ranges = {};
  46799. for (var name in this._ranges) {
  46800. var range = this._ranges[name];
  46801. if (!range) {
  46802. continue;
  46803. }
  46804. clone._ranges[name] = range.clone();
  46805. }
  46806. }
  46807. return clone;
  46808. };
  46809. Animation.prototype.setKeys = function (values) {
  46810. this._keys = values.slice(0);
  46811. };
  46812. Animation.prototype.serialize = function () {
  46813. var serializationObject = {};
  46814. serializationObject.name = this.name;
  46815. serializationObject.property = this.targetProperty;
  46816. serializationObject.framePerSecond = this.framePerSecond;
  46817. serializationObject.dataType = this.dataType;
  46818. serializationObject.loopBehavior = this.loopMode;
  46819. serializationObject.enableBlending = this.enableBlending;
  46820. serializationObject.blendingSpeed = this.blendingSpeed;
  46821. var dataType = this.dataType;
  46822. serializationObject.keys = [];
  46823. var keys = this.getKeys();
  46824. for (var index = 0; index < keys.length; index++) {
  46825. var animationKey = keys[index];
  46826. var key = {};
  46827. key.frame = animationKey.frame;
  46828. switch (dataType) {
  46829. case Animation.ANIMATIONTYPE_FLOAT:
  46830. key.values = [animationKey.value];
  46831. break;
  46832. case Animation.ANIMATIONTYPE_QUATERNION:
  46833. case Animation.ANIMATIONTYPE_MATRIX:
  46834. case Animation.ANIMATIONTYPE_VECTOR3:
  46835. case Animation.ANIMATIONTYPE_COLOR3:
  46836. key.values = animationKey.value.asArray();
  46837. break;
  46838. }
  46839. serializationObject.keys.push(key);
  46840. }
  46841. serializationObject.ranges = [];
  46842. for (var name in this._ranges) {
  46843. var source = this._ranges[name];
  46844. if (!source) {
  46845. continue;
  46846. }
  46847. var range = {};
  46848. range.name = name;
  46849. range.from = source.from;
  46850. range.to = source.to;
  46851. serializationObject.ranges.push(range);
  46852. }
  46853. return serializationObject;
  46854. };
  46855. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  46856. get: function () {
  46857. return Animation._ANIMATIONTYPE_FLOAT;
  46858. },
  46859. enumerable: true,
  46860. configurable: true
  46861. });
  46862. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  46863. get: function () {
  46864. return Animation._ANIMATIONTYPE_VECTOR3;
  46865. },
  46866. enumerable: true,
  46867. configurable: true
  46868. });
  46869. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  46870. get: function () {
  46871. return Animation._ANIMATIONTYPE_VECTOR2;
  46872. },
  46873. enumerable: true,
  46874. configurable: true
  46875. });
  46876. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  46877. get: function () {
  46878. return Animation._ANIMATIONTYPE_SIZE;
  46879. },
  46880. enumerable: true,
  46881. configurable: true
  46882. });
  46883. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  46884. get: function () {
  46885. return Animation._ANIMATIONTYPE_QUATERNION;
  46886. },
  46887. enumerable: true,
  46888. configurable: true
  46889. });
  46890. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  46891. get: function () {
  46892. return Animation._ANIMATIONTYPE_MATRIX;
  46893. },
  46894. enumerable: true,
  46895. configurable: true
  46896. });
  46897. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  46898. get: function () {
  46899. return Animation._ANIMATIONTYPE_COLOR3;
  46900. },
  46901. enumerable: true,
  46902. configurable: true
  46903. });
  46904. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  46905. get: function () {
  46906. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  46907. },
  46908. enumerable: true,
  46909. configurable: true
  46910. });
  46911. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  46912. get: function () {
  46913. return Animation._ANIMATIONLOOPMODE_CYCLE;
  46914. },
  46915. enumerable: true,
  46916. configurable: true
  46917. });
  46918. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  46919. get: function () {
  46920. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  46921. },
  46922. enumerable: true,
  46923. configurable: true
  46924. });
  46925. Animation.Parse = function (parsedAnimation) {
  46926. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  46927. var dataType = parsedAnimation.dataType;
  46928. var keys = [];
  46929. var data;
  46930. var index;
  46931. if (parsedAnimation.enableBlending) {
  46932. animation.enableBlending = parsedAnimation.enableBlending;
  46933. }
  46934. if (parsedAnimation.blendingSpeed) {
  46935. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  46936. }
  46937. for (index = 0; index < parsedAnimation.keys.length; index++) {
  46938. var key = parsedAnimation.keys[index];
  46939. var inTangent;
  46940. var outTangent;
  46941. switch (dataType) {
  46942. case Animation.ANIMATIONTYPE_FLOAT:
  46943. data = key.values[0];
  46944. if (key.values.length >= 1) {
  46945. inTangent = key.values[1];
  46946. }
  46947. if (key.values.length >= 2) {
  46948. outTangent = key.values[2];
  46949. }
  46950. break;
  46951. case Animation.ANIMATIONTYPE_QUATERNION:
  46952. data = BABYLON.Quaternion.FromArray(key.values);
  46953. if (key.values.length >= 8) {
  46954. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  46955. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  46956. inTangent = _inTangent;
  46957. }
  46958. }
  46959. if (key.values.length >= 12) {
  46960. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  46961. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  46962. outTangent = _outTangent;
  46963. }
  46964. }
  46965. break;
  46966. case Animation.ANIMATIONTYPE_MATRIX:
  46967. data = BABYLON.Matrix.FromArray(key.values);
  46968. break;
  46969. case Animation.ANIMATIONTYPE_COLOR3:
  46970. data = BABYLON.Color3.FromArray(key.values);
  46971. break;
  46972. case Animation.ANIMATIONTYPE_VECTOR3:
  46973. default:
  46974. data = BABYLON.Vector3.FromArray(key.values);
  46975. break;
  46976. }
  46977. var keyData = {};
  46978. keyData.frame = key.frame;
  46979. keyData.value = data;
  46980. if (inTangent != undefined) {
  46981. keyData.inTangent = inTangent;
  46982. }
  46983. if (outTangent != undefined) {
  46984. keyData.outTangent = outTangent;
  46985. }
  46986. keys.push(keyData);
  46987. }
  46988. animation.setKeys(keys);
  46989. if (parsedAnimation.ranges) {
  46990. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  46991. data = parsedAnimation.ranges[index];
  46992. animation.createRange(data.name, data.from, data.to);
  46993. }
  46994. }
  46995. return animation;
  46996. };
  46997. Animation.AppendSerializedAnimations = function (source, destination) {
  46998. if (source.animations) {
  46999. destination.animations = [];
  47000. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  47001. var animation = source.animations[animationIndex];
  47002. destination.animations.push(animation.serialize());
  47003. }
  47004. }
  47005. };
  47006. Animation.AllowMatricesInterpolation = false;
  47007. // Statics
  47008. Animation._ANIMATIONTYPE_FLOAT = 0;
  47009. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  47010. Animation._ANIMATIONTYPE_QUATERNION = 2;
  47011. Animation._ANIMATIONTYPE_MATRIX = 3;
  47012. Animation._ANIMATIONTYPE_COLOR3 = 4;
  47013. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  47014. Animation._ANIMATIONTYPE_SIZE = 6;
  47015. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  47016. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  47017. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  47018. return Animation;
  47019. }());
  47020. BABYLON.Animation = Animation;
  47021. })(BABYLON || (BABYLON = {}));
  47022. //# sourceMappingURL=babylon.animation.js.map
  47023. var BABYLON;
  47024. (function (BABYLON) {
  47025. /**
  47026. * This class defines the direct association between an animation and a target
  47027. */
  47028. var TargetedAnimation = /** @class */ (function () {
  47029. function TargetedAnimation() {
  47030. }
  47031. return TargetedAnimation;
  47032. }());
  47033. BABYLON.TargetedAnimation = TargetedAnimation;
  47034. /**
  47035. * Use this class to create coordinated animations on multiple targets
  47036. */
  47037. var AnimationGroup = /** @class */ (function () {
  47038. function AnimationGroup(name, scene) {
  47039. if (scene === void 0) { scene = null; }
  47040. this.name = name;
  47041. this._targetedAnimations = new Array();
  47042. this._animatables = new Array();
  47043. this._from = Number.MAX_VALUE;
  47044. this._to = -Number.MAX_VALUE;
  47045. this._speedRatio = 1;
  47046. this.onAnimationEndObservable = new BABYLON.Observable();
  47047. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  47048. this._scene.animationGroups.push(this);
  47049. }
  47050. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  47051. /**
  47052. * Define if the animations are started
  47053. */
  47054. get: function () {
  47055. return this._isStarted;
  47056. },
  47057. enumerable: true,
  47058. configurable: true
  47059. });
  47060. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  47061. /**
  47062. * Gets or sets the speed ratio to use for all animations
  47063. */
  47064. get: function () {
  47065. return this._speedRatio;
  47066. },
  47067. /**
  47068. * Gets or sets the speed ratio to use for all animations
  47069. */
  47070. set: function (value) {
  47071. if (this._speedRatio === value) {
  47072. return;
  47073. }
  47074. this._speedRatio = value;
  47075. for (var index = 0; index < this._animatables.length; index++) {
  47076. var animatable = this._animatables[index];
  47077. animatable.speedRatio = this._speedRatio;
  47078. }
  47079. },
  47080. enumerable: true,
  47081. configurable: true
  47082. });
  47083. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  47084. /**
  47085. * Gets the targeted animations for this animation group
  47086. */
  47087. get: function () {
  47088. return this._targetedAnimations;
  47089. },
  47090. enumerable: true,
  47091. configurable: true
  47092. });
  47093. Object.defineProperty(AnimationGroup.prototype, "animatables", {
  47094. /**
  47095. * returning the list of animatables controlled by this animation group.
  47096. */
  47097. get: function () {
  47098. return this._animatables;
  47099. },
  47100. enumerable: true,
  47101. configurable: true
  47102. });
  47103. /**
  47104. * Add an animation (with its target) in the group
  47105. * @param animation defines the animation we want to add
  47106. * @param target defines the target of the animation
  47107. * @returns the {BABYLON.TargetedAnimation} object
  47108. */
  47109. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  47110. var targetedAnimation = {
  47111. animation: animation,
  47112. target: target
  47113. };
  47114. var keys = animation.getKeys();
  47115. if (this._from > keys[0].frame) {
  47116. this._from = keys[0].frame;
  47117. }
  47118. if (this._to < keys[keys.length - 1].frame) {
  47119. this._to = keys[keys.length - 1].frame;
  47120. }
  47121. this._targetedAnimations.push(targetedAnimation);
  47122. return targetedAnimation;
  47123. };
  47124. /**
  47125. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  47126. * It can add constant keys at begin or end
  47127. * @param beginFrame defines the new begin frame for all animations. It can't be bigger than the smallest begin frame of all animations
  47128. * @param endFrame defines the new end frame for all animations. It can't be smaller than the largest end frame of all animations
  47129. */
  47130. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  47131. if (beginFrame === void 0) { beginFrame = -Number.MAX_VALUE; }
  47132. if (endFrame === void 0) { endFrame = Number.MAX_VALUE; }
  47133. beginFrame = Math.max(beginFrame, this._from);
  47134. endFrame = Math.min(endFrame, this._to);
  47135. for (var index = 0; index < this._targetedAnimations.length; index++) {
  47136. var targetedAnimation = this._targetedAnimations[index];
  47137. var keys = targetedAnimation.animation.getKeys();
  47138. var startKey = keys[0];
  47139. var endKey = keys[keys.length - 1];
  47140. if (startKey.frame > beginFrame) {
  47141. var newKey = {
  47142. frame: beginFrame,
  47143. value: startKey.value,
  47144. inTangent: startKey.inTangent,
  47145. outTangent: startKey.outTangent,
  47146. interpolation: startKey.interpolation
  47147. };
  47148. keys.splice(0, 0, newKey);
  47149. }
  47150. if (endKey.frame < endFrame) {
  47151. var newKey = {
  47152. frame: endFrame,
  47153. value: endKey.value,
  47154. inTangent: endKey.outTangent,
  47155. outTangent: endKey.outTangent,
  47156. interpolation: endKey.interpolation
  47157. };
  47158. keys.push(newKey);
  47159. }
  47160. }
  47161. return this;
  47162. };
  47163. /**
  47164. * Start all animations on given targets
  47165. * @param loop defines if animations must loop
  47166. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  47167. */
  47168. AnimationGroup.prototype.start = function (loop, speedRatio) {
  47169. var _this = this;
  47170. if (loop === void 0) { loop = false; }
  47171. if (speedRatio === void 0) { speedRatio = 1; }
  47172. if (this._isStarted || this._targetedAnimations.length === 0) {
  47173. return this;
  47174. }
  47175. var _loop_1 = function () {
  47176. var targetedAnimation = this_1._targetedAnimations[index];
  47177. this_1._animatables.push(this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], this_1._from, this_1._to, loop, speedRatio, function () {
  47178. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  47179. }));
  47180. };
  47181. var this_1 = this;
  47182. for (var index = 0; index < this._targetedAnimations.length; index++) {
  47183. _loop_1();
  47184. }
  47185. this._speedRatio = speedRatio;
  47186. this._isStarted = true;
  47187. return this;
  47188. };
  47189. /**
  47190. * Pause all animations
  47191. */
  47192. AnimationGroup.prototype.pause = function () {
  47193. if (!this._isStarted) {
  47194. return this;
  47195. }
  47196. for (var index = 0; index < this._animatables.length; index++) {
  47197. var animatable = this._animatables[index];
  47198. animatable.pause();
  47199. }
  47200. return this;
  47201. };
  47202. /**
  47203. * Play all animations to initial state
  47204. * This function will start() the animations if they were not started or will restart() them if they were paused
  47205. * @param loop defines if animations must loop
  47206. */
  47207. AnimationGroup.prototype.play = function (loop) {
  47208. if (this.isStarted) {
  47209. if (loop !== undefined) {
  47210. for (var index = 0; index < this._animatables.length; index++) {
  47211. var animatable = this._animatables[index];
  47212. animatable.loopAnimation = loop;
  47213. }
  47214. }
  47215. this.restart();
  47216. }
  47217. else {
  47218. this.start(loop, this._speedRatio);
  47219. }
  47220. return this;
  47221. };
  47222. /**
  47223. * Reset all animations to initial state
  47224. */
  47225. AnimationGroup.prototype.reset = function () {
  47226. if (!this._isStarted) {
  47227. return this;
  47228. }
  47229. for (var index = 0; index < this._animatables.length; index++) {
  47230. var animatable = this._animatables[index];
  47231. animatable.reset();
  47232. }
  47233. return this;
  47234. };
  47235. /**
  47236. * Restart animations from key 0
  47237. */
  47238. AnimationGroup.prototype.restart = function () {
  47239. if (!this._isStarted) {
  47240. return this;
  47241. }
  47242. for (var index = 0; index < this._animatables.length; index++) {
  47243. var animatable = this._animatables[index];
  47244. animatable.restart();
  47245. }
  47246. return this;
  47247. };
  47248. /**
  47249. * Stop all animations
  47250. */
  47251. AnimationGroup.prototype.stop = function () {
  47252. if (!this._isStarted) {
  47253. return this;
  47254. }
  47255. for (var index = 0; index < this._animatables.length; index++) {
  47256. var animatable = this._animatables[index];
  47257. animatable.stop();
  47258. }
  47259. this._isStarted = false;
  47260. return this;
  47261. };
  47262. /**
  47263. * Goes to a specific frame in this animation group
  47264. *
  47265. * @param frame the frame number to go to
  47266. * @return the animationGroup
  47267. */
  47268. AnimationGroup.prototype.goToFrame = function (frame) {
  47269. if (!this._isStarted) {
  47270. return this;
  47271. }
  47272. for (var index = 0; index < this._animatables.length; index++) {
  47273. var animatable = this._animatables[index];
  47274. animatable.goToFrame(frame);
  47275. }
  47276. return this;
  47277. };
  47278. /**
  47279. * Dispose all associated resources
  47280. */
  47281. AnimationGroup.prototype.dispose = function () {
  47282. this._targetedAnimations = [];
  47283. this._animatables = [];
  47284. var index = this._scene.animationGroups.indexOf(this);
  47285. if (index > -1) {
  47286. this._scene.animationGroups.splice(index, 1);
  47287. }
  47288. };
  47289. return AnimationGroup;
  47290. }());
  47291. BABYLON.AnimationGroup = AnimationGroup;
  47292. })(BABYLON || (BABYLON = {}));
  47293. //# sourceMappingURL=babylon.animationGroup.js.map
  47294. var BABYLON;
  47295. (function (BABYLON) {
  47296. var RuntimeAnimation = /** @class */ (function () {
  47297. function RuntimeAnimation(target, animation) {
  47298. this._offsetsCache = {};
  47299. this._highLimitsCache = {};
  47300. this._stopped = false;
  47301. this._blendingFactor = 0;
  47302. this._ratioOffset = 0;
  47303. this._animation = animation;
  47304. this._target = target;
  47305. animation._runtimeAnimations.push(this);
  47306. }
  47307. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  47308. get: function () {
  47309. return this._animation;
  47310. },
  47311. enumerable: true,
  47312. configurable: true
  47313. });
  47314. RuntimeAnimation.prototype.reset = function () {
  47315. this._offsetsCache = {};
  47316. this._highLimitsCache = {};
  47317. this.currentFrame = 0;
  47318. this._blendingFactor = 0;
  47319. this._originalBlendValue = null;
  47320. };
  47321. RuntimeAnimation.prototype.isStopped = function () {
  47322. return this._stopped;
  47323. };
  47324. RuntimeAnimation.prototype.dispose = function () {
  47325. var index = this._animation.runtimeAnimations.indexOf(this);
  47326. if (index > -1) {
  47327. this._animation.runtimeAnimations.splice(index, 1);
  47328. }
  47329. };
  47330. RuntimeAnimation.prototype._getKeyValue = function (value) {
  47331. if (typeof value === "function") {
  47332. return value();
  47333. }
  47334. return value;
  47335. };
  47336. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  47337. if (loopMode === BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  47338. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  47339. }
  47340. this.currentFrame = currentFrame;
  47341. var keys = this._animation.getKeys();
  47342. // Try to get a hash to find the right key
  47343. 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));
  47344. if (keys[startKeyIndex].frame >= currentFrame) {
  47345. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  47346. startKeyIndex--;
  47347. }
  47348. }
  47349. for (var key = startKeyIndex; key < keys.length; key++) {
  47350. var endKey = keys[key + 1];
  47351. if (endKey.frame >= currentFrame) {
  47352. var startKey = keys[key];
  47353. var startValue = this._getKeyValue(startKey.value);
  47354. if (startKey.interpolation === BABYLON.AnimationKeyInterpolation.STEP) {
  47355. return startValue;
  47356. }
  47357. var endValue = this._getKeyValue(endKey.value);
  47358. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  47359. var frameDelta = endKey.frame - startKey.frame;
  47360. // gradient : percent of currentFrame between the frame inf and the frame sup
  47361. var gradient = (currentFrame - startKey.frame) / frameDelta;
  47362. // check for easingFunction and correction of gradient
  47363. var easingFunction = this._animation.getEasingFunction();
  47364. if (easingFunction != null) {
  47365. gradient = easingFunction.ease(gradient);
  47366. }
  47367. switch (this._animation.dataType) {
  47368. // Float
  47369. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  47370. var floatValue = useTangent ? this._animation.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this._animation.floatInterpolateFunction(startValue, endValue, gradient);
  47371. switch (loopMode) {
  47372. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47373. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47374. return floatValue;
  47375. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47376. return offsetValue * repeatCount + floatValue;
  47377. }
  47378. break;
  47379. // Quaternion
  47380. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  47381. var quatValue = useTangent ? this._animation.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.quaternionInterpolateFunction(startValue, endValue, gradient);
  47382. switch (loopMode) {
  47383. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47384. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47385. return quatValue;
  47386. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47387. return quatValue.add(offsetValue.scale(repeatCount));
  47388. }
  47389. return quatValue;
  47390. // Vector3
  47391. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  47392. var vec3Value = useTangent ? this._animation.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector3InterpolateFunction(startValue, endValue, gradient);
  47393. switch (loopMode) {
  47394. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47395. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47396. return vec3Value;
  47397. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47398. return vec3Value.add(offsetValue.scale(repeatCount));
  47399. }
  47400. // Vector2
  47401. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  47402. var vec2Value = useTangent ? this._animation.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector2InterpolateFunction(startValue, endValue, gradient);
  47403. switch (loopMode) {
  47404. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47405. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47406. return vec2Value;
  47407. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47408. return vec2Value.add(offsetValue.scale(repeatCount));
  47409. }
  47410. // Size
  47411. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  47412. switch (loopMode) {
  47413. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47414. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47415. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient);
  47416. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47417. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  47418. }
  47419. // Color3
  47420. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  47421. switch (loopMode) {
  47422. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47423. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47424. return this._animation.color3InterpolateFunction(startValue, endValue, gradient);
  47425. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47426. return this._animation.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  47427. }
  47428. // Matrix
  47429. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  47430. switch (loopMode) {
  47431. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47432. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47433. if (BABYLON.Animation.AllowMatricesInterpolation) {
  47434. return this._animation.matrixInterpolateFunction(startValue, endValue, gradient);
  47435. }
  47436. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47437. return startValue;
  47438. }
  47439. default:
  47440. break;
  47441. }
  47442. break;
  47443. }
  47444. }
  47445. return this._getKeyValue(keys[keys.length - 1].value);
  47446. };
  47447. RuntimeAnimation.prototype.setValue = function (currentValue, blend) {
  47448. if (blend === void 0) { blend = false; }
  47449. // Set value
  47450. var path;
  47451. var destination;
  47452. var targetPropertyPath = this._animation.targetPropertyPath;
  47453. if (targetPropertyPath.length > 1) {
  47454. var property = this._target[targetPropertyPath[0]];
  47455. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  47456. property = property[targetPropertyPath[index]];
  47457. }
  47458. path = targetPropertyPath[targetPropertyPath.length - 1];
  47459. destination = property;
  47460. }
  47461. else {
  47462. path = targetPropertyPath[0];
  47463. destination = this._target;
  47464. }
  47465. // Blending
  47466. var enableBlending = this._target && this._target.animationPropertiesOverride ? this._target.animationPropertiesOverride.enableBlending : this._animation.enableBlending;
  47467. var blendingSpeed = this._target && this._target.animationPropertiesOverride ? this._target.animationPropertiesOverride.blendingSpeed : this._animation.blendingSpeed;
  47468. if (enableBlending && this._blendingFactor <= 1.0) {
  47469. if (!this._originalBlendValue) {
  47470. if (destination[path].clone) {
  47471. this._originalBlendValue = destination[path].clone();
  47472. }
  47473. else {
  47474. this._originalBlendValue = destination[path];
  47475. }
  47476. }
  47477. if (this._originalBlendValue.prototype) {
  47478. if (this._originalBlendValue.prototype.Lerp) {
  47479. destination[path] = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  47480. }
  47481. else {
  47482. destination[path] = currentValue;
  47483. }
  47484. }
  47485. else if (this._originalBlendValue.m) {
  47486. destination[path] = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  47487. }
  47488. else {
  47489. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  47490. }
  47491. this._blendingFactor += blendingSpeed;
  47492. }
  47493. else {
  47494. destination[path] = currentValue;
  47495. }
  47496. if (this._target.markAsDirty) {
  47497. this._target.markAsDirty(this._animation.targetProperty);
  47498. }
  47499. };
  47500. RuntimeAnimation.prototype._getCorrectLoopMode = function () {
  47501. if (this._target && this._target.animationPropertiesOverride) {
  47502. return this._target.animationPropertiesOverride.loopMode;
  47503. }
  47504. return this._animation.loopMode;
  47505. };
  47506. RuntimeAnimation.prototype.goToFrame = function (frame) {
  47507. var keys = this._animation.getKeys();
  47508. if (frame < keys[0].frame) {
  47509. frame = keys[0].frame;
  47510. }
  47511. else if (frame > keys[keys.length - 1].frame) {
  47512. frame = keys[keys.length - 1].frame;
  47513. }
  47514. var currentValue = this._interpolate(frame, 0, this._getCorrectLoopMode());
  47515. this.setValue(currentValue);
  47516. };
  47517. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  47518. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  47519. this._ratioOffset = this._previousRatio - newRatio;
  47520. };
  47521. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  47522. if (blend === void 0) { blend = false; }
  47523. var targetPropertyPath = this._animation.targetPropertyPath;
  47524. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  47525. this._stopped = true;
  47526. return false;
  47527. }
  47528. var returnValue = true;
  47529. var keys = this._animation.getKeys();
  47530. // Adding a start key at frame 0 if missing
  47531. if (keys[0].frame !== 0) {
  47532. var newKey = { frame: 0, value: keys[0].value };
  47533. keys.splice(0, 0, newKey);
  47534. }
  47535. // Check limits
  47536. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  47537. from = keys[0].frame;
  47538. }
  47539. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  47540. to = keys[keys.length - 1].frame;
  47541. }
  47542. //to and from cannot be the same key
  47543. if (from === to) {
  47544. if (from > keys[0].frame) {
  47545. from--;
  47546. }
  47547. else if (to < keys[keys.length - 1].frame) {
  47548. to++;
  47549. }
  47550. }
  47551. // Compute ratio
  47552. var range = to - from;
  47553. var offsetValue;
  47554. // ratio represents the frame delta between from and to
  47555. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  47556. var highLimitValue = 0;
  47557. this._previousDelay = delay;
  47558. this._previousRatio = ratio;
  47559. if (((to > from && ratio > range) || (from > to && ratio < range)) && !loop) {
  47560. returnValue = false;
  47561. highLimitValue = this._getKeyValue(keys[keys.length - 1].value);
  47562. }
  47563. else {
  47564. // Get max value if required
  47565. if (this._getCorrectLoopMode() !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  47566. var keyOffset = to.toString() + from.toString();
  47567. if (!this._offsetsCache[keyOffset]) {
  47568. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  47569. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  47570. switch (this._animation.dataType) {
  47571. // Float
  47572. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  47573. this._offsetsCache[keyOffset] = toValue - fromValue;
  47574. break;
  47575. // Quaternion
  47576. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  47577. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  47578. break;
  47579. // Vector3
  47580. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  47581. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  47582. // Vector2
  47583. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  47584. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  47585. // Size
  47586. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  47587. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  47588. // Color3
  47589. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  47590. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  47591. default:
  47592. break;
  47593. }
  47594. this._highLimitsCache[keyOffset] = toValue;
  47595. }
  47596. highLimitValue = this._highLimitsCache[keyOffset];
  47597. offsetValue = this._offsetsCache[keyOffset];
  47598. }
  47599. }
  47600. if (offsetValue === undefined) {
  47601. switch (this._animation.dataType) {
  47602. // Float
  47603. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  47604. offsetValue = 0;
  47605. break;
  47606. // Quaternion
  47607. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  47608. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  47609. break;
  47610. // Vector3
  47611. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  47612. offsetValue = BABYLON.Vector3.Zero();
  47613. break;
  47614. // Vector2
  47615. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  47616. offsetValue = BABYLON.Vector2.Zero();
  47617. break;
  47618. // Size
  47619. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  47620. offsetValue = BABYLON.Size.Zero();
  47621. break;
  47622. // Color3
  47623. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  47624. offsetValue = BABYLON.Color3.Black();
  47625. }
  47626. }
  47627. // Compute value
  47628. var repeatCount = (ratio / range) >> 0;
  47629. var currentFrame = returnValue ? from + ratio % range : to;
  47630. var currentValue = this._interpolate(currentFrame, repeatCount, this._getCorrectLoopMode(), offsetValue, highLimitValue);
  47631. // Set value
  47632. this.setValue(currentValue);
  47633. // Check events
  47634. var events = this._animation.getEvents();
  47635. for (var index = 0; index < events.length; index++) {
  47636. // Make sure current frame has passed event frame and that event frame is within the current range
  47637. // Also, handle both forward and reverse animations
  47638. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  47639. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  47640. var event = events[index];
  47641. if (!event.isDone) {
  47642. // If event should be done only once, remove it.
  47643. if (event.onlyOnce) {
  47644. events.splice(index, 1);
  47645. index--;
  47646. }
  47647. event.isDone = true;
  47648. event.action();
  47649. } // Don't do anything if the event has already be done.
  47650. }
  47651. else if (events[index].isDone && !events[index].onlyOnce) {
  47652. // reset event, the animation is looping
  47653. events[index].isDone = false;
  47654. }
  47655. }
  47656. if (!returnValue) {
  47657. this._stopped = true;
  47658. }
  47659. return returnValue;
  47660. };
  47661. return RuntimeAnimation;
  47662. }());
  47663. BABYLON.RuntimeAnimation = RuntimeAnimation;
  47664. })(BABYLON || (BABYLON = {}));
  47665. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  47666. var BABYLON;
  47667. (function (BABYLON) {
  47668. var Animatable = /** @class */ (function () {
  47669. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  47670. if (fromFrame === void 0) { fromFrame = 0; }
  47671. if (toFrame === void 0) { toFrame = 100; }
  47672. if (loopAnimation === void 0) { loopAnimation = false; }
  47673. if (speedRatio === void 0) { speedRatio = 1.0; }
  47674. this.target = target;
  47675. this.fromFrame = fromFrame;
  47676. this.toFrame = toFrame;
  47677. this.loopAnimation = loopAnimation;
  47678. this.onAnimationEnd = onAnimationEnd;
  47679. this._localDelayOffset = null;
  47680. this._pausedDelay = null;
  47681. this._runtimeAnimations = new Array();
  47682. this._paused = false;
  47683. this._speedRatio = 1;
  47684. this.animationStarted = false;
  47685. if (animations) {
  47686. this.appendAnimations(target, animations);
  47687. }
  47688. this._speedRatio = speedRatio;
  47689. this._scene = scene;
  47690. scene._activeAnimatables.push(this);
  47691. }
  47692. Object.defineProperty(Animatable.prototype, "speedRatio", {
  47693. get: function () {
  47694. return this._speedRatio;
  47695. },
  47696. set: function (value) {
  47697. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  47698. var animation = this._runtimeAnimations[index];
  47699. animation._prepareForSpeedRatioChange(value);
  47700. }
  47701. this._speedRatio = value;
  47702. },
  47703. enumerable: true,
  47704. configurable: true
  47705. });
  47706. // Methods
  47707. Animatable.prototype.getAnimations = function () {
  47708. return this._runtimeAnimations;
  47709. };
  47710. Animatable.prototype.appendAnimations = function (target, animations) {
  47711. for (var index = 0; index < animations.length; index++) {
  47712. var animation = animations[index];
  47713. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation));
  47714. }
  47715. };
  47716. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  47717. var runtimeAnimations = this._runtimeAnimations;
  47718. for (var index = 0; index < runtimeAnimations.length; index++) {
  47719. if (runtimeAnimations[index].animation.targetProperty === property) {
  47720. return runtimeAnimations[index].animation;
  47721. }
  47722. }
  47723. return null;
  47724. };
  47725. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  47726. var runtimeAnimations = this._runtimeAnimations;
  47727. for (var index = 0; index < runtimeAnimations.length; index++) {
  47728. if (runtimeAnimations[index].animation.targetProperty === property) {
  47729. return runtimeAnimations[index];
  47730. }
  47731. }
  47732. return null;
  47733. };
  47734. Animatable.prototype.reset = function () {
  47735. var runtimeAnimations = this._runtimeAnimations;
  47736. for (var index = 0; index < runtimeAnimations.length; index++) {
  47737. runtimeAnimations[index].reset();
  47738. }
  47739. // Reset to original value
  47740. for (index = 0; index < runtimeAnimations.length; index++) {
  47741. var animation = runtimeAnimations[index];
  47742. animation.animate(0, this.fromFrame, this.toFrame, false, this._speedRatio);
  47743. }
  47744. this._localDelayOffset = null;
  47745. this._pausedDelay = null;
  47746. };
  47747. Animatable.prototype.enableBlending = function (blendingSpeed) {
  47748. var runtimeAnimations = this._runtimeAnimations;
  47749. for (var index = 0; index < runtimeAnimations.length; index++) {
  47750. runtimeAnimations[index].animation.enableBlending = true;
  47751. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  47752. }
  47753. };
  47754. Animatable.prototype.disableBlending = function () {
  47755. var runtimeAnimations = this._runtimeAnimations;
  47756. for (var index = 0; index < runtimeAnimations.length; index++) {
  47757. runtimeAnimations[index].animation.enableBlending = false;
  47758. }
  47759. };
  47760. Animatable.prototype.goToFrame = function (frame) {
  47761. var runtimeAnimations = this._runtimeAnimations;
  47762. if (runtimeAnimations[0]) {
  47763. var fps = runtimeAnimations[0].animation.framePerSecond;
  47764. var currentFrame = runtimeAnimations[0].currentFrame;
  47765. var adjustTime = frame - currentFrame;
  47766. var delay = adjustTime * 1000 / (fps * this.speedRatio);
  47767. if (this._localDelayOffset === null) {
  47768. this._localDelayOffset = 0;
  47769. }
  47770. this._localDelayOffset -= delay;
  47771. }
  47772. for (var index = 0; index < runtimeAnimations.length; index++) {
  47773. runtimeAnimations[index].goToFrame(frame);
  47774. }
  47775. };
  47776. Animatable.prototype.pause = function () {
  47777. if (this._paused) {
  47778. return;
  47779. }
  47780. this._paused = true;
  47781. };
  47782. Animatable.prototype.restart = function () {
  47783. this._paused = false;
  47784. };
  47785. Animatable.prototype.stop = function (animationName) {
  47786. if (animationName) {
  47787. var idx = this._scene._activeAnimatables.indexOf(this);
  47788. if (idx > -1) {
  47789. var runtimeAnimations = this._runtimeAnimations;
  47790. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  47791. if (typeof animationName === "string" && runtimeAnimations[index].animation.name != animationName) {
  47792. continue;
  47793. }
  47794. runtimeAnimations[index].dispose();
  47795. runtimeAnimations.splice(index, 1);
  47796. }
  47797. if (runtimeAnimations.length == 0) {
  47798. this._scene._activeAnimatables.splice(idx, 1);
  47799. if (this.onAnimationEnd) {
  47800. this.onAnimationEnd();
  47801. }
  47802. }
  47803. }
  47804. }
  47805. else {
  47806. var index = this._scene._activeAnimatables.indexOf(this);
  47807. if (index > -1) {
  47808. this._scene._activeAnimatables.splice(index, 1);
  47809. var runtimeAnimations = this._runtimeAnimations;
  47810. for (var index = 0; index < runtimeAnimations.length; index++) {
  47811. runtimeAnimations[index].dispose();
  47812. }
  47813. if (this.onAnimationEnd) {
  47814. this.onAnimationEnd();
  47815. }
  47816. }
  47817. }
  47818. };
  47819. Animatable.prototype._animate = function (delay) {
  47820. if (this._paused) {
  47821. this.animationStarted = false;
  47822. if (this._pausedDelay === null) {
  47823. this._pausedDelay = delay;
  47824. }
  47825. return true;
  47826. }
  47827. if (this._localDelayOffset === null) {
  47828. this._localDelayOffset = delay;
  47829. this._pausedDelay = null;
  47830. }
  47831. else if (this._pausedDelay !== null) {
  47832. this._localDelayOffset += delay - this._pausedDelay;
  47833. this._pausedDelay = null;
  47834. }
  47835. // Animating
  47836. var running = false;
  47837. var runtimeAnimations = this._runtimeAnimations;
  47838. var index;
  47839. for (index = 0; index < runtimeAnimations.length; index++) {
  47840. var animation = runtimeAnimations[index];
  47841. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio);
  47842. running = running || isRunning;
  47843. }
  47844. this.animationStarted = running;
  47845. if (!running) {
  47846. // Remove from active animatables
  47847. index = this._scene._activeAnimatables.indexOf(this);
  47848. this._scene._activeAnimatables.splice(index, 1);
  47849. // Dispose all runtime animations
  47850. for (index = 0; index < runtimeAnimations.length; index++) {
  47851. runtimeAnimations[index].dispose();
  47852. }
  47853. }
  47854. if (!running && this.onAnimationEnd) {
  47855. this.onAnimationEnd();
  47856. this.onAnimationEnd = null;
  47857. }
  47858. return running;
  47859. };
  47860. return Animatable;
  47861. }());
  47862. BABYLON.Animatable = Animatable;
  47863. })(BABYLON || (BABYLON = {}));
  47864. //# sourceMappingURL=babylon.animatable.js.map
  47865. var BABYLON;
  47866. (function (BABYLON) {
  47867. var EasingFunction = /** @class */ (function () {
  47868. function EasingFunction() {
  47869. // Properties
  47870. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  47871. }
  47872. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  47873. get: function () {
  47874. return EasingFunction._EASINGMODE_EASEIN;
  47875. },
  47876. enumerable: true,
  47877. configurable: true
  47878. });
  47879. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  47880. get: function () {
  47881. return EasingFunction._EASINGMODE_EASEOUT;
  47882. },
  47883. enumerable: true,
  47884. configurable: true
  47885. });
  47886. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  47887. get: function () {
  47888. return EasingFunction._EASINGMODE_EASEINOUT;
  47889. },
  47890. enumerable: true,
  47891. configurable: true
  47892. });
  47893. EasingFunction.prototype.setEasingMode = function (easingMode) {
  47894. var n = Math.min(Math.max(easingMode, 0), 2);
  47895. this._easingMode = n;
  47896. };
  47897. EasingFunction.prototype.getEasingMode = function () {
  47898. return this._easingMode;
  47899. };
  47900. EasingFunction.prototype.easeInCore = function (gradient) {
  47901. throw new Error('You must implement this method');
  47902. };
  47903. EasingFunction.prototype.ease = function (gradient) {
  47904. switch (this._easingMode) {
  47905. case EasingFunction.EASINGMODE_EASEIN:
  47906. return this.easeInCore(gradient);
  47907. case EasingFunction.EASINGMODE_EASEOUT:
  47908. return (1 - this.easeInCore(1 - gradient));
  47909. }
  47910. if (gradient >= 0.5) {
  47911. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  47912. }
  47913. return (this.easeInCore(gradient * 2) * 0.5);
  47914. };
  47915. //Statics
  47916. EasingFunction._EASINGMODE_EASEIN = 0;
  47917. EasingFunction._EASINGMODE_EASEOUT = 1;
  47918. EasingFunction._EASINGMODE_EASEINOUT = 2;
  47919. return EasingFunction;
  47920. }());
  47921. BABYLON.EasingFunction = EasingFunction;
  47922. var CircleEase = /** @class */ (function (_super) {
  47923. __extends(CircleEase, _super);
  47924. function CircleEase() {
  47925. return _super !== null && _super.apply(this, arguments) || this;
  47926. }
  47927. CircleEase.prototype.easeInCore = function (gradient) {
  47928. gradient = Math.max(0, Math.min(1, gradient));
  47929. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  47930. };
  47931. return CircleEase;
  47932. }(EasingFunction));
  47933. BABYLON.CircleEase = CircleEase;
  47934. var BackEase = /** @class */ (function (_super) {
  47935. __extends(BackEase, _super);
  47936. function BackEase(amplitude) {
  47937. if (amplitude === void 0) { amplitude = 1; }
  47938. var _this = _super.call(this) || this;
  47939. _this.amplitude = amplitude;
  47940. return _this;
  47941. }
  47942. BackEase.prototype.easeInCore = function (gradient) {
  47943. var num = Math.max(0, this.amplitude);
  47944. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  47945. };
  47946. return BackEase;
  47947. }(EasingFunction));
  47948. BABYLON.BackEase = BackEase;
  47949. var BounceEase = /** @class */ (function (_super) {
  47950. __extends(BounceEase, _super);
  47951. function BounceEase(bounces, bounciness) {
  47952. if (bounces === void 0) { bounces = 3; }
  47953. if (bounciness === void 0) { bounciness = 2; }
  47954. var _this = _super.call(this) || this;
  47955. _this.bounces = bounces;
  47956. _this.bounciness = bounciness;
  47957. return _this;
  47958. }
  47959. BounceEase.prototype.easeInCore = function (gradient) {
  47960. var y = Math.max(0.0, this.bounces);
  47961. var bounciness = this.bounciness;
  47962. if (bounciness <= 1.0) {
  47963. bounciness = 1.001;
  47964. }
  47965. var num9 = Math.pow(bounciness, y);
  47966. var num5 = 1.0 - bounciness;
  47967. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  47968. var num15 = gradient * num4;
  47969. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  47970. var num3 = Math.floor(num65);
  47971. var num13 = num3 + 1.0;
  47972. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  47973. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  47974. var num7 = (num8 + num12) * 0.5;
  47975. var num6 = gradient - num7;
  47976. var num2 = num7 - num8;
  47977. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  47978. };
  47979. return BounceEase;
  47980. }(EasingFunction));
  47981. BABYLON.BounceEase = BounceEase;
  47982. var CubicEase = /** @class */ (function (_super) {
  47983. __extends(CubicEase, _super);
  47984. function CubicEase() {
  47985. return _super !== null && _super.apply(this, arguments) || this;
  47986. }
  47987. CubicEase.prototype.easeInCore = function (gradient) {
  47988. return (gradient * gradient * gradient);
  47989. };
  47990. return CubicEase;
  47991. }(EasingFunction));
  47992. BABYLON.CubicEase = CubicEase;
  47993. var ElasticEase = /** @class */ (function (_super) {
  47994. __extends(ElasticEase, _super);
  47995. function ElasticEase(oscillations, springiness) {
  47996. if (oscillations === void 0) { oscillations = 3; }
  47997. if (springiness === void 0) { springiness = 3; }
  47998. var _this = _super.call(this) || this;
  47999. _this.oscillations = oscillations;
  48000. _this.springiness = springiness;
  48001. return _this;
  48002. }
  48003. ElasticEase.prototype.easeInCore = function (gradient) {
  48004. var num2;
  48005. var num3 = Math.max(0.0, this.oscillations);
  48006. var num = Math.max(0.0, this.springiness);
  48007. if (num == 0) {
  48008. num2 = gradient;
  48009. }
  48010. else {
  48011. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  48012. }
  48013. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  48014. };
  48015. return ElasticEase;
  48016. }(EasingFunction));
  48017. BABYLON.ElasticEase = ElasticEase;
  48018. var ExponentialEase = /** @class */ (function (_super) {
  48019. __extends(ExponentialEase, _super);
  48020. function ExponentialEase(exponent) {
  48021. if (exponent === void 0) { exponent = 2; }
  48022. var _this = _super.call(this) || this;
  48023. _this.exponent = exponent;
  48024. return _this;
  48025. }
  48026. ExponentialEase.prototype.easeInCore = function (gradient) {
  48027. if (this.exponent <= 0) {
  48028. return gradient;
  48029. }
  48030. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  48031. };
  48032. return ExponentialEase;
  48033. }(EasingFunction));
  48034. BABYLON.ExponentialEase = ExponentialEase;
  48035. var PowerEase = /** @class */ (function (_super) {
  48036. __extends(PowerEase, _super);
  48037. function PowerEase(power) {
  48038. if (power === void 0) { power = 2; }
  48039. var _this = _super.call(this) || this;
  48040. _this.power = power;
  48041. return _this;
  48042. }
  48043. PowerEase.prototype.easeInCore = function (gradient) {
  48044. var y = Math.max(0.0, this.power);
  48045. return Math.pow(gradient, y);
  48046. };
  48047. return PowerEase;
  48048. }(EasingFunction));
  48049. BABYLON.PowerEase = PowerEase;
  48050. var QuadraticEase = /** @class */ (function (_super) {
  48051. __extends(QuadraticEase, _super);
  48052. function QuadraticEase() {
  48053. return _super !== null && _super.apply(this, arguments) || this;
  48054. }
  48055. QuadraticEase.prototype.easeInCore = function (gradient) {
  48056. return (gradient * gradient);
  48057. };
  48058. return QuadraticEase;
  48059. }(EasingFunction));
  48060. BABYLON.QuadraticEase = QuadraticEase;
  48061. var QuarticEase = /** @class */ (function (_super) {
  48062. __extends(QuarticEase, _super);
  48063. function QuarticEase() {
  48064. return _super !== null && _super.apply(this, arguments) || this;
  48065. }
  48066. QuarticEase.prototype.easeInCore = function (gradient) {
  48067. return (gradient * gradient * gradient * gradient);
  48068. };
  48069. return QuarticEase;
  48070. }(EasingFunction));
  48071. BABYLON.QuarticEase = QuarticEase;
  48072. var QuinticEase = /** @class */ (function (_super) {
  48073. __extends(QuinticEase, _super);
  48074. function QuinticEase() {
  48075. return _super !== null && _super.apply(this, arguments) || this;
  48076. }
  48077. QuinticEase.prototype.easeInCore = function (gradient) {
  48078. return (gradient * gradient * gradient * gradient * gradient);
  48079. };
  48080. return QuinticEase;
  48081. }(EasingFunction));
  48082. BABYLON.QuinticEase = QuinticEase;
  48083. var SineEase = /** @class */ (function (_super) {
  48084. __extends(SineEase, _super);
  48085. function SineEase() {
  48086. return _super !== null && _super.apply(this, arguments) || this;
  48087. }
  48088. SineEase.prototype.easeInCore = function (gradient) {
  48089. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  48090. };
  48091. return SineEase;
  48092. }(EasingFunction));
  48093. BABYLON.SineEase = SineEase;
  48094. var BezierCurveEase = /** @class */ (function (_super) {
  48095. __extends(BezierCurveEase, _super);
  48096. function BezierCurveEase(x1, y1, x2, y2) {
  48097. if (x1 === void 0) { x1 = 0; }
  48098. if (y1 === void 0) { y1 = 0; }
  48099. if (x2 === void 0) { x2 = 1; }
  48100. if (y2 === void 0) { y2 = 1; }
  48101. var _this = _super.call(this) || this;
  48102. _this.x1 = x1;
  48103. _this.y1 = y1;
  48104. _this.x2 = x2;
  48105. _this.y2 = y2;
  48106. return _this;
  48107. }
  48108. BezierCurveEase.prototype.easeInCore = function (gradient) {
  48109. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  48110. };
  48111. return BezierCurveEase;
  48112. }(EasingFunction));
  48113. BABYLON.BezierCurveEase = BezierCurveEase;
  48114. })(BABYLON || (BABYLON = {}));
  48115. //# sourceMappingURL=babylon.easing.js.map
  48116. var BABYLON;
  48117. (function (BABYLON) {
  48118. var Condition = /** @class */ (function () {
  48119. function Condition(actionManager) {
  48120. this._actionManager = actionManager;
  48121. }
  48122. Condition.prototype.isValid = function () {
  48123. return true;
  48124. };
  48125. Condition.prototype._getProperty = function (propertyPath) {
  48126. return this._actionManager._getProperty(propertyPath);
  48127. };
  48128. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  48129. return this._actionManager._getEffectiveTarget(target, propertyPath);
  48130. };
  48131. Condition.prototype.serialize = function () {
  48132. };
  48133. Condition.prototype._serialize = function (serializedCondition) {
  48134. return {
  48135. type: 2,
  48136. children: [],
  48137. name: serializedCondition.name,
  48138. properties: serializedCondition.properties
  48139. };
  48140. };
  48141. return Condition;
  48142. }());
  48143. BABYLON.Condition = Condition;
  48144. var ValueCondition = /** @class */ (function (_super) {
  48145. __extends(ValueCondition, _super);
  48146. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  48147. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  48148. var _this = _super.call(this, actionManager) || this;
  48149. _this.propertyPath = propertyPath;
  48150. _this.value = value;
  48151. _this.operator = operator;
  48152. _this._target = target;
  48153. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  48154. _this._property = _this._getProperty(_this.propertyPath);
  48155. return _this;
  48156. }
  48157. Object.defineProperty(ValueCondition, "IsEqual", {
  48158. get: function () {
  48159. return ValueCondition._IsEqual;
  48160. },
  48161. enumerable: true,
  48162. configurable: true
  48163. });
  48164. Object.defineProperty(ValueCondition, "IsDifferent", {
  48165. get: function () {
  48166. return ValueCondition._IsDifferent;
  48167. },
  48168. enumerable: true,
  48169. configurable: true
  48170. });
  48171. Object.defineProperty(ValueCondition, "IsGreater", {
  48172. get: function () {
  48173. return ValueCondition._IsGreater;
  48174. },
  48175. enumerable: true,
  48176. configurable: true
  48177. });
  48178. Object.defineProperty(ValueCondition, "IsLesser", {
  48179. get: function () {
  48180. return ValueCondition._IsLesser;
  48181. },
  48182. enumerable: true,
  48183. configurable: true
  48184. });
  48185. // Methods
  48186. ValueCondition.prototype.isValid = function () {
  48187. switch (this.operator) {
  48188. case ValueCondition.IsGreater:
  48189. return this._effectiveTarget[this._property] > this.value;
  48190. case ValueCondition.IsLesser:
  48191. return this._effectiveTarget[this._property] < this.value;
  48192. case ValueCondition.IsEqual:
  48193. case ValueCondition.IsDifferent:
  48194. var check;
  48195. if (this.value.equals) {
  48196. check = this.value.equals(this._effectiveTarget[this._property]);
  48197. }
  48198. else {
  48199. check = this.value === this._effectiveTarget[this._property];
  48200. }
  48201. return this.operator === ValueCondition.IsEqual ? check : !check;
  48202. }
  48203. return false;
  48204. };
  48205. ValueCondition.prototype.serialize = function () {
  48206. return this._serialize({
  48207. name: "ValueCondition",
  48208. properties: [
  48209. BABYLON.Action._GetTargetProperty(this._target),
  48210. { name: "propertyPath", value: this.propertyPath },
  48211. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  48212. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  48213. ]
  48214. });
  48215. };
  48216. ValueCondition.GetOperatorName = function (operator) {
  48217. switch (operator) {
  48218. case ValueCondition._IsEqual: return "IsEqual";
  48219. case ValueCondition._IsDifferent: return "IsDifferent";
  48220. case ValueCondition._IsGreater: return "IsGreater";
  48221. case ValueCondition._IsLesser: return "IsLesser";
  48222. default: return "";
  48223. }
  48224. };
  48225. // Statics
  48226. ValueCondition._IsEqual = 0;
  48227. ValueCondition._IsDifferent = 1;
  48228. ValueCondition._IsGreater = 2;
  48229. ValueCondition._IsLesser = 3;
  48230. return ValueCondition;
  48231. }(Condition));
  48232. BABYLON.ValueCondition = ValueCondition;
  48233. var PredicateCondition = /** @class */ (function (_super) {
  48234. __extends(PredicateCondition, _super);
  48235. function PredicateCondition(actionManager, predicate) {
  48236. var _this = _super.call(this, actionManager) || this;
  48237. _this.predicate = predicate;
  48238. return _this;
  48239. }
  48240. PredicateCondition.prototype.isValid = function () {
  48241. return this.predicate();
  48242. };
  48243. return PredicateCondition;
  48244. }(Condition));
  48245. BABYLON.PredicateCondition = PredicateCondition;
  48246. var StateCondition = /** @class */ (function (_super) {
  48247. __extends(StateCondition, _super);
  48248. function StateCondition(actionManager, target, value) {
  48249. var _this = _super.call(this, actionManager) || this;
  48250. _this.value = value;
  48251. _this._target = target;
  48252. return _this;
  48253. }
  48254. // Methods
  48255. StateCondition.prototype.isValid = function () {
  48256. return this._target.state === this.value;
  48257. };
  48258. StateCondition.prototype.serialize = function () {
  48259. return this._serialize({
  48260. name: "StateCondition",
  48261. properties: [
  48262. BABYLON.Action._GetTargetProperty(this._target),
  48263. { name: "value", value: this.value }
  48264. ]
  48265. });
  48266. };
  48267. return StateCondition;
  48268. }(Condition));
  48269. BABYLON.StateCondition = StateCondition;
  48270. })(BABYLON || (BABYLON = {}));
  48271. //# sourceMappingURL=babylon.condition.js.map
  48272. var BABYLON;
  48273. (function (BABYLON) {
  48274. var Action = /** @class */ (function () {
  48275. function Action(triggerOptions, condition) {
  48276. this.triggerOptions = triggerOptions;
  48277. this.onBeforeExecuteObservable = new BABYLON.Observable();
  48278. if (triggerOptions.parameter) {
  48279. this.trigger = triggerOptions.trigger;
  48280. this._triggerParameter = triggerOptions.parameter;
  48281. }
  48282. else {
  48283. this.trigger = triggerOptions;
  48284. }
  48285. this._nextActiveAction = this;
  48286. this._condition = condition;
  48287. }
  48288. // Methods
  48289. Action.prototype._prepare = function () {
  48290. };
  48291. Action.prototype.getTriggerParameter = function () {
  48292. return this._triggerParameter;
  48293. };
  48294. Action.prototype._executeCurrent = function (evt) {
  48295. if (this._nextActiveAction._condition) {
  48296. var condition = this._nextActiveAction._condition;
  48297. var currentRenderId = this._actionManager.getScene().getRenderId();
  48298. // We cache the current evaluation for the current frame
  48299. if (condition._evaluationId === currentRenderId) {
  48300. if (!condition._currentResult) {
  48301. return;
  48302. }
  48303. }
  48304. else {
  48305. condition._evaluationId = currentRenderId;
  48306. if (!condition.isValid()) {
  48307. condition._currentResult = false;
  48308. return;
  48309. }
  48310. condition._currentResult = true;
  48311. }
  48312. }
  48313. this.onBeforeExecuteObservable.notifyObservers(this);
  48314. this._nextActiveAction.execute(evt);
  48315. this.skipToNextActiveAction();
  48316. };
  48317. Action.prototype.execute = function (evt) {
  48318. };
  48319. Action.prototype.skipToNextActiveAction = function () {
  48320. if (this._nextActiveAction._child) {
  48321. if (!this._nextActiveAction._child._actionManager) {
  48322. this._nextActiveAction._child._actionManager = this._actionManager;
  48323. }
  48324. this._nextActiveAction = this._nextActiveAction._child;
  48325. }
  48326. else {
  48327. this._nextActiveAction = this;
  48328. }
  48329. };
  48330. Action.prototype.then = function (action) {
  48331. this._child = action;
  48332. action._actionManager = this._actionManager;
  48333. action._prepare();
  48334. return action;
  48335. };
  48336. Action.prototype._getProperty = function (propertyPath) {
  48337. return this._actionManager._getProperty(propertyPath);
  48338. };
  48339. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  48340. return this._actionManager._getEffectiveTarget(target, propertyPath);
  48341. };
  48342. Action.prototype.serialize = function (parent) {
  48343. };
  48344. // Called by BABYLON.Action objects in serialize(...). Internal use
  48345. Action.prototype._serialize = function (serializedAction, parent) {
  48346. var serializationObject = {
  48347. type: 1,
  48348. children: [],
  48349. name: serializedAction.name,
  48350. properties: serializedAction.properties || []
  48351. };
  48352. // Serialize child
  48353. if (this._child) {
  48354. this._child.serialize(serializationObject);
  48355. }
  48356. // Check if "this" has a condition
  48357. if (this._condition) {
  48358. var serializedCondition = this._condition.serialize();
  48359. serializedCondition.children.push(serializationObject);
  48360. if (parent) {
  48361. parent.children.push(serializedCondition);
  48362. }
  48363. return serializedCondition;
  48364. }
  48365. if (parent) {
  48366. parent.children.push(serializationObject);
  48367. }
  48368. return serializationObject;
  48369. };
  48370. Action._SerializeValueAsString = function (value) {
  48371. if (typeof value === "number") {
  48372. return value.toString();
  48373. }
  48374. if (typeof value === "boolean") {
  48375. return value ? "true" : "false";
  48376. }
  48377. if (value instanceof BABYLON.Vector2) {
  48378. return value.x + ", " + value.y;
  48379. }
  48380. if (value instanceof BABYLON.Vector3) {
  48381. return value.x + ", " + value.y + ", " + value.z;
  48382. }
  48383. if (value instanceof BABYLON.Color3) {
  48384. return value.r + ", " + value.g + ", " + value.b;
  48385. }
  48386. if (value instanceof BABYLON.Color4) {
  48387. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  48388. }
  48389. return value; // string
  48390. };
  48391. Action._GetTargetProperty = function (target) {
  48392. return {
  48393. name: "target",
  48394. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  48395. : target instanceof BABYLON.Light ? "LightProperties"
  48396. : target instanceof BABYLON.Camera ? "CameraProperties"
  48397. : "SceneProperties",
  48398. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  48399. };
  48400. };
  48401. return Action;
  48402. }());
  48403. BABYLON.Action = Action;
  48404. })(BABYLON || (BABYLON = {}));
  48405. //# sourceMappingURL=babylon.action.js.map
  48406. var BABYLON;
  48407. (function (BABYLON) {
  48408. /**
  48409. * ActionEvent is the event beint sent when an action is triggered.
  48410. */
  48411. var ActionEvent = /** @class */ (function () {
  48412. /**
  48413. * @param source The mesh or sprite that triggered the action.
  48414. * @param pointerX The X mouse cursor position at the time of the event
  48415. * @param pointerY The Y mouse cursor position at the time of the event
  48416. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  48417. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  48418. */
  48419. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  48420. this.source = source;
  48421. this.pointerX = pointerX;
  48422. this.pointerY = pointerY;
  48423. this.meshUnderPointer = meshUnderPointer;
  48424. this.sourceEvent = sourceEvent;
  48425. this.additionalData = additionalData;
  48426. }
  48427. /**
  48428. * Helper function to auto-create an ActionEvent from a source mesh.
  48429. * @param source The source mesh that triggered the event
  48430. * @param evt {Event} The original (browser) event
  48431. */
  48432. ActionEvent.CreateNew = function (source, evt, additionalData) {
  48433. var scene = source.getScene();
  48434. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  48435. };
  48436. /**
  48437. * Helper function to auto-create an ActionEvent from a source mesh.
  48438. * @param source The source sprite that triggered the event
  48439. * @param scene Scene associated with the sprite
  48440. * @param evt {Event} The original (browser) event
  48441. */
  48442. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  48443. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  48444. };
  48445. /**
  48446. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  48447. * @param scene the scene where the event occurred
  48448. * @param evt {Event} The original (browser) event
  48449. */
  48450. ActionEvent.CreateNewFromScene = function (scene, evt) {
  48451. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  48452. };
  48453. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  48454. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  48455. };
  48456. return ActionEvent;
  48457. }());
  48458. BABYLON.ActionEvent = ActionEvent;
  48459. /**
  48460. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  48461. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  48462. */
  48463. var ActionManager = /** @class */ (function () {
  48464. function ActionManager(scene) {
  48465. // Members
  48466. this.actions = new Array();
  48467. this.hoverCursor = '';
  48468. this._scene = scene;
  48469. scene._actionManagers.push(this);
  48470. }
  48471. Object.defineProperty(ActionManager, "NothingTrigger", {
  48472. get: function () {
  48473. return ActionManager._NothingTrigger;
  48474. },
  48475. enumerable: true,
  48476. configurable: true
  48477. });
  48478. Object.defineProperty(ActionManager, "OnPickTrigger", {
  48479. get: function () {
  48480. return ActionManager._OnPickTrigger;
  48481. },
  48482. enumerable: true,
  48483. configurable: true
  48484. });
  48485. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  48486. get: function () {
  48487. return ActionManager._OnLeftPickTrigger;
  48488. },
  48489. enumerable: true,
  48490. configurable: true
  48491. });
  48492. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  48493. get: function () {
  48494. return ActionManager._OnRightPickTrigger;
  48495. },
  48496. enumerable: true,
  48497. configurable: true
  48498. });
  48499. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  48500. get: function () {
  48501. return ActionManager._OnCenterPickTrigger;
  48502. },
  48503. enumerable: true,
  48504. configurable: true
  48505. });
  48506. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  48507. get: function () {
  48508. return ActionManager._OnPickDownTrigger;
  48509. },
  48510. enumerable: true,
  48511. configurable: true
  48512. });
  48513. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  48514. get: function () {
  48515. return ActionManager._OnDoublePickTrigger;
  48516. },
  48517. enumerable: true,
  48518. configurable: true
  48519. });
  48520. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  48521. get: function () {
  48522. return ActionManager._OnPickUpTrigger;
  48523. },
  48524. enumerable: true,
  48525. configurable: true
  48526. });
  48527. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  48528. /// This trigger will only be raised if you also declared a OnPickDown
  48529. get: function () {
  48530. return ActionManager._OnPickOutTrigger;
  48531. },
  48532. enumerable: true,
  48533. configurable: true
  48534. });
  48535. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  48536. get: function () {
  48537. return ActionManager._OnLongPressTrigger;
  48538. },
  48539. enumerable: true,
  48540. configurable: true
  48541. });
  48542. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  48543. get: function () {
  48544. return ActionManager._OnPointerOverTrigger;
  48545. },
  48546. enumerable: true,
  48547. configurable: true
  48548. });
  48549. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  48550. get: function () {
  48551. return ActionManager._OnPointerOutTrigger;
  48552. },
  48553. enumerable: true,
  48554. configurable: true
  48555. });
  48556. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  48557. get: function () {
  48558. return ActionManager._OnEveryFrameTrigger;
  48559. },
  48560. enumerable: true,
  48561. configurable: true
  48562. });
  48563. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  48564. get: function () {
  48565. return ActionManager._OnIntersectionEnterTrigger;
  48566. },
  48567. enumerable: true,
  48568. configurable: true
  48569. });
  48570. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  48571. get: function () {
  48572. return ActionManager._OnIntersectionExitTrigger;
  48573. },
  48574. enumerable: true,
  48575. configurable: true
  48576. });
  48577. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  48578. get: function () {
  48579. return ActionManager._OnKeyDownTrigger;
  48580. },
  48581. enumerable: true,
  48582. configurable: true
  48583. });
  48584. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  48585. get: function () {
  48586. return ActionManager._OnKeyUpTrigger;
  48587. },
  48588. enumerable: true,
  48589. configurable: true
  48590. });
  48591. // Methods
  48592. ActionManager.prototype.dispose = function () {
  48593. var index = this._scene._actionManagers.indexOf(this);
  48594. for (var i = 0; i < this.actions.length; i++) {
  48595. var action = this.actions[i];
  48596. ActionManager.Triggers[action.trigger]--;
  48597. if (ActionManager.Triggers[action.trigger] === 0) {
  48598. delete ActionManager.Triggers[action.trigger];
  48599. }
  48600. }
  48601. if (index > -1) {
  48602. this._scene._actionManagers.splice(index, 1);
  48603. }
  48604. };
  48605. ActionManager.prototype.getScene = function () {
  48606. return this._scene;
  48607. };
  48608. /**
  48609. * Does this action manager handles actions of any of the given triggers
  48610. * @param {number[]} triggers - the triggers to be tested
  48611. * @return {boolean} whether one (or more) of the triggers is handeled
  48612. */
  48613. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  48614. for (var index = 0; index < this.actions.length; index++) {
  48615. var action = this.actions[index];
  48616. if (triggers.indexOf(action.trigger) > -1) {
  48617. return true;
  48618. }
  48619. }
  48620. return false;
  48621. };
  48622. /**
  48623. * Does this action manager handles actions of a given trigger
  48624. * @param {number} trigger - the trigger to be tested
  48625. * @return {boolean} whether the trigger is handeled
  48626. */
  48627. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  48628. for (var index = 0; index < this.actions.length; index++) {
  48629. var action = this.actions[index];
  48630. if (action.trigger === trigger) {
  48631. return true;
  48632. }
  48633. }
  48634. return false;
  48635. };
  48636. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  48637. /**
  48638. * Does this action manager has pointer triggers
  48639. * @return {boolean} whether or not it has pointer triggers
  48640. */
  48641. get: function () {
  48642. for (var index = 0; index < this.actions.length; index++) {
  48643. var action = this.actions[index];
  48644. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  48645. return true;
  48646. }
  48647. }
  48648. return false;
  48649. },
  48650. enumerable: true,
  48651. configurable: true
  48652. });
  48653. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  48654. /**
  48655. * Does this action manager has pick triggers
  48656. * @return {boolean} whether or not it has pick triggers
  48657. */
  48658. get: function () {
  48659. for (var index = 0; index < this.actions.length; index++) {
  48660. var action = this.actions[index];
  48661. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  48662. return true;
  48663. }
  48664. }
  48665. return false;
  48666. },
  48667. enumerable: true,
  48668. configurable: true
  48669. });
  48670. Object.defineProperty(ActionManager, "HasTriggers", {
  48671. /**
  48672. * Does exist one action manager with at least one trigger
  48673. * @return {boolean} whether or not it exists one action manager with one trigger
  48674. **/
  48675. get: function () {
  48676. for (var t in ActionManager.Triggers) {
  48677. if (ActionManager.Triggers.hasOwnProperty(t)) {
  48678. return true;
  48679. }
  48680. }
  48681. return false;
  48682. },
  48683. enumerable: true,
  48684. configurable: true
  48685. });
  48686. Object.defineProperty(ActionManager, "HasPickTriggers", {
  48687. /**
  48688. * Does exist one action manager with at least one pick trigger
  48689. * @return {boolean} whether or not it exists one action manager with one pick trigger
  48690. **/
  48691. get: function () {
  48692. for (var t in ActionManager.Triggers) {
  48693. if (ActionManager.Triggers.hasOwnProperty(t)) {
  48694. var t_int = parseInt(t);
  48695. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  48696. return true;
  48697. }
  48698. }
  48699. }
  48700. return false;
  48701. },
  48702. enumerable: true,
  48703. configurable: true
  48704. });
  48705. /**
  48706. * Does exist one action manager that handles actions of a given trigger
  48707. * @param {number} trigger - the trigger to be tested
  48708. * @return {boolean} whether the trigger is handeled by at least one action manager
  48709. **/
  48710. ActionManager.HasSpecificTrigger = function (trigger) {
  48711. for (var t in ActionManager.Triggers) {
  48712. if (ActionManager.Triggers.hasOwnProperty(t)) {
  48713. var t_int = parseInt(t);
  48714. if (t_int === trigger) {
  48715. return true;
  48716. }
  48717. }
  48718. }
  48719. return false;
  48720. };
  48721. /**
  48722. * Registers an action to this action manager
  48723. * @param {BABYLON.Action} action - the action to be registered
  48724. * @return {BABYLON.Action} the action amended (prepared) after registration
  48725. */
  48726. ActionManager.prototype.registerAction = function (action) {
  48727. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  48728. if (this.getScene().actionManager !== this) {
  48729. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  48730. return null;
  48731. }
  48732. }
  48733. this.actions.push(action);
  48734. if (ActionManager.Triggers[action.trigger]) {
  48735. ActionManager.Triggers[action.trigger]++;
  48736. }
  48737. else {
  48738. ActionManager.Triggers[action.trigger] = 1;
  48739. }
  48740. action._actionManager = this;
  48741. action._prepare();
  48742. return action;
  48743. };
  48744. /**
  48745. * Unregisters an action to this action manager
  48746. * @param action The action to be unregistered
  48747. * @return whether the action has been unregistered
  48748. */
  48749. ActionManager.prototype.unregisterAction = function (action) {
  48750. var index = this.actions.indexOf(action);
  48751. if (index !== -1) {
  48752. this.actions.splice(index, 1);
  48753. ActionManager.Triggers[action.trigger] -= 1;
  48754. if (ActionManager.Triggers[action.trigger] === 0) {
  48755. delete ActionManager.Triggers[action.trigger];
  48756. }
  48757. delete action._actionManager;
  48758. return true;
  48759. }
  48760. return false;
  48761. };
  48762. /**
  48763. * Process a specific trigger
  48764. * @param {number} trigger - the trigger to process
  48765. * @param evt {BABYLON.ActionEvent} the event details to be processed
  48766. */
  48767. ActionManager.prototype.processTrigger = function (trigger, evt) {
  48768. for (var index = 0; index < this.actions.length; index++) {
  48769. var action = this.actions[index];
  48770. if (action.trigger === trigger) {
  48771. if (evt) {
  48772. if (trigger === ActionManager.OnKeyUpTrigger
  48773. || trigger === ActionManager.OnKeyDownTrigger) {
  48774. var parameter = action.getTriggerParameter();
  48775. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  48776. if (!parameter.toLowerCase) {
  48777. continue;
  48778. }
  48779. var lowerCase = parameter.toLowerCase();
  48780. if (lowerCase !== evt.sourceEvent.key) {
  48781. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  48782. var actualkey = String.fromCharCode(unicode).toLowerCase();
  48783. if (actualkey !== lowerCase) {
  48784. continue;
  48785. }
  48786. }
  48787. }
  48788. }
  48789. }
  48790. action._executeCurrent(evt);
  48791. }
  48792. }
  48793. };
  48794. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  48795. var properties = propertyPath.split(".");
  48796. for (var index = 0; index < properties.length - 1; index++) {
  48797. target = target[properties[index]];
  48798. }
  48799. return target;
  48800. };
  48801. ActionManager.prototype._getProperty = function (propertyPath) {
  48802. var properties = propertyPath.split(".");
  48803. return properties[properties.length - 1];
  48804. };
  48805. ActionManager.prototype.serialize = function (name) {
  48806. var root = {
  48807. children: new Array(),
  48808. name: name,
  48809. type: 3,
  48810. properties: new Array() // Empty for root but required
  48811. };
  48812. for (var i = 0; i < this.actions.length; i++) {
  48813. var triggerObject = {
  48814. type: 0,
  48815. children: new Array(),
  48816. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  48817. properties: new Array()
  48818. };
  48819. var triggerOptions = this.actions[i].triggerOptions;
  48820. if (triggerOptions && typeof triggerOptions !== "number") {
  48821. if (triggerOptions.parameter instanceof BABYLON.Node) {
  48822. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  48823. }
  48824. else {
  48825. var parameter = {};
  48826. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  48827. if (triggerOptions.parameter.mesh) {
  48828. parameter._meshId = triggerOptions.parameter.mesh.id;
  48829. }
  48830. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  48831. }
  48832. }
  48833. // Serialize child action, recursively
  48834. this.actions[i].serialize(triggerObject);
  48835. // Add serialized trigger
  48836. root.children.push(triggerObject);
  48837. }
  48838. return root;
  48839. };
  48840. ActionManager.Parse = function (parsedActions, object, scene) {
  48841. var actionManager = new ActionManager(scene);
  48842. if (object === null)
  48843. scene.actionManager = actionManager;
  48844. else
  48845. object.actionManager = actionManager;
  48846. // instanciate a new object
  48847. var instanciate = function (name, params) {
  48848. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  48849. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  48850. newInstance.constructor.apply(newInstance, params);
  48851. return newInstance;
  48852. };
  48853. var parseParameter = function (name, value, target, propertyPath) {
  48854. if (propertyPath === null) {
  48855. // String, boolean or float
  48856. var floatValue = parseFloat(value);
  48857. if (value === "true" || value === "false")
  48858. return value === "true";
  48859. else
  48860. return isNaN(floatValue) ? value : floatValue;
  48861. }
  48862. var effectiveTarget = propertyPath.split(".");
  48863. var values = value.split(",");
  48864. // Get effective Target
  48865. for (var i = 0; i < effectiveTarget.length; i++) {
  48866. target = target[effectiveTarget[i]];
  48867. }
  48868. // Return appropriate value with its type
  48869. if (typeof (target) === "boolean")
  48870. return values[0] === "true";
  48871. if (typeof (target) === "string")
  48872. return values[0];
  48873. // Parameters with multiple values such as Vector3 etc.
  48874. var split = new Array();
  48875. for (var i = 0; i < values.length; i++)
  48876. split.push(parseFloat(values[i]));
  48877. if (target instanceof BABYLON.Vector3)
  48878. return BABYLON.Vector3.FromArray(split);
  48879. if (target instanceof BABYLON.Vector4)
  48880. return BABYLON.Vector4.FromArray(split);
  48881. if (target instanceof BABYLON.Color3)
  48882. return BABYLON.Color3.FromArray(split);
  48883. if (target instanceof BABYLON.Color4)
  48884. return BABYLON.Color4.FromArray(split);
  48885. return parseFloat(values[0]);
  48886. };
  48887. // traverse graph per trigger
  48888. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  48889. if (combineArray === void 0) { combineArray = null; }
  48890. if (parsedAction.detached)
  48891. return;
  48892. var parameters = new Array();
  48893. var target = null;
  48894. var propertyPath = null;
  48895. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  48896. // Parameters
  48897. if (parsedAction.type === 2)
  48898. parameters.push(actionManager);
  48899. else
  48900. parameters.push(trigger);
  48901. if (combine) {
  48902. var actions = new Array();
  48903. for (var j = 0; j < parsedAction.combine.length; j++) {
  48904. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  48905. }
  48906. parameters.push(actions);
  48907. }
  48908. else {
  48909. for (var i = 0; i < parsedAction.properties.length; i++) {
  48910. var value = parsedAction.properties[i].value;
  48911. var name = parsedAction.properties[i].name;
  48912. var targetType = parsedAction.properties[i].targetType;
  48913. if (name === "target")
  48914. if (targetType !== null && targetType === "SceneProperties")
  48915. value = target = scene;
  48916. else
  48917. value = target = scene.getNodeByName(value);
  48918. else if (name === "parent")
  48919. value = scene.getNodeByName(value);
  48920. else if (name === "sound")
  48921. value = scene.getSoundByName(value);
  48922. else if (name !== "propertyPath") {
  48923. if (parsedAction.type === 2 && name === "operator")
  48924. value = BABYLON.ValueCondition[value];
  48925. else
  48926. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  48927. }
  48928. else {
  48929. propertyPath = value;
  48930. }
  48931. parameters.push(value);
  48932. }
  48933. }
  48934. if (combineArray === null) {
  48935. parameters.push(condition);
  48936. }
  48937. else {
  48938. parameters.push(null);
  48939. }
  48940. // If interpolate value action
  48941. if (parsedAction.name === "InterpolateValueAction") {
  48942. var param = parameters[parameters.length - 2];
  48943. parameters[parameters.length - 1] = param;
  48944. parameters[parameters.length - 2] = condition;
  48945. }
  48946. // Action or condition(s) and not CombineAction
  48947. var newAction = instanciate(parsedAction.name, parameters);
  48948. if (newAction instanceof BABYLON.Condition && condition !== null) {
  48949. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  48950. if (action)
  48951. action.then(nothing);
  48952. else
  48953. actionManager.registerAction(nothing);
  48954. action = nothing;
  48955. }
  48956. if (combineArray === null) {
  48957. if (newAction instanceof BABYLON.Condition) {
  48958. condition = newAction;
  48959. newAction = action;
  48960. }
  48961. else {
  48962. condition = null;
  48963. if (action)
  48964. action.then(newAction);
  48965. else
  48966. actionManager.registerAction(newAction);
  48967. }
  48968. }
  48969. else {
  48970. combineArray.push(newAction);
  48971. }
  48972. for (var i = 0; i < parsedAction.children.length; i++)
  48973. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  48974. };
  48975. // triggers
  48976. for (var i = 0; i < parsedActions.children.length; i++) {
  48977. var triggerParams;
  48978. var trigger = parsedActions.children[i];
  48979. if (trigger.properties.length > 0) {
  48980. var param = trigger.properties[0].value;
  48981. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  48982. if (value._meshId) {
  48983. value.mesh = scene.getMeshByID(value._meshId);
  48984. }
  48985. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  48986. }
  48987. else
  48988. triggerParams = ActionManager[trigger.name];
  48989. for (var j = 0; j < trigger.children.length; j++) {
  48990. if (!trigger.detached)
  48991. traverse(trigger.children[j], triggerParams, null, null);
  48992. }
  48993. }
  48994. };
  48995. ActionManager.GetTriggerName = function (trigger) {
  48996. switch (trigger) {
  48997. case 0: return "NothingTrigger";
  48998. case 1: return "OnPickTrigger";
  48999. case 2: return "OnLeftPickTrigger";
  49000. case 3: return "OnRightPickTrigger";
  49001. case 4: return "OnCenterPickTrigger";
  49002. case 5: return "OnPickDownTrigger";
  49003. case 6: return "OnPickUpTrigger";
  49004. case 7: return "OnLongPressTrigger";
  49005. case 8: return "OnPointerOverTrigger";
  49006. case 9: return "OnPointerOutTrigger";
  49007. case 10: return "OnEveryFrameTrigger";
  49008. case 11: return "OnIntersectionEnterTrigger";
  49009. case 12: return "OnIntersectionExitTrigger";
  49010. case 13: return "OnKeyDownTrigger";
  49011. case 14: return "OnKeyUpTrigger";
  49012. case 15: return "OnPickOutTrigger";
  49013. default: return "";
  49014. }
  49015. };
  49016. // Statics
  49017. ActionManager._NothingTrigger = 0;
  49018. ActionManager._OnPickTrigger = 1;
  49019. ActionManager._OnLeftPickTrigger = 2;
  49020. ActionManager._OnRightPickTrigger = 3;
  49021. ActionManager._OnCenterPickTrigger = 4;
  49022. ActionManager._OnPickDownTrigger = 5;
  49023. ActionManager._OnDoublePickTrigger = 6;
  49024. ActionManager._OnPickUpTrigger = 7;
  49025. ActionManager._OnLongPressTrigger = 8;
  49026. ActionManager._OnPointerOverTrigger = 9;
  49027. ActionManager._OnPointerOutTrigger = 10;
  49028. ActionManager._OnEveryFrameTrigger = 11;
  49029. ActionManager._OnIntersectionEnterTrigger = 12;
  49030. ActionManager._OnIntersectionExitTrigger = 13;
  49031. ActionManager._OnKeyDownTrigger = 14;
  49032. ActionManager._OnKeyUpTrigger = 15;
  49033. ActionManager._OnPickOutTrigger = 16;
  49034. ActionManager.Triggers = {};
  49035. return ActionManager;
  49036. }());
  49037. BABYLON.ActionManager = ActionManager;
  49038. })(BABYLON || (BABYLON = {}));
  49039. //# sourceMappingURL=babylon.actionManager.js.map
  49040. var BABYLON;
  49041. (function (BABYLON) {
  49042. var InterpolateValueAction = /** @class */ (function (_super) {
  49043. __extends(InterpolateValueAction, _super);
  49044. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  49045. if (duration === void 0) { duration = 1000; }
  49046. var _this = _super.call(this, triggerOptions, condition) || this;
  49047. _this.propertyPath = propertyPath;
  49048. _this.value = value;
  49049. _this.duration = duration;
  49050. _this.stopOtherAnimations = stopOtherAnimations;
  49051. _this.onInterpolationDone = onInterpolationDone;
  49052. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  49053. _this._target = _this._effectiveTarget = target;
  49054. return _this;
  49055. }
  49056. InterpolateValueAction.prototype._prepare = function () {
  49057. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  49058. this._property = this._getProperty(this.propertyPath);
  49059. };
  49060. InterpolateValueAction.prototype.execute = function () {
  49061. var _this = this;
  49062. var scene = this._actionManager.getScene();
  49063. var keys = [
  49064. {
  49065. frame: 0,
  49066. value: this._effectiveTarget[this._property]
  49067. }, {
  49068. frame: 100,
  49069. value: this.value
  49070. }
  49071. ];
  49072. var dataType;
  49073. if (typeof this.value === "number") {
  49074. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  49075. }
  49076. else if (this.value instanceof BABYLON.Color3) {
  49077. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  49078. }
  49079. else if (this.value instanceof BABYLON.Vector3) {
  49080. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  49081. }
  49082. else if (this.value instanceof BABYLON.Matrix) {
  49083. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  49084. }
  49085. else if (this.value instanceof BABYLON.Quaternion) {
  49086. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  49087. }
  49088. else {
  49089. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  49090. return;
  49091. }
  49092. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  49093. animation.setKeys(keys);
  49094. if (this.stopOtherAnimations) {
  49095. scene.stopAnimation(this._effectiveTarget);
  49096. }
  49097. var wrapper = function () {
  49098. _this.onInterpolationDoneObservable.notifyObservers(_this);
  49099. if (_this.onInterpolationDone) {
  49100. _this.onInterpolationDone();
  49101. }
  49102. };
  49103. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  49104. };
  49105. InterpolateValueAction.prototype.serialize = function (parent) {
  49106. return _super.prototype._serialize.call(this, {
  49107. name: "InterpolateValueAction",
  49108. properties: [
  49109. BABYLON.Action._GetTargetProperty(this._target),
  49110. { name: "propertyPath", value: this.propertyPath },
  49111. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  49112. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  49113. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  49114. ]
  49115. }, parent);
  49116. };
  49117. return InterpolateValueAction;
  49118. }(BABYLON.Action));
  49119. BABYLON.InterpolateValueAction = InterpolateValueAction;
  49120. })(BABYLON || (BABYLON = {}));
  49121. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  49122. var BABYLON;
  49123. (function (BABYLON) {
  49124. var SwitchBooleanAction = /** @class */ (function (_super) {
  49125. __extends(SwitchBooleanAction, _super);
  49126. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  49127. var _this = _super.call(this, triggerOptions, condition) || this;
  49128. _this.propertyPath = propertyPath;
  49129. _this._target = _this._effectiveTarget = target;
  49130. return _this;
  49131. }
  49132. SwitchBooleanAction.prototype._prepare = function () {
  49133. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  49134. this._property = this._getProperty(this.propertyPath);
  49135. };
  49136. SwitchBooleanAction.prototype.execute = function () {
  49137. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  49138. };
  49139. SwitchBooleanAction.prototype.serialize = function (parent) {
  49140. return _super.prototype._serialize.call(this, {
  49141. name: "SwitchBooleanAction",
  49142. properties: [
  49143. BABYLON.Action._GetTargetProperty(this._target),
  49144. { name: "propertyPath", value: this.propertyPath }
  49145. ]
  49146. }, parent);
  49147. };
  49148. return SwitchBooleanAction;
  49149. }(BABYLON.Action));
  49150. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  49151. var SetStateAction = /** @class */ (function (_super) {
  49152. __extends(SetStateAction, _super);
  49153. function SetStateAction(triggerOptions, target, value, condition) {
  49154. var _this = _super.call(this, triggerOptions, condition) || this;
  49155. _this.value = value;
  49156. _this._target = target;
  49157. return _this;
  49158. }
  49159. SetStateAction.prototype.execute = function () {
  49160. this._target.state = this.value;
  49161. };
  49162. SetStateAction.prototype.serialize = function (parent) {
  49163. return _super.prototype._serialize.call(this, {
  49164. name: "SetStateAction",
  49165. properties: [
  49166. BABYLON.Action._GetTargetProperty(this._target),
  49167. { name: "value", value: this.value }
  49168. ]
  49169. }, parent);
  49170. };
  49171. return SetStateAction;
  49172. }(BABYLON.Action));
  49173. BABYLON.SetStateAction = SetStateAction;
  49174. var SetValueAction = /** @class */ (function (_super) {
  49175. __extends(SetValueAction, _super);
  49176. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  49177. var _this = _super.call(this, triggerOptions, condition) || this;
  49178. _this.propertyPath = propertyPath;
  49179. _this.value = value;
  49180. _this._target = _this._effectiveTarget = target;
  49181. return _this;
  49182. }
  49183. SetValueAction.prototype._prepare = function () {
  49184. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  49185. this._property = this._getProperty(this.propertyPath);
  49186. };
  49187. SetValueAction.prototype.execute = function () {
  49188. this._effectiveTarget[this._property] = this.value;
  49189. if (this._target.markAsDirty) {
  49190. this._target.markAsDirty(this._property);
  49191. }
  49192. };
  49193. SetValueAction.prototype.serialize = function (parent) {
  49194. return _super.prototype._serialize.call(this, {
  49195. name: "SetValueAction",
  49196. properties: [
  49197. BABYLON.Action._GetTargetProperty(this._target),
  49198. { name: "propertyPath", value: this.propertyPath },
  49199. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  49200. ]
  49201. }, parent);
  49202. };
  49203. return SetValueAction;
  49204. }(BABYLON.Action));
  49205. BABYLON.SetValueAction = SetValueAction;
  49206. var IncrementValueAction = /** @class */ (function (_super) {
  49207. __extends(IncrementValueAction, _super);
  49208. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  49209. var _this = _super.call(this, triggerOptions, condition) || this;
  49210. _this.propertyPath = propertyPath;
  49211. _this.value = value;
  49212. _this._target = _this._effectiveTarget = target;
  49213. return _this;
  49214. }
  49215. IncrementValueAction.prototype._prepare = function () {
  49216. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  49217. this._property = this._getProperty(this.propertyPath);
  49218. if (typeof this._effectiveTarget[this._property] !== "number") {
  49219. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  49220. }
  49221. };
  49222. IncrementValueAction.prototype.execute = function () {
  49223. this._effectiveTarget[this._property] += this.value;
  49224. if (this._target.markAsDirty) {
  49225. this._target.markAsDirty(this._property);
  49226. }
  49227. };
  49228. IncrementValueAction.prototype.serialize = function (parent) {
  49229. return _super.prototype._serialize.call(this, {
  49230. name: "IncrementValueAction",
  49231. properties: [
  49232. BABYLON.Action._GetTargetProperty(this._target),
  49233. { name: "propertyPath", value: this.propertyPath },
  49234. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  49235. ]
  49236. }, parent);
  49237. };
  49238. return IncrementValueAction;
  49239. }(BABYLON.Action));
  49240. BABYLON.IncrementValueAction = IncrementValueAction;
  49241. var PlayAnimationAction = /** @class */ (function (_super) {
  49242. __extends(PlayAnimationAction, _super);
  49243. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  49244. var _this = _super.call(this, triggerOptions, condition) || this;
  49245. _this.from = from;
  49246. _this.to = to;
  49247. _this.loop = loop;
  49248. _this._target = target;
  49249. return _this;
  49250. }
  49251. PlayAnimationAction.prototype._prepare = function () {
  49252. };
  49253. PlayAnimationAction.prototype.execute = function () {
  49254. var scene = this._actionManager.getScene();
  49255. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  49256. };
  49257. PlayAnimationAction.prototype.serialize = function (parent) {
  49258. return _super.prototype._serialize.call(this, {
  49259. name: "PlayAnimationAction",
  49260. properties: [
  49261. BABYLON.Action._GetTargetProperty(this._target),
  49262. { name: "from", value: String(this.from) },
  49263. { name: "to", value: String(this.to) },
  49264. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  49265. ]
  49266. }, parent);
  49267. };
  49268. return PlayAnimationAction;
  49269. }(BABYLON.Action));
  49270. BABYLON.PlayAnimationAction = PlayAnimationAction;
  49271. var StopAnimationAction = /** @class */ (function (_super) {
  49272. __extends(StopAnimationAction, _super);
  49273. function StopAnimationAction(triggerOptions, target, condition) {
  49274. var _this = _super.call(this, triggerOptions, condition) || this;
  49275. _this._target = target;
  49276. return _this;
  49277. }
  49278. StopAnimationAction.prototype._prepare = function () {
  49279. };
  49280. StopAnimationAction.prototype.execute = function () {
  49281. var scene = this._actionManager.getScene();
  49282. scene.stopAnimation(this._target);
  49283. };
  49284. StopAnimationAction.prototype.serialize = function (parent) {
  49285. return _super.prototype._serialize.call(this, {
  49286. name: "StopAnimationAction",
  49287. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  49288. }, parent);
  49289. };
  49290. return StopAnimationAction;
  49291. }(BABYLON.Action));
  49292. BABYLON.StopAnimationAction = StopAnimationAction;
  49293. var DoNothingAction = /** @class */ (function (_super) {
  49294. __extends(DoNothingAction, _super);
  49295. function DoNothingAction(triggerOptions, condition) {
  49296. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  49297. return _super.call(this, triggerOptions, condition) || this;
  49298. }
  49299. DoNothingAction.prototype.execute = function () {
  49300. };
  49301. DoNothingAction.prototype.serialize = function (parent) {
  49302. return _super.prototype._serialize.call(this, {
  49303. name: "DoNothingAction",
  49304. properties: []
  49305. }, parent);
  49306. };
  49307. return DoNothingAction;
  49308. }(BABYLON.Action));
  49309. BABYLON.DoNothingAction = DoNothingAction;
  49310. var CombineAction = /** @class */ (function (_super) {
  49311. __extends(CombineAction, _super);
  49312. function CombineAction(triggerOptions, children, condition) {
  49313. var _this = _super.call(this, triggerOptions, condition) || this;
  49314. _this.children = children;
  49315. return _this;
  49316. }
  49317. CombineAction.prototype._prepare = function () {
  49318. for (var index = 0; index < this.children.length; index++) {
  49319. this.children[index]._actionManager = this._actionManager;
  49320. this.children[index]._prepare();
  49321. }
  49322. };
  49323. CombineAction.prototype.execute = function (evt) {
  49324. for (var index = 0; index < this.children.length; index++) {
  49325. this.children[index].execute(evt);
  49326. }
  49327. };
  49328. CombineAction.prototype.serialize = function (parent) {
  49329. var serializationObject = _super.prototype._serialize.call(this, {
  49330. name: "CombineAction",
  49331. properties: [],
  49332. combine: []
  49333. }, parent);
  49334. for (var i = 0; i < this.children.length; i++) {
  49335. serializationObject.combine.push(this.children[i].serialize(null));
  49336. }
  49337. return serializationObject;
  49338. };
  49339. return CombineAction;
  49340. }(BABYLON.Action));
  49341. BABYLON.CombineAction = CombineAction;
  49342. var ExecuteCodeAction = /** @class */ (function (_super) {
  49343. __extends(ExecuteCodeAction, _super);
  49344. function ExecuteCodeAction(triggerOptions, func, condition) {
  49345. var _this = _super.call(this, triggerOptions, condition) || this;
  49346. _this.func = func;
  49347. return _this;
  49348. }
  49349. ExecuteCodeAction.prototype.execute = function (evt) {
  49350. this.func(evt);
  49351. };
  49352. return ExecuteCodeAction;
  49353. }(BABYLON.Action));
  49354. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  49355. var SetParentAction = /** @class */ (function (_super) {
  49356. __extends(SetParentAction, _super);
  49357. function SetParentAction(triggerOptions, target, parent, condition) {
  49358. var _this = _super.call(this, triggerOptions, condition) || this;
  49359. _this._target = target;
  49360. _this._parent = parent;
  49361. return _this;
  49362. }
  49363. SetParentAction.prototype._prepare = function () {
  49364. };
  49365. SetParentAction.prototype.execute = function () {
  49366. if (this._target.parent === this._parent) {
  49367. return;
  49368. }
  49369. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  49370. invertParentWorldMatrix.invert();
  49371. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  49372. this._target.parent = this._parent;
  49373. };
  49374. SetParentAction.prototype.serialize = function (parent) {
  49375. return _super.prototype._serialize.call(this, {
  49376. name: "SetParentAction",
  49377. properties: [
  49378. BABYLON.Action._GetTargetProperty(this._target),
  49379. BABYLON.Action._GetTargetProperty(this._parent),
  49380. ]
  49381. }, parent);
  49382. };
  49383. return SetParentAction;
  49384. }(BABYLON.Action));
  49385. BABYLON.SetParentAction = SetParentAction;
  49386. var PlaySoundAction = /** @class */ (function (_super) {
  49387. __extends(PlaySoundAction, _super);
  49388. function PlaySoundAction(triggerOptions, sound, condition) {
  49389. var _this = _super.call(this, triggerOptions, condition) || this;
  49390. _this._sound = sound;
  49391. return _this;
  49392. }
  49393. PlaySoundAction.prototype._prepare = function () {
  49394. };
  49395. PlaySoundAction.prototype.execute = function () {
  49396. if (this._sound !== undefined)
  49397. this._sound.play();
  49398. };
  49399. PlaySoundAction.prototype.serialize = function (parent) {
  49400. return _super.prototype._serialize.call(this, {
  49401. name: "PlaySoundAction",
  49402. properties: [{ name: "sound", value: this._sound.name }]
  49403. }, parent);
  49404. };
  49405. return PlaySoundAction;
  49406. }(BABYLON.Action));
  49407. BABYLON.PlaySoundAction = PlaySoundAction;
  49408. var StopSoundAction = /** @class */ (function (_super) {
  49409. __extends(StopSoundAction, _super);
  49410. function StopSoundAction(triggerOptions, sound, condition) {
  49411. var _this = _super.call(this, triggerOptions, condition) || this;
  49412. _this._sound = sound;
  49413. return _this;
  49414. }
  49415. StopSoundAction.prototype._prepare = function () {
  49416. };
  49417. StopSoundAction.prototype.execute = function () {
  49418. if (this._sound !== undefined)
  49419. this._sound.stop();
  49420. };
  49421. StopSoundAction.prototype.serialize = function (parent) {
  49422. return _super.prototype._serialize.call(this, {
  49423. name: "StopSoundAction",
  49424. properties: [{ name: "sound", value: this._sound.name }]
  49425. }, parent);
  49426. };
  49427. return StopSoundAction;
  49428. }(BABYLON.Action));
  49429. BABYLON.StopSoundAction = StopSoundAction;
  49430. })(BABYLON || (BABYLON = {}));
  49431. //# sourceMappingURL=babylon.directActions.js.map
  49432. var BABYLON;
  49433. (function (BABYLON) {
  49434. var SpriteManager = /** @class */ (function () {
  49435. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  49436. if (epsilon === void 0) { epsilon = 0.01; }
  49437. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  49438. this.name = name;
  49439. this.sprites = new Array();
  49440. this.renderingGroupId = 0;
  49441. this.layerMask = 0x0FFFFFFF;
  49442. this.fogEnabled = true;
  49443. this.isPickable = false;
  49444. /**
  49445. * An event triggered when the manager is disposed.
  49446. * @type {BABYLON.Observable}
  49447. */
  49448. this.onDisposeObservable = new BABYLON.Observable();
  49449. this._vertexBuffers = {};
  49450. this._capacity = capacity;
  49451. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  49452. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  49453. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  49454. if (cellSize.width && cellSize.height) {
  49455. this.cellWidth = cellSize.width;
  49456. this.cellHeight = cellSize.height;
  49457. }
  49458. else if (cellSize !== undefined) {
  49459. this.cellWidth = cellSize;
  49460. this.cellHeight = cellSize;
  49461. }
  49462. else {
  49463. return;
  49464. }
  49465. this._epsilon = epsilon;
  49466. this._scene = scene;
  49467. this._scene.spriteManagers.push(this);
  49468. var indices = [];
  49469. var index = 0;
  49470. for (var count = 0; count < capacity; count++) {
  49471. indices.push(index);
  49472. indices.push(index + 1);
  49473. indices.push(index + 2);
  49474. indices.push(index);
  49475. indices.push(index + 2);
  49476. indices.push(index + 3);
  49477. index += 4;
  49478. }
  49479. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  49480. // VBO
  49481. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  49482. this._vertexData = new Float32Array(capacity * 16 * 4);
  49483. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  49484. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  49485. var options = this._buffer.createVertexBuffer("options", 4, 4);
  49486. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  49487. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  49488. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  49489. this._vertexBuffers["options"] = options;
  49490. this._vertexBuffers["cellInfo"] = cellInfo;
  49491. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  49492. // Effects
  49493. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  49494. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  49495. }
  49496. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  49497. set: function (callback) {
  49498. if (this._onDisposeObserver) {
  49499. this.onDisposeObservable.remove(this._onDisposeObserver);
  49500. }
  49501. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  49502. },
  49503. enumerable: true,
  49504. configurable: true
  49505. });
  49506. Object.defineProperty(SpriteManager.prototype, "texture", {
  49507. get: function () {
  49508. return this._spriteTexture;
  49509. },
  49510. set: function (value) {
  49511. this._spriteTexture = value;
  49512. },
  49513. enumerable: true,
  49514. configurable: true
  49515. });
  49516. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  49517. var arrayOffset = index * 16;
  49518. if (offsetX === 0)
  49519. offsetX = this._epsilon;
  49520. else if (offsetX === 1)
  49521. offsetX = 1 - this._epsilon;
  49522. if (offsetY === 0)
  49523. offsetY = this._epsilon;
  49524. else if (offsetY === 1)
  49525. offsetY = 1 - this._epsilon;
  49526. this._vertexData[arrayOffset] = sprite.position.x;
  49527. this._vertexData[arrayOffset + 1] = sprite.position.y;
  49528. this._vertexData[arrayOffset + 2] = sprite.position.z;
  49529. this._vertexData[arrayOffset + 3] = sprite.angle;
  49530. this._vertexData[arrayOffset + 4] = sprite.width;
  49531. this._vertexData[arrayOffset + 5] = sprite.height;
  49532. this._vertexData[arrayOffset + 6] = offsetX;
  49533. this._vertexData[arrayOffset + 7] = offsetY;
  49534. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  49535. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  49536. var offset = (sprite.cellIndex / rowSize) >> 0;
  49537. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  49538. this._vertexData[arrayOffset + 11] = offset;
  49539. // Color
  49540. this._vertexData[arrayOffset + 12] = sprite.color.r;
  49541. this._vertexData[arrayOffset + 13] = sprite.color.g;
  49542. this._vertexData[arrayOffset + 14] = sprite.color.b;
  49543. this._vertexData[arrayOffset + 15] = sprite.color.a;
  49544. };
  49545. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  49546. var count = Math.min(this._capacity, this.sprites.length);
  49547. var min = BABYLON.Vector3.Zero();
  49548. var max = BABYLON.Vector3.Zero();
  49549. var distance = Number.MAX_VALUE;
  49550. var currentSprite = null;
  49551. var cameraSpacePosition = BABYLON.Vector3.Zero();
  49552. var cameraView = camera.getViewMatrix();
  49553. for (var index = 0; index < count; index++) {
  49554. var sprite = this.sprites[index];
  49555. if (!sprite) {
  49556. continue;
  49557. }
  49558. if (predicate) {
  49559. if (!predicate(sprite)) {
  49560. continue;
  49561. }
  49562. }
  49563. else if (!sprite.isPickable) {
  49564. continue;
  49565. }
  49566. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  49567. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  49568. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  49569. if (ray.intersectsBoxMinMax(min, max)) {
  49570. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  49571. if (distance > currentDistance) {
  49572. distance = currentDistance;
  49573. currentSprite = sprite;
  49574. if (fastCheck) {
  49575. break;
  49576. }
  49577. }
  49578. }
  49579. }
  49580. if (currentSprite) {
  49581. var result = new BABYLON.PickingInfo();
  49582. result.hit = true;
  49583. result.pickedSprite = currentSprite;
  49584. result.distance = distance;
  49585. return result;
  49586. }
  49587. return null;
  49588. };
  49589. SpriteManager.prototype.render = function () {
  49590. // Check
  49591. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  49592. return;
  49593. var engine = this._scene.getEngine();
  49594. var baseSize = this._spriteTexture.getBaseSize();
  49595. // Sprites
  49596. var deltaTime = engine.getDeltaTime();
  49597. var max = Math.min(this._capacity, this.sprites.length);
  49598. var rowSize = baseSize.width / this.cellWidth;
  49599. var offset = 0;
  49600. for (var index = 0; index < max; index++) {
  49601. var sprite = this.sprites[index];
  49602. if (!sprite) {
  49603. continue;
  49604. }
  49605. sprite._animate(deltaTime);
  49606. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  49607. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  49608. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  49609. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  49610. }
  49611. this._buffer.update(this._vertexData);
  49612. // Render
  49613. var effect = this._effectBase;
  49614. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  49615. effect = this._effectFog;
  49616. }
  49617. engine.enableEffect(effect);
  49618. var viewMatrix = this._scene.getViewMatrix();
  49619. effect.setTexture("diffuseSampler", this._spriteTexture);
  49620. effect.setMatrix("view", viewMatrix);
  49621. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  49622. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  49623. // Fog
  49624. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  49625. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  49626. effect.setColor3("vFogColor", this._scene.fogColor);
  49627. }
  49628. // VBOs
  49629. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  49630. // Draw order
  49631. engine.setDepthFunctionToLessOrEqual();
  49632. effect.setBool("alphaTest", true);
  49633. engine.setColorWrite(false);
  49634. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  49635. engine.setColorWrite(true);
  49636. effect.setBool("alphaTest", false);
  49637. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  49638. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  49639. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  49640. };
  49641. SpriteManager.prototype.dispose = function () {
  49642. if (this._buffer) {
  49643. this._buffer.dispose();
  49644. this._buffer = null;
  49645. }
  49646. if (this._indexBuffer) {
  49647. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  49648. this._indexBuffer = null;
  49649. }
  49650. if (this._spriteTexture) {
  49651. this._spriteTexture.dispose();
  49652. this._spriteTexture = null;
  49653. }
  49654. // Remove from scene
  49655. var index = this._scene.spriteManagers.indexOf(this);
  49656. this._scene.spriteManagers.splice(index, 1);
  49657. // Callback
  49658. this.onDisposeObservable.notifyObservers(this);
  49659. this.onDisposeObservable.clear();
  49660. };
  49661. return SpriteManager;
  49662. }());
  49663. BABYLON.SpriteManager = SpriteManager;
  49664. })(BABYLON || (BABYLON = {}));
  49665. //# sourceMappingURL=babylon.spriteManager.js.map
  49666. var BABYLON;
  49667. (function (BABYLON) {
  49668. var Sprite = /** @class */ (function () {
  49669. function Sprite(name, manager) {
  49670. this.name = name;
  49671. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  49672. this.width = 1.0;
  49673. this.height = 1.0;
  49674. this.angle = 0;
  49675. this.cellIndex = 0;
  49676. this.invertU = 0;
  49677. this.invertV = 0;
  49678. this.animations = new Array();
  49679. this.isPickable = false;
  49680. this._animationStarted = false;
  49681. this._loopAnimation = false;
  49682. this._fromIndex = 0;
  49683. this._toIndex = 0;
  49684. this._delay = 0;
  49685. this._direction = 1;
  49686. this._time = 0;
  49687. this._manager = manager;
  49688. this._manager.sprites.push(this);
  49689. this.position = BABYLON.Vector3.Zero();
  49690. }
  49691. Object.defineProperty(Sprite.prototype, "size", {
  49692. get: function () {
  49693. return this.width;
  49694. },
  49695. set: function (value) {
  49696. this.width = value;
  49697. this.height = value;
  49698. },
  49699. enumerable: true,
  49700. configurable: true
  49701. });
  49702. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  49703. this._fromIndex = from;
  49704. this._toIndex = to;
  49705. this._loopAnimation = loop;
  49706. this._delay = delay;
  49707. this._animationStarted = true;
  49708. this._direction = from < to ? 1 : -1;
  49709. this.cellIndex = from;
  49710. this._time = 0;
  49711. this._onAnimationEnd = onAnimationEnd;
  49712. };
  49713. Sprite.prototype.stopAnimation = function () {
  49714. this._animationStarted = false;
  49715. };
  49716. Sprite.prototype._animate = function (deltaTime) {
  49717. if (!this._animationStarted)
  49718. return;
  49719. this._time += deltaTime;
  49720. if (this._time > this._delay) {
  49721. this._time = this._time % this._delay;
  49722. this.cellIndex += this._direction;
  49723. if (this.cellIndex > this._toIndex) {
  49724. if (this._loopAnimation) {
  49725. this.cellIndex = this._fromIndex;
  49726. }
  49727. else {
  49728. this.cellIndex = this._toIndex;
  49729. this._animationStarted = false;
  49730. if (this._onAnimationEnd) {
  49731. this._onAnimationEnd();
  49732. }
  49733. if (this.disposeWhenFinishedAnimating) {
  49734. this.dispose();
  49735. }
  49736. }
  49737. }
  49738. }
  49739. };
  49740. Sprite.prototype.dispose = function () {
  49741. for (var i = 0; i < this._manager.sprites.length; i++) {
  49742. if (this._manager.sprites[i] == this) {
  49743. this._manager.sprites.splice(i, 1);
  49744. }
  49745. }
  49746. };
  49747. return Sprite;
  49748. }());
  49749. BABYLON.Sprite = Sprite;
  49750. })(BABYLON || (BABYLON = {}));
  49751. //# sourceMappingURL=babylon.sprite.js.map
  49752. var BABYLON;
  49753. (function (BABYLON) {
  49754. var IntersectionInfo = /** @class */ (function () {
  49755. function IntersectionInfo(bu, bv, distance) {
  49756. this.bu = bu;
  49757. this.bv = bv;
  49758. this.distance = distance;
  49759. this.faceId = 0;
  49760. this.subMeshId = 0;
  49761. }
  49762. return IntersectionInfo;
  49763. }());
  49764. BABYLON.IntersectionInfo = IntersectionInfo;
  49765. var PickingInfo = /** @class */ (function () {
  49766. function PickingInfo() {
  49767. this.hit = false;
  49768. this.distance = 0;
  49769. this.pickedPoint = null;
  49770. this.pickedMesh = null;
  49771. this.bu = 0;
  49772. this.bv = 0;
  49773. this.faceId = -1;
  49774. this.subMeshId = 0;
  49775. this.pickedSprite = null;
  49776. }
  49777. // Methods
  49778. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  49779. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  49780. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  49781. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  49782. return null;
  49783. }
  49784. var indices = this.pickedMesh.getIndices();
  49785. if (!indices) {
  49786. return null;
  49787. }
  49788. var result;
  49789. if (useVerticesNormals) {
  49790. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  49791. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  49792. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  49793. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  49794. normal0 = normal0.scale(this.bu);
  49795. normal1 = normal1.scale(this.bv);
  49796. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  49797. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  49798. }
  49799. else {
  49800. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  49801. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  49802. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  49803. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  49804. var p1p2 = vertex1.subtract(vertex2);
  49805. var p3p2 = vertex3.subtract(vertex2);
  49806. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  49807. }
  49808. if (useWorldCoordinates) {
  49809. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  49810. }
  49811. return BABYLON.Vector3.Normalize(result);
  49812. };
  49813. PickingInfo.prototype.getTextureCoordinates = function () {
  49814. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  49815. return null;
  49816. }
  49817. var indices = this.pickedMesh.getIndices();
  49818. if (!indices) {
  49819. return null;
  49820. }
  49821. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  49822. if (!uvs) {
  49823. return null;
  49824. }
  49825. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  49826. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  49827. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  49828. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  49829. uv1 = uv1.scale(this.bu);
  49830. uv2 = uv2.scale(this.bv);
  49831. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  49832. };
  49833. return PickingInfo;
  49834. }());
  49835. BABYLON.PickingInfo = PickingInfo;
  49836. })(BABYLON || (BABYLON = {}));
  49837. //# sourceMappingURL=babylon.pickingInfo.js.map
  49838. var BABYLON;
  49839. (function (BABYLON) {
  49840. var Ray = /** @class */ (function () {
  49841. function Ray(origin, direction, length) {
  49842. if (length === void 0) { length = Number.MAX_VALUE; }
  49843. this.origin = origin;
  49844. this.direction = direction;
  49845. this.length = length;
  49846. }
  49847. // Methods
  49848. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  49849. var d = 0.0;
  49850. var maxValue = Number.MAX_VALUE;
  49851. var inv;
  49852. var min;
  49853. var max;
  49854. var temp;
  49855. if (Math.abs(this.direction.x) < 0.0000001) {
  49856. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  49857. return false;
  49858. }
  49859. }
  49860. else {
  49861. inv = 1.0 / this.direction.x;
  49862. min = (minimum.x - this.origin.x) * inv;
  49863. max = (maximum.x - this.origin.x) * inv;
  49864. if (max === -Infinity) {
  49865. max = Infinity;
  49866. }
  49867. if (min > max) {
  49868. temp = min;
  49869. min = max;
  49870. max = temp;
  49871. }
  49872. d = Math.max(min, d);
  49873. maxValue = Math.min(max, maxValue);
  49874. if (d > maxValue) {
  49875. return false;
  49876. }
  49877. }
  49878. if (Math.abs(this.direction.y) < 0.0000001) {
  49879. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  49880. return false;
  49881. }
  49882. }
  49883. else {
  49884. inv = 1.0 / this.direction.y;
  49885. min = (minimum.y - this.origin.y) * inv;
  49886. max = (maximum.y - this.origin.y) * inv;
  49887. if (max === -Infinity) {
  49888. max = Infinity;
  49889. }
  49890. if (min > max) {
  49891. temp = min;
  49892. min = max;
  49893. max = temp;
  49894. }
  49895. d = Math.max(min, d);
  49896. maxValue = Math.min(max, maxValue);
  49897. if (d > maxValue) {
  49898. return false;
  49899. }
  49900. }
  49901. if (Math.abs(this.direction.z) < 0.0000001) {
  49902. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  49903. return false;
  49904. }
  49905. }
  49906. else {
  49907. inv = 1.0 / this.direction.z;
  49908. min = (minimum.z - this.origin.z) * inv;
  49909. max = (maximum.z - this.origin.z) * inv;
  49910. if (max === -Infinity) {
  49911. max = Infinity;
  49912. }
  49913. if (min > max) {
  49914. temp = min;
  49915. min = max;
  49916. max = temp;
  49917. }
  49918. d = Math.max(min, d);
  49919. maxValue = Math.min(max, maxValue);
  49920. if (d > maxValue) {
  49921. return false;
  49922. }
  49923. }
  49924. return true;
  49925. };
  49926. Ray.prototype.intersectsBox = function (box) {
  49927. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  49928. };
  49929. Ray.prototype.intersectsSphere = function (sphere) {
  49930. var x = sphere.center.x - this.origin.x;
  49931. var y = sphere.center.y - this.origin.y;
  49932. var z = sphere.center.z - this.origin.z;
  49933. var pyth = (x * x) + (y * y) + (z * z);
  49934. var rr = sphere.radius * sphere.radius;
  49935. if (pyth <= rr) {
  49936. return true;
  49937. }
  49938. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  49939. if (dot < 0.0) {
  49940. return false;
  49941. }
  49942. var temp = pyth - (dot * dot);
  49943. return temp <= rr;
  49944. };
  49945. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  49946. if (!this._edge1) {
  49947. this._edge1 = BABYLON.Vector3.Zero();
  49948. this._edge2 = BABYLON.Vector3.Zero();
  49949. this._pvec = BABYLON.Vector3.Zero();
  49950. this._tvec = BABYLON.Vector3.Zero();
  49951. this._qvec = BABYLON.Vector3.Zero();
  49952. }
  49953. vertex1.subtractToRef(vertex0, this._edge1);
  49954. vertex2.subtractToRef(vertex0, this._edge2);
  49955. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  49956. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  49957. if (det === 0) {
  49958. return null;
  49959. }
  49960. var invdet = 1 / det;
  49961. this.origin.subtractToRef(vertex0, this._tvec);
  49962. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  49963. if (bu < 0 || bu > 1.0) {
  49964. return null;
  49965. }
  49966. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  49967. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  49968. if (bv < 0 || bu + bv > 1.0) {
  49969. return null;
  49970. }
  49971. //check if the distance is longer than the predefined length.
  49972. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  49973. if (distance > this.length) {
  49974. return null;
  49975. }
  49976. return new BABYLON.IntersectionInfo(bu, bv, distance);
  49977. };
  49978. Ray.prototype.intersectsPlane = function (plane) {
  49979. var distance;
  49980. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  49981. if (Math.abs(result1) < 9.99999997475243E-07) {
  49982. return null;
  49983. }
  49984. else {
  49985. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  49986. distance = (-plane.d - result2) / result1;
  49987. if (distance < 0.0) {
  49988. if (distance < -9.99999997475243E-07) {
  49989. return null;
  49990. }
  49991. else {
  49992. return 0;
  49993. }
  49994. }
  49995. return distance;
  49996. }
  49997. };
  49998. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  49999. var tm = BABYLON.Tmp.Matrix[0];
  50000. mesh.getWorldMatrix().invertToRef(tm);
  50001. if (this._tmpRay) {
  50002. Ray.TransformToRef(this, tm, this._tmpRay);
  50003. }
  50004. else {
  50005. this._tmpRay = Ray.Transform(this, tm);
  50006. }
  50007. return mesh.intersects(this._tmpRay, fastCheck);
  50008. };
  50009. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  50010. if (results) {
  50011. results.length = 0;
  50012. }
  50013. else {
  50014. results = [];
  50015. }
  50016. for (var i = 0; i < meshes.length; i++) {
  50017. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  50018. if (pickInfo.hit) {
  50019. results.push(pickInfo);
  50020. }
  50021. }
  50022. results.sort(this._comparePickingInfo);
  50023. return results;
  50024. };
  50025. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  50026. if (pickingInfoA.distance < pickingInfoB.distance) {
  50027. return -1;
  50028. }
  50029. else if (pickingInfoA.distance > pickingInfoB.distance) {
  50030. return 1;
  50031. }
  50032. else {
  50033. return 0;
  50034. }
  50035. };
  50036. /**
  50037. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  50038. * @param sega the first point of the segment to test the intersection against
  50039. * @param segb the second point of the segment to test the intersection against
  50040. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  50041. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  50042. */
  50043. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  50044. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  50045. var u = segb.subtract(sega);
  50046. var v = rsegb.subtract(this.origin);
  50047. var w = sega.subtract(this.origin);
  50048. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  50049. var b = BABYLON.Vector3.Dot(u, v);
  50050. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  50051. var d = BABYLON.Vector3.Dot(u, w);
  50052. var e = BABYLON.Vector3.Dot(v, w);
  50053. var D = a * c - b * b; // always >= 0
  50054. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  50055. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  50056. // compute the line parameters of the two closest points
  50057. if (D < Ray.smallnum) {
  50058. sN = 0.0; // force using point P0 on segment S1
  50059. sD = 1.0; // to prevent possible division by 0.0 later
  50060. tN = e;
  50061. tD = c;
  50062. }
  50063. else {
  50064. sN = (b * e - c * d);
  50065. tN = (a * e - b * d);
  50066. if (sN < 0.0) {
  50067. sN = 0.0;
  50068. tN = e;
  50069. tD = c;
  50070. }
  50071. else if (sN > sD) {
  50072. sN = sD;
  50073. tN = e + b;
  50074. tD = c;
  50075. }
  50076. }
  50077. if (tN < 0.0) {
  50078. tN = 0.0;
  50079. // recompute sc for this edge
  50080. if (-d < 0.0) {
  50081. sN = 0.0;
  50082. }
  50083. else if (-d > a)
  50084. sN = sD;
  50085. else {
  50086. sN = -d;
  50087. sD = a;
  50088. }
  50089. }
  50090. else if (tN > tD) {
  50091. tN = tD;
  50092. // recompute sc for this edge
  50093. if ((-d + b) < 0.0) {
  50094. sN = 0;
  50095. }
  50096. else if ((-d + b) > a) {
  50097. sN = sD;
  50098. }
  50099. else {
  50100. sN = (-d + b);
  50101. sD = a;
  50102. }
  50103. }
  50104. // finally do the division to get sc and tc
  50105. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  50106. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  50107. // get the difference of the two closest points
  50108. var qtc = v.multiplyByFloats(tc, tc, tc);
  50109. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  50110. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  50111. if (isIntersected) {
  50112. return qtc.length();
  50113. }
  50114. return -1;
  50115. };
  50116. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  50117. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  50118. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  50119. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  50120. this.direction.normalize();
  50121. return this;
  50122. };
  50123. // Statics
  50124. Ray.Zero = function () {
  50125. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  50126. };
  50127. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  50128. var result = Ray.Zero();
  50129. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  50130. };
  50131. /**
  50132. * 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
  50133. * transformed to the given world matrix.
  50134. * @param origin The origin point
  50135. * @param end The end point
  50136. * @param world a matrix to transform the ray to. Default is the identity matrix.
  50137. */
  50138. Ray.CreateNewFromTo = function (origin, end, world) {
  50139. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  50140. var direction = end.subtract(origin);
  50141. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  50142. direction.normalize();
  50143. return Ray.Transform(new Ray(origin, direction, length), world);
  50144. };
  50145. Ray.Transform = function (ray, matrix) {
  50146. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  50147. Ray.TransformToRef(ray, matrix, result);
  50148. return result;
  50149. };
  50150. Ray.TransformToRef = function (ray, matrix, result) {
  50151. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  50152. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  50153. result.length = ray.length;
  50154. var dir = result.direction;
  50155. var len = dir.length();
  50156. if (!(len === 0 || len === 1)) {
  50157. var num = 1.0 / len;
  50158. dir.x *= num;
  50159. dir.y *= num;
  50160. dir.z *= num;
  50161. result.length *= len;
  50162. }
  50163. };
  50164. Ray.smallnum = 0.00000001;
  50165. Ray.rayl = 10e8;
  50166. return Ray;
  50167. }());
  50168. BABYLON.Ray = Ray;
  50169. })(BABYLON || (BABYLON = {}));
  50170. //# sourceMappingURL=babylon.ray.js.map
  50171. var BABYLON;
  50172. (function (BABYLON) {
  50173. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  50174. if (boxMin.x > sphereCenter.x + sphereRadius)
  50175. return false;
  50176. if (sphereCenter.x - sphereRadius > boxMax.x)
  50177. return false;
  50178. if (boxMin.y > sphereCenter.y + sphereRadius)
  50179. return false;
  50180. if (sphereCenter.y - sphereRadius > boxMax.y)
  50181. return false;
  50182. if (boxMin.z > sphereCenter.z + sphereRadius)
  50183. return false;
  50184. if (sphereCenter.z - sphereRadius > boxMax.z)
  50185. return false;
  50186. return true;
  50187. };
  50188. var getLowestRoot = (function () {
  50189. var result = { root: 0, found: false };
  50190. return function (a, b, c, maxR) {
  50191. result.root = 0;
  50192. result.found = false;
  50193. var determinant = b * b - 4.0 * a * c;
  50194. if (determinant < 0)
  50195. return result;
  50196. var sqrtD = Math.sqrt(determinant);
  50197. var r1 = (-b - sqrtD) / (2.0 * a);
  50198. var r2 = (-b + sqrtD) / (2.0 * a);
  50199. if (r1 > r2) {
  50200. var temp = r2;
  50201. r2 = r1;
  50202. r1 = temp;
  50203. }
  50204. if (r1 > 0 && r1 < maxR) {
  50205. result.root = r1;
  50206. result.found = true;
  50207. return result;
  50208. }
  50209. if (r2 > 0 && r2 < maxR) {
  50210. result.root = r2;
  50211. result.found = true;
  50212. return result;
  50213. }
  50214. return result;
  50215. };
  50216. })();
  50217. var Collider = /** @class */ (function () {
  50218. function Collider() {
  50219. this._collisionPoint = BABYLON.Vector3.Zero();
  50220. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  50221. this._tempVector = BABYLON.Vector3.Zero();
  50222. this._tempVector2 = BABYLON.Vector3.Zero();
  50223. this._tempVector3 = BABYLON.Vector3.Zero();
  50224. this._tempVector4 = BABYLON.Vector3.Zero();
  50225. this._edge = BABYLON.Vector3.Zero();
  50226. this._baseToVertex = BABYLON.Vector3.Zero();
  50227. this._destinationPoint = BABYLON.Vector3.Zero();
  50228. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  50229. this._displacementVector = BABYLON.Vector3.Zero();
  50230. this._radius = BABYLON.Vector3.One();
  50231. this._retry = 0;
  50232. this._basePointWorld = BABYLON.Vector3.Zero();
  50233. this._velocityWorld = BABYLON.Vector3.Zero();
  50234. this._normalizedVelocity = BABYLON.Vector3.Zero();
  50235. this._collisionMask = -1;
  50236. }
  50237. Object.defineProperty(Collider.prototype, "collisionMask", {
  50238. get: function () {
  50239. return this._collisionMask;
  50240. },
  50241. set: function (mask) {
  50242. this._collisionMask = !isNaN(mask) ? mask : -1;
  50243. },
  50244. enumerable: true,
  50245. configurable: true
  50246. });
  50247. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  50248. /**
  50249. * Gets the plane normal used to compute the sliding response (in local space)
  50250. */
  50251. get: function () {
  50252. return this._slidePlaneNormal;
  50253. },
  50254. enumerable: true,
  50255. configurable: true
  50256. });
  50257. // Methods
  50258. Collider.prototype._initialize = function (source, dir, e) {
  50259. this._velocity = dir;
  50260. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  50261. this._basePoint = source;
  50262. source.multiplyToRef(this._radius, this._basePointWorld);
  50263. dir.multiplyToRef(this._radius, this._velocityWorld);
  50264. this._velocityWorldLength = this._velocityWorld.length();
  50265. this._epsilon = e;
  50266. this.collisionFound = false;
  50267. };
  50268. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  50269. pa.subtractToRef(point, this._tempVector);
  50270. pb.subtractToRef(point, this._tempVector2);
  50271. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  50272. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  50273. if (d < 0)
  50274. return false;
  50275. pc.subtractToRef(point, this._tempVector3);
  50276. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  50277. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  50278. if (d < 0)
  50279. return false;
  50280. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  50281. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  50282. return d >= 0;
  50283. };
  50284. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  50285. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  50286. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  50287. if (distance > this._velocityWorldLength + max + sphereRadius) {
  50288. return false;
  50289. }
  50290. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  50291. return false;
  50292. return true;
  50293. };
  50294. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  50295. var t0;
  50296. var embeddedInPlane = false;
  50297. //defensive programming, actually not needed.
  50298. if (!trianglePlaneArray) {
  50299. trianglePlaneArray = [];
  50300. }
  50301. if (!trianglePlaneArray[faceIndex]) {
  50302. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  50303. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  50304. }
  50305. var trianglePlane = trianglePlaneArray[faceIndex];
  50306. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  50307. return;
  50308. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  50309. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  50310. if (normalDotVelocity == 0) {
  50311. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  50312. return;
  50313. embeddedInPlane = true;
  50314. t0 = 0;
  50315. }
  50316. else {
  50317. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  50318. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  50319. if (t0 > t1) {
  50320. var temp = t1;
  50321. t1 = t0;
  50322. t0 = temp;
  50323. }
  50324. if (t0 > 1.0 || t1 < 0.0)
  50325. return;
  50326. if (t0 < 0)
  50327. t0 = 0;
  50328. if (t0 > 1.0)
  50329. t0 = 1.0;
  50330. }
  50331. this._collisionPoint.copyFromFloats(0, 0, 0);
  50332. var found = false;
  50333. var t = 1.0;
  50334. if (!embeddedInPlane) {
  50335. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  50336. this._velocity.scaleToRef(t0, this._tempVector);
  50337. this._planeIntersectionPoint.addInPlace(this._tempVector);
  50338. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  50339. found = true;
  50340. t = t0;
  50341. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  50342. }
  50343. }
  50344. if (!found) {
  50345. var velocitySquaredLength = this._velocity.lengthSquared();
  50346. var a = velocitySquaredLength;
  50347. this._basePoint.subtractToRef(p1, this._tempVector);
  50348. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  50349. var c = this._tempVector.lengthSquared() - 1.0;
  50350. var lowestRoot = getLowestRoot(a, b, c, t);
  50351. if (lowestRoot.found) {
  50352. t = lowestRoot.root;
  50353. found = true;
  50354. this._collisionPoint.copyFrom(p1);
  50355. }
  50356. this._basePoint.subtractToRef(p2, this._tempVector);
  50357. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  50358. c = this._tempVector.lengthSquared() - 1.0;
  50359. lowestRoot = getLowestRoot(a, b, c, t);
  50360. if (lowestRoot.found) {
  50361. t = lowestRoot.root;
  50362. found = true;
  50363. this._collisionPoint.copyFrom(p2);
  50364. }
  50365. this._basePoint.subtractToRef(p3, this._tempVector);
  50366. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  50367. c = this._tempVector.lengthSquared() - 1.0;
  50368. lowestRoot = getLowestRoot(a, b, c, t);
  50369. if (lowestRoot.found) {
  50370. t = lowestRoot.root;
  50371. found = true;
  50372. this._collisionPoint.copyFrom(p3);
  50373. }
  50374. p2.subtractToRef(p1, this._edge);
  50375. p1.subtractToRef(this._basePoint, this._baseToVertex);
  50376. var edgeSquaredLength = this._edge.lengthSquared();
  50377. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  50378. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  50379. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  50380. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  50381. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  50382. lowestRoot = getLowestRoot(a, b, c, t);
  50383. if (lowestRoot.found) {
  50384. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  50385. if (f >= 0.0 && f <= 1.0) {
  50386. t = lowestRoot.root;
  50387. found = true;
  50388. this._edge.scaleInPlace(f);
  50389. p1.addToRef(this._edge, this._collisionPoint);
  50390. }
  50391. }
  50392. p3.subtractToRef(p2, this._edge);
  50393. p2.subtractToRef(this._basePoint, this._baseToVertex);
  50394. edgeSquaredLength = this._edge.lengthSquared();
  50395. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  50396. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  50397. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  50398. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  50399. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  50400. lowestRoot = getLowestRoot(a, b, c, t);
  50401. if (lowestRoot.found) {
  50402. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  50403. if (f >= 0.0 && f <= 1.0) {
  50404. t = lowestRoot.root;
  50405. found = true;
  50406. this._edge.scaleInPlace(f);
  50407. p2.addToRef(this._edge, this._collisionPoint);
  50408. }
  50409. }
  50410. p1.subtractToRef(p3, this._edge);
  50411. p3.subtractToRef(this._basePoint, this._baseToVertex);
  50412. edgeSquaredLength = this._edge.lengthSquared();
  50413. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  50414. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  50415. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  50416. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  50417. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  50418. lowestRoot = getLowestRoot(a, b, c, t);
  50419. if (lowestRoot.found) {
  50420. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  50421. if (f >= 0.0 && f <= 1.0) {
  50422. t = lowestRoot.root;
  50423. found = true;
  50424. this._edge.scaleInPlace(f);
  50425. p3.addToRef(this._edge, this._collisionPoint);
  50426. }
  50427. }
  50428. }
  50429. if (found) {
  50430. var distToCollision = t * this._velocity.length();
  50431. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  50432. if (!this.intersectionPoint) {
  50433. this.intersectionPoint = this._collisionPoint.clone();
  50434. }
  50435. else {
  50436. this.intersectionPoint.copyFrom(this._collisionPoint);
  50437. }
  50438. this._nearestDistance = distToCollision;
  50439. this.collisionFound = true;
  50440. }
  50441. }
  50442. };
  50443. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  50444. for (var i = indexStart; i < indexEnd; i += 3) {
  50445. var p1 = pts[indices[i] - decal];
  50446. var p2 = pts[indices[i + 1] - decal];
  50447. var p3 = pts[indices[i + 2] - decal];
  50448. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  50449. }
  50450. };
  50451. Collider.prototype._getResponse = function (pos, vel) {
  50452. pos.addToRef(vel, this._destinationPoint);
  50453. vel.scaleInPlace((this._nearestDistance / vel.length()));
  50454. this._basePoint.addToRef(vel, pos);
  50455. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  50456. this._slidePlaneNormal.normalize();
  50457. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  50458. pos.addInPlace(this._displacementVector);
  50459. this.intersectionPoint.addInPlace(this._displacementVector);
  50460. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  50461. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  50462. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  50463. };
  50464. return Collider;
  50465. }());
  50466. BABYLON.Collider = Collider;
  50467. })(BABYLON || (BABYLON = {}));
  50468. //# sourceMappingURL=babylon.collider.js.map
  50469. var BABYLON;
  50470. (function (BABYLON) {
  50471. //WebWorker code will be inserted to this variable.
  50472. BABYLON.CollisionWorker = "";
  50473. var WorkerTaskType;
  50474. (function (WorkerTaskType) {
  50475. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  50476. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  50477. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  50478. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  50479. var WorkerReplyType;
  50480. (function (WorkerReplyType) {
  50481. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  50482. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  50483. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  50484. var CollisionCoordinatorWorker = /** @class */ (function () {
  50485. function CollisionCoordinatorWorker() {
  50486. var _this = this;
  50487. this._scaledPosition = BABYLON.Vector3.Zero();
  50488. this._scaledVelocity = BABYLON.Vector3.Zero();
  50489. this.onMeshUpdated = function (transformNode) {
  50490. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  50491. };
  50492. this.onGeometryUpdated = function (geometry) {
  50493. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  50494. };
  50495. this._afterRender = function () {
  50496. if (!_this._init)
  50497. return;
  50498. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  50499. return;
  50500. }
  50501. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  50502. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  50503. if (_this._runningUpdated > 4) {
  50504. return;
  50505. }
  50506. ++_this._runningUpdated;
  50507. var payload = {
  50508. updatedMeshes: _this._addUpdateMeshesList,
  50509. updatedGeometries: _this._addUpdateGeometriesList,
  50510. removedGeometries: _this._toRemoveGeometryArray,
  50511. removedMeshes: _this._toRemoveMeshesArray
  50512. };
  50513. var message = {
  50514. payload: payload,
  50515. taskType: WorkerTaskType.UPDATE
  50516. };
  50517. var serializable = [];
  50518. for (var id in payload.updatedGeometries) {
  50519. if (payload.updatedGeometries.hasOwnProperty(id)) {
  50520. //prepare transferables
  50521. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  50522. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  50523. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  50524. }
  50525. }
  50526. _this._worker.postMessage(message, serializable);
  50527. _this._addUpdateMeshesList = {};
  50528. _this._addUpdateGeometriesList = {};
  50529. _this._toRemoveGeometryArray = [];
  50530. _this._toRemoveMeshesArray = [];
  50531. };
  50532. this._onMessageFromWorker = function (e) {
  50533. var returnData = e.data;
  50534. if (returnData.error != WorkerReplyType.SUCCESS) {
  50535. //TODO what errors can be returned from the worker?
  50536. BABYLON.Tools.Warn("error returned from worker!");
  50537. return;
  50538. }
  50539. switch (returnData.taskType) {
  50540. case WorkerTaskType.INIT:
  50541. _this._init = true;
  50542. //Update the worked with ALL of the scene's current state
  50543. _this._scene.meshes.forEach(function (mesh) {
  50544. _this.onMeshAdded(mesh);
  50545. });
  50546. _this._scene.getGeometries().forEach(function (geometry) {
  50547. _this.onGeometryAdded(geometry);
  50548. });
  50549. break;
  50550. case WorkerTaskType.UPDATE:
  50551. _this._runningUpdated--;
  50552. break;
  50553. case WorkerTaskType.COLLIDE:
  50554. var returnPayload = returnData.payload;
  50555. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  50556. return;
  50557. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  50558. if (callback) {
  50559. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  50560. if (mesh) {
  50561. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  50562. }
  50563. }
  50564. //cleanup
  50565. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  50566. break;
  50567. }
  50568. };
  50569. this._collisionsCallbackArray = [];
  50570. this._init = false;
  50571. this._runningUpdated = 0;
  50572. this._addUpdateMeshesList = {};
  50573. this._addUpdateGeometriesList = {};
  50574. this._toRemoveGeometryArray = [];
  50575. this._toRemoveMeshesArray = [];
  50576. }
  50577. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  50578. if (!this._init)
  50579. return;
  50580. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  50581. return;
  50582. position.divideToRef(collider._radius, this._scaledPosition);
  50583. displacement.divideToRef(collider._radius, this._scaledVelocity);
  50584. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  50585. var payload = {
  50586. collider: {
  50587. position: this._scaledPosition.asArray(),
  50588. velocity: this._scaledVelocity.asArray(),
  50589. radius: collider._radius.asArray()
  50590. },
  50591. collisionId: collisionIndex,
  50592. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  50593. maximumRetry: maximumRetry
  50594. };
  50595. var message = {
  50596. payload: payload,
  50597. taskType: WorkerTaskType.COLLIDE
  50598. };
  50599. this._worker.postMessage(message);
  50600. };
  50601. CollisionCoordinatorWorker.prototype.init = function (scene) {
  50602. this._scene = scene;
  50603. this._scene.registerAfterRender(this._afterRender);
  50604. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  50605. this._worker = new Worker(workerUrl);
  50606. this._worker.onmessage = this._onMessageFromWorker;
  50607. var message = {
  50608. payload: {},
  50609. taskType: WorkerTaskType.INIT
  50610. };
  50611. this._worker.postMessage(message);
  50612. };
  50613. CollisionCoordinatorWorker.prototype.destroy = function () {
  50614. this._scene.unregisterAfterRender(this._afterRender);
  50615. this._worker.terminate();
  50616. };
  50617. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  50618. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  50619. this.onMeshUpdated(mesh);
  50620. };
  50621. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  50622. this._toRemoveMeshesArray.push(mesh.uniqueId);
  50623. };
  50624. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  50625. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  50626. geometry.onGeometryUpdated = this.onGeometryUpdated;
  50627. this.onGeometryUpdated(geometry);
  50628. };
  50629. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  50630. this._toRemoveGeometryArray.push(geometry.id);
  50631. };
  50632. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  50633. var submeshes = [];
  50634. if (mesh.subMeshes) {
  50635. submeshes = mesh.subMeshes.map(function (sm, idx) {
  50636. var boundingInfo = sm.getBoundingInfo();
  50637. return {
  50638. position: idx,
  50639. verticesStart: sm.verticesStart,
  50640. verticesCount: sm.verticesCount,
  50641. indexStart: sm.indexStart,
  50642. indexCount: sm.indexCount,
  50643. hasMaterial: !!sm.getMaterial(),
  50644. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  50645. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  50646. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  50647. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  50648. };
  50649. });
  50650. }
  50651. var geometryId = null;
  50652. if (mesh instanceof BABYLON.Mesh) {
  50653. var geometry = mesh.geometry;
  50654. geometryId = geometry ? geometry.id : null;
  50655. }
  50656. else if (mesh instanceof BABYLON.InstancedMesh) {
  50657. var geometry = mesh.sourceMesh && mesh.sourceMesh.geometry;
  50658. geometryId = geometry ? geometry.id : null;
  50659. }
  50660. var boundingInfo = mesh.getBoundingInfo();
  50661. return {
  50662. uniqueId: mesh.uniqueId,
  50663. id: mesh.id,
  50664. name: mesh.name,
  50665. geometryId: geometryId,
  50666. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  50667. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  50668. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  50669. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  50670. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  50671. subMeshes: submeshes,
  50672. checkCollisions: mesh.checkCollisions
  50673. };
  50674. };
  50675. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  50676. return {
  50677. id: geometry.id,
  50678. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  50679. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  50680. indices: new Uint32Array(geometry.getIndices() || []),
  50681. };
  50682. };
  50683. return CollisionCoordinatorWorker;
  50684. }());
  50685. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  50686. var CollisionCoordinatorLegacy = /** @class */ (function () {
  50687. function CollisionCoordinatorLegacy() {
  50688. this._scaledPosition = BABYLON.Vector3.Zero();
  50689. this._scaledVelocity = BABYLON.Vector3.Zero();
  50690. this._finalPosition = BABYLON.Vector3.Zero();
  50691. }
  50692. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  50693. position.divideToRef(collider._radius, this._scaledPosition);
  50694. displacement.divideToRef(collider._radius, this._scaledVelocity);
  50695. collider.collidedMesh = null;
  50696. collider._retry = 0;
  50697. collider._initialVelocity = this._scaledVelocity;
  50698. collider._initialPosition = this._scaledPosition;
  50699. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  50700. this._finalPosition.multiplyInPlace(collider._radius);
  50701. //run the callback
  50702. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  50703. };
  50704. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  50705. this._scene = scene;
  50706. };
  50707. CollisionCoordinatorLegacy.prototype.destroy = function () {
  50708. //Legacy need no destruction method.
  50709. };
  50710. //No update in legacy mode
  50711. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  50712. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  50713. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  50714. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  50715. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  50716. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  50717. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  50718. if (excludedMesh === void 0) { excludedMesh = null; }
  50719. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  50720. if (collider._retry >= maximumRetry) {
  50721. finalPosition.copyFrom(position);
  50722. return;
  50723. }
  50724. // Check if this is a mesh else camera or -1
  50725. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  50726. collider._initialize(position, velocity, closeDistance);
  50727. // Check all meshes
  50728. for (var index = 0; index < this._scene.meshes.length; index++) {
  50729. var mesh = this._scene.meshes[index];
  50730. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  50731. mesh._checkCollision(collider);
  50732. }
  50733. }
  50734. if (!collider.collisionFound) {
  50735. position.addToRef(velocity, finalPosition);
  50736. return;
  50737. }
  50738. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  50739. collider._getResponse(position, velocity);
  50740. }
  50741. if (velocity.length() <= closeDistance) {
  50742. finalPosition.copyFrom(position);
  50743. return;
  50744. }
  50745. collider._retry++;
  50746. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  50747. };
  50748. return CollisionCoordinatorLegacy;
  50749. }());
  50750. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  50751. })(BABYLON || (BABYLON = {}));
  50752. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  50753. var BABYLON;
  50754. (function (BABYLON) {
  50755. /**
  50756. * A particle represents one of the element emitted by a particle system.
  50757. * This is mainly define by its coordinates, direction, velocity and age.
  50758. */
  50759. var Particle = /** @class */ (function () {
  50760. /**
  50761. * Creates a new instance of @see Particle
  50762. * @param particleSystem the particle system the particle belongs to
  50763. */
  50764. function Particle(
  50765. /**
  50766. * particleSystem the particle system the particle belongs to.
  50767. */
  50768. particleSystem) {
  50769. this.particleSystem = particleSystem;
  50770. /**
  50771. * The world position of the particle in the scene.
  50772. */
  50773. this.position = BABYLON.Vector3.Zero();
  50774. /**
  50775. * The world direction of the particle in the scene.
  50776. */
  50777. this.direction = BABYLON.Vector3.Zero();
  50778. /**
  50779. * The color of the particle.
  50780. */
  50781. this.color = new BABYLON.Color4(0, 0, 0, 0);
  50782. /**
  50783. * The color change of the particle per step.
  50784. */
  50785. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  50786. /**
  50787. * Defines how long will the life of the particle be.
  50788. */
  50789. this.lifeTime = 1.0;
  50790. /**
  50791. * The current age of the particle.
  50792. */
  50793. this.age = 0;
  50794. /**
  50795. * The current size of the particle.
  50796. */
  50797. this.size = 0;
  50798. /**
  50799. * The current angle of the particle.
  50800. */
  50801. this.angle = 0;
  50802. /**
  50803. * Defines how fast is the angle changing.
  50804. */
  50805. this.angularSpeed = 0;
  50806. /**
  50807. * Defines the cell index used by the particle to be rendered from a sprite.
  50808. */
  50809. this.cellIndex = 0;
  50810. this._currentFrameCounter = 0;
  50811. if (!this.particleSystem.isAnimationSheetEnabled) {
  50812. return;
  50813. }
  50814. this.updateCellInfoFromSystem();
  50815. }
  50816. Particle.prototype.updateCellInfoFromSystem = function () {
  50817. this.cellIndex = this.particleSystem.startSpriteCellID;
  50818. if (this.particleSystem.spriteCellChangeSpeed == 0) {
  50819. this.updateCellIndex = this._updateCellIndexWithSpeedCalculated;
  50820. }
  50821. else {
  50822. this.updateCellIndex = this._updateCellIndexWithCustomSpeed;
  50823. }
  50824. };
  50825. Particle.prototype._updateCellIndexWithSpeedCalculated = function (scaledUpdateSpeed) {
  50826. // (ageOffset / scaledUpdateSpeed) / available cells
  50827. var numberOfScaledUpdatesPerCell = ((this.lifeTime - this.age) / scaledUpdateSpeed) / (this.particleSystem.endSpriteCellID + 1 - this.cellIndex);
  50828. this._currentFrameCounter += scaledUpdateSpeed;
  50829. if (this._currentFrameCounter >= numberOfScaledUpdatesPerCell * scaledUpdateSpeed) {
  50830. this._currentFrameCounter = 0;
  50831. this.cellIndex++;
  50832. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  50833. this.cellIndex = this.particleSystem.endSpriteCellID;
  50834. }
  50835. }
  50836. };
  50837. Particle.prototype._updateCellIndexWithCustomSpeed = function () {
  50838. if (this._currentFrameCounter >= this.particleSystem.spriteCellChangeSpeed) {
  50839. this.cellIndex++;
  50840. this._currentFrameCounter = 0;
  50841. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  50842. if (this.particleSystem.spriteCellLoop) {
  50843. this.cellIndex = this.particleSystem.startSpriteCellID;
  50844. }
  50845. else {
  50846. this.cellIndex = this.particleSystem.endSpriteCellID;
  50847. }
  50848. }
  50849. }
  50850. else {
  50851. this._currentFrameCounter++;
  50852. }
  50853. };
  50854. /**
  50855. * Copy the properties of particle to another one.
  50856. * @param other the particle to copy the information to.
  50857. */
  50858. Particle.prototype.copyTo = function (other) {
  50859. other.position.copyFrom(this.position);
  50860. other.direction.copyFrom(this.direction);
  50861. other.color.copyFrom(this.color);
  50862. other.colorStep.copyFrom(this.colorStep);
  50863. other.lifeTime = this.lifeTime;
  50864. other.age = this.age;
  50865. other.size = this.size;
  50866. other.angle = this.angle;
  50867. other.angularSpeed = this.angularSpeed;
  50868. other.particleSystem = this.particleSystem;
  50869. other.cellIndex = this.cellIndex;
  50870. };
  50871. return Particle;
  50872. }());
  50873. BABYLON.Particle = Particle;
  50874. })(BABYLON || (BABYLON = {}));
  50875. //# sourceMappingURL=babylon.particle.js.map
  50876. var BABYLON;
  50877. (function (BABYLON) {
  50878. /**
  50879. * This represents a particle system in Babylon.
  50880. * 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.
  50881. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  50882. * @example https://doc.babylonjs.com/babylon101/particles
  50883. */
  50884. var ParticleSystem = /** @class */ (function () {
  50885. /**
  50886. * Instantiates a particle system.
  50887. * 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.
  50888. * @param name The name of the particle system
  50889. * @param capacity The max number of particles alive at the same time
  50890. * @param scene The scene the particle system belongs to
  50891. * @param customEffect a custom effect used to change the way particles are rendered by default
  50892. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  50893. * @param epsilon Offset used to render the particles
  50894. */
  50895. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  50896. if (customEffect === void 0) { customEffect = null; }
  50897. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  50898. if (epsilon === void 0) { epsilon = 0.01; }
  50899. var _this = this;
  50900. /**
  50901. * List of animations used by the particle system.
  50902. */
  50903. this.animations = [];
  50904. /**
  50905. * The rendering group used by the Particle system to chose when to render.
  50906. */
  50907. this.renderingGroupId = 0;
  50908. /**
  50909. * The emitter represents the Mesh or position we are attaching the particle system to.
  50910. */
  50911. this.emitter = null;
  50912. /**
  50913. * The maximum number of particles to emit per frame
  50914. */
  50915. this.emitRate = 10;
  50916. /**
  50917. * If you want to launch only a few particles at once, that can be done, as well.
  50918. */
  50919. this.manualEmitCount = -1;
  50920. /**
  50921. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  50922. */
  50923. this.updateSpeed = 0.01;
  50924. /**
  50925. * The amount of time the particle system is running (depends of the overall update speed).
  50926. */
  50927. this.targetStopDuration = 0;
  50928. /**
  50929. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  50930. */
  50931. this.disposeOnStop = false;
  50932. /**
  50933. * Minimum power of emitting particles.
  50934. */
  50935. this.minEmitPower = 1;
  50936. /**
  50937. * Maximum power of emitting particles.
  50938. */
  50939. this.maxEmitPower = 1;
  50940. /**
  50941. * Minimum life time of emitting particles.
  50942. */
  50943. this.minLifeTime = 1;
  50944. /**
  50945. * Maximum life time of emitting particles.
  50946. */
  50947. this.maxLifeTime = 1;
  50948. /**
  50949. * Minimum Size of emitting particles.
  50950. */
  50951. this.minSize = 1;
  50952. /**
  50953. * Maximum Size of emitting particles.
  50954. */
  50955. this.maxSize = 1;
  50956. /**
  50957. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  50958. */
  50959. this.minAngularSpeed = 0;
  50960. /**
  50961. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  50962. */
  50963. this.maxAngularSpeed = 0;
  50964. /**
  50965. * The layer mask we are rendering the particles through.
  50966. */
  50967. this.layerMask = 0x0FFFFFFF;
  50968. /**
  50969. * This can help using your own shader to render the particle system.
  50970. * The according effect will be created
  50971. */
  50972. this.customShader = null;
  50973. /**
  50974. * By default particle system starts as soon as they are created. This prevents the
  50975. * automatic start to happen and let you decide when to start emitting particles.
  50976. */
  50977. this.preventAutoStart = false;
  50978. /**
  50979. * Callback triggered when the particle animation is ending.
  50980. */
  50981. this.onAnimationEnd = null;
  50982. /**
  50983. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  50984. */
  50985. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  50986. /**
  50987. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  50988. * to override the particles.
  50989. */
  50990. this.forceDepthWrite = false;
  50991. /**
  50992. * You can use gravity if you want to give an orientation to your particles.
  50993. */
  50994. this.gravity = BABYLON.Vector3.Zero();
  50995. /**
  50996. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  50997. */
  50998. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  50999. /**
  51000. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  51001. */
  51002. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  51003. /**
  51004. * Color the particle will have at the end of its lifetime.
  51005. */
  51006. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  51007. /**
  51008. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel.
  51009. */
  51010. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  51011. /**
  51012. * If using a spritesheet (isAnimationSheetEnabled), defines if the sprite animation should loop between startSpriteCellID and endSpriteCellID or not.
  51013. */
  51014. this.spriteCellLoop = true;
  51015. /**
  51016. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the speed of the sprite loop.
  51017. */
  51018. this.spriteCellChangeSpeed = 0;
  51019. /**
  51020. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the first sprite cell to display.
  51021. */
  51022. this.startSpriteCellID = 0;
  51023. /**
  51024. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the last sprite cell to display.
  51025. */
  51026. this.endSpriteCellID = 0;
  51027. /**
  51028. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use.
  51029. */
  51030. this.spriteCellWidth = 0;
  51031. /**
  51032. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use.
  51033. */
  51034. this.spriteCellHeight = 0;
  51035. /**
  51036. * An event triggered when the system is disposed.
  51037. */
  51038. this.onDisposeObservable = new BABYLON.Observable();
  51039. this._particles = new Array();
  51040. this._stockParticles = new Array();
  51041. this._newPartsExcess = 0;
  51042. this._vertexBuffers = {};
  51043. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  51044. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  51045. this._scaledDirection = BABYLON.Vector3.Zero();
  51046. this._scaledGravity = BABYLON.Vector3.Zero();
  51047. this._currentRenderId = -1;
  51048. this._started = false;
  51049. this._stopped = false;
  51050. this._actualFrame = 0;
  51051. this._vertexBufferSize = 11;
  51052. // start of sub system methods
  51053. /**
  51054. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  51055. * Its lifetime will start back at 0.
  51056. */
  51057. this.recycleParticle = function (particle) {
  51058. var lastParticle = _this._particles.pop();
  51059. if (lastParticle !== particle) {
  51060. lastParticle.copyTo(particle);
  51061. }
  51062. _this._stockParticles.push(lastParticle);
  51063. };
  51064. this._createParticle = function () {
  51065. var particle;
  51066. if (_this._stockParticles.length !== 0) {
  51067. particle = _this._stockParticles.pop();
  51068. particle.age = 0;
  51069. particle.cellIndex = _this.startSpriteCellID;
  51070. }
  51071. else {
  51072. particle = new BABYLON.Particle(_this);
  51073. }
  51074. return particle;
  51075. };
  51076. this._emitFromParticle = function (particle) {
  51077. if (!_this.subEmitters || _this.subEmitters.length === 0) {
  51078. return;
  51079. }
  51080. var templateIndex = Math.floor(Math.random() * _this.subEmitters.length);
  51081. var subSystem = _this.subEmitters[templateIndex].clone(_this.name + "_sub", particle.position.clone());
  51082. subSystem._rootParticleSystem = _this;
  51083. _this.activeSubSystems.push(subSystem);
  51084. subSystem.start();
  51085. };
  51086. this._appendParticleVertexes = null;
  51087. this.id = name;
  51088. this.name = name;
  51089. this._capacity = capacity;
  51090. this._epsilon = epsilon;
  51091. this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  51092. if (isAnimationSheetEnabled) {
  51093. this._vertexBufferSize = 12;
  51094. }
  51095. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  51096. this._customEffect = customEffect;
  51097. scene.particleSystems.push(this);
  51098. this._createIndexBuffer();
  51099. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  51100. this._vertexData = new Float32Array(capacity * this._vertexBufferSize * 4);
  51101. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, this._vertexBufferSize);
  51102. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  51103. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  51104. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  51105. if (this._isAnimationSheetEnabled) {
  51106. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", 11, 1);
  51107. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  51108. }
  51109. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  51110. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  51111. this._vertexBuffers["options"] = options;
  51112. // Default emitter type
  51113. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  51114. this.updateFunction = function (particles) {
  51115. for (var index = 0; index < particles.length; index++) {
  51116. var particle = particles[index];
  51117. particle.age += _this._scaledUpdateSpeed;
  51118. if (particle.age >= particle.lifeTime) {
  51119. _this._emitFromParticle(particle);
  51120. _this.recycleParticle(particle);
  51121. index--;
  51122. continue;
  51123. }
  51124. else {
  51125. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  51126. particle.color.addInPlace(_this._scaledColorStep);
  51127. if (particle.color.a < 0)
  51128. particle.color.a = 0;
  51129. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  51130. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  51131. particle.position.addInPlace(_this._scaledDirection);
  51132. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  51133. particle.direction.addInPlace(_this._scaledGravity);
  51134. if (_this._isAnimationSheetEnabled) {
  51135. particle.updateCellIndex(_this._scaledUpdateSpeed);
  51136. }
  51137. }
  51138. }
  51139. };
  51140. }
  51141. Object.defineProperty(ParticleSystem.prototype, "direction1", {
  51142. /**
  51143. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  51144. * This only works when particleEmitterTyps is a BoxParticleEmitter
  51145. */
  51146. get: function () {
  51147. if (this.particleEmitterType.direction1) {
  51148. return this.particleEmitterType.direction1;
  51149. }
  51150. return BABYLON.Vector3.Zero();
  51151. },
  51152. set: function (value) {
  51153. if (this.particleEmitterType.direction1) {
  51154. this.particleEmitterType.direction1 = value;
  51155. }
  51156. },
  51157. enumerable: true,
  51158. configurable: true
  51159. });
  51160. Object.defineProperty(ParticleSystem.prototype, "direction2", {
  51161. /**
  51162. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  51163. * This only works when particleEmitterTyps is a BoxParticleEmitter
  51164. */
  51165. get: function () {
  51166. if (this.particleEmitterType.direction2) {
  51167. return this.particleEmitterType.direction2;
  51168. }
  51169. return BABYLON.Vector3.Zero();
  51170. },
  51171. set: function (value) {
  51172. if (this.particleEmitterType.direction2) {
  51173. this.particleEmitterType.direction2 = value;
  51174. }
  51175. },
  51176. enumerable: true,
  51177. configurable: true
  51178. });
  51179. Object.defineProperty(ParticleSystem.prototype, "minEmitBox", {
  51180. /**
  51181. * 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.
  51182. * This only works when particleEmitterTyps is a BoxParticleEmitter
  51183. */
  51184. get: function () {
  51185. if (this.particleEmitterType.minEmitBox) {
  51186. return this.particleEmitterType.minEmitBox;
  51187. }
  51188. return BABYLON.Vector3.Zero();
  51189. },
  51190. set: function (value) {
  51191. if (this.particleEmitterType.minEmitBox) {
  51192. this.particleEmitterType.minEmitBox = value;
  51193. }
  51194. },
  51195. enumerable: true,
  51196. configurable: true
  51197. });
  51198. Object.defineProperty(ParticleSystem.prototype, "maxEmitBox", {
  51199. /**
  51200. * 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.
  51201. * This only works when particleEmitterTyps is a BoxParticleEmitter
  51202. */
  51203. get: function () {
  51204. if (this.particleEmitterType.maxEmitBox) {
  51205. return this.particleEmitterType.maxEmitBox;
  51206. }
  51207. return BABYLON.Vector3.Zero();
  51208. },
  51209. set: function (value) {
  51210. if (this.particleEmitterType.maxEmitBox) {
  51211. this.particleEmitterType.maxEmitBox = value;
  51212. }
  51213. },
  51214. enumerable: true,
  51215. configurable: true
  51216. });
  51217. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  51218. /**
  51219. * Sets a callback that will be triggered when the system is disposed.
  51220. */
  51221. set: function (callback) {
  51222. if (this._onDisposeObserver) {
  51223. this.onDisposeObservable.remove(this._onDisposeObserver);
  51224. }
  51225. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  51226. },
  51227. enumerable: true,
  51228. configurable: true
  51229. });
  51230. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  51231. /**
  51232. * Gets wether an animation sprite sheet is enabled or not on the particle system.
  51233. */
  51234. get: function () {
  51235. return this._isAnimationSheetEnabled;
  51236. },
  51237. enumerable: true,
  51238. configurable: true
  51239. });
  51240. Object.defineProperty(ParticleSystem.prototype, "particles", {
  51241. //end of Sub-emitter
  51242. /**
  51243. * Gets the current list of active particles
  51244. */
  51245. get: function () {
  51246. return this._particles;
  51247. },
  51248. enumerable: true,
  51249. configurable: true
  51250. });
  51251. /**
  51252. * Returns the string "ParticleSystem"
  51253. * @returns a string containing the class name
  51254. */
  51255. ParticleSystem.prototype.getClassName = function () {
  51256. return "ParticleSystem";
  51257. };
  51258. ParticleSystem.prototype._createIndexBuffer = function () {
  51259. var indices = [];
  51260. var index = 0;
  51261. for (var count = 0; count < this._capacity; count++) {
  51262. indices.push(index);
  51263. indices.push(index + 1);
  51264. indices.push(index + 2);
  51265. indices.push(index);
  51266. indices.push(index + 2);
  51267. indices.push(index + 3);
  51268. index += 4;
  51269. }
  51270. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  51271. };
  51272. /**
  51273. * Gets the maximum number of particles active at the same time.
  51274. * @returns The max number of active particles.
  51275. */
  51276. ParticleSystem.prototype.getCapacity = function () {
  51277. return this._capacity;
  51278. };
  51279. /**
  51280. * Gets Wether there are still active particles in the system.
  51281. * @returns True if it is alive, otherwise false.
  51282. */
  51283. ParticleSystem.prototype.isAlive = function () {
  51284. return this._alive;
  51285. };
  51286. /**
  51287. * Gets Wether the system has been started.
  51288. * @returns True if it has been started, otherwise false.
  51289. */
  51290. ParticleSystem.prototype.isStarted = function () {
  51291. return this._started;
  51292. };
  51293. /**
  51294. * Starts the particle system and begins to emit.
  51295. */
  51296. ParticleSystem.prototype.start = function () {
  51297. this._started = true;
  51298. this._stopped = false;
  51299. this._actualFrame = 0;
  51300. if (this.subEmitters && this.subEmitters.length != 0) {
  51301. this.activeSubSystems = new Array();
  51302. }
  51303. };
  51304. /**
  51305. * Stops the particle system.
  51306. * @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.
  51307. */
  51308. ParticleSystem.prototype.stop = function (stopSubEmitters) {
  51309. if (stopSubEmitters === void 0) { stopSubEmitters = true; }
  51310. this._stopped = true;
  51311. if (stopSubEmitters) {
  51312. this._stopSubEmitters();
  51313. }
  51314. };
  51315. // animation sheet
  51316. /**
  51317. * Remove all active particles
  51318. */
  51319. ParticleSystem.prototype.reset = function () {
  51320. this._stockParticles = [];
  51321. this._particles = [];
  51322. };
  51323. /**
  51324. * @ignore (for internal use only)
  51325. */
  51326. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  51327. var offset = index * this._vertexBufferSize;
  51328. this._vertexData[offset] = particle.position.x;
  51329. this._vertexData[offset + 1] = particle.position.y;
  51330. this._vertexData[offset + 2] = particle.position.z;
  51331. this._vertexData[offset + 3] = particle.color.r;
  51332. this._vertexData[offset + 4] = particle.color.g;
  51333. this._vertexData[offset + 5] = particle.color.b;
  51334. this._vertexData[offset + 6] = particle.color.a;
  51335. this._vertexData[offset + 7] = particle.angle;
  51336. this._vertexData[offset + 8] = particle.size;
  51337. this._vertexData[offset + 9] = offsetX;
  51338. this._vertexData[offset + 10] = offsetY;
  51339. };
  51340. /**
  51341. * @ignore (for internal use only)
  51342. */
  51343. ParticleSystem.prototype._appendParticleVertexWithAnimation = function (index, particle, offsetX, offsetY) {
  51344. if (offsetX === 0)
  51345. offsetX = this._epsilon;
  51346. else if (offsetX === 1)
  51347. offsetX = 1 - this._epsilon;
  51348. if (offsetY === 0)
  51349. offsetY = this._epsilon;
  51350. else if (offsetY === 1)
  51351. offsetY = 1 - this._epsilon;
  51352. var offset = index * this._vertexBufferSize;
  51353. this._vertexData[offset] = particle.position.x;
  51354. this._vertexData[offset + 1] = particle.position.y;
  51355. this._vertexData[offset + 2] = particle.position.z;
  51356. this._vertexData[offset + 3] = particle.color.r;
  51357. this._vertexData[offset + 4] = particle.color.g;
  51358. this._vertexData[offset + 5] = particle.color.b;
  51359. this._vertexData[offset + 6] = particle.color.a;
  51360. this._vertexData[offset + 7] = particle.angle;
  51361. this._vertexData[offset + 8] = particle.size;
  51362. this._vertexData[offset + 9] = offsetX;
  51363. this._vertexData[offset + 10] = offsetY;
  51364. this._vertexData[offset + 11] = particle.cellIndex;
  51365. };
  51366. ParticleSystem.prototype._stopSubEmitters = function () {
  51367. if (!this.activeSubSystems) {
  51368. return;
  51369. }
  51370. this.activeSubSystems.forEach(function (subSystem) {
  51371. subSystem.stop(true);
  51372. });
  51373. this.activeSubSystems = new Array();
  51374. };
  51375. ParticleSystem.prototype._removeFromRoot = function () {
  51376. if (!this._rootParticleSystem) {
  51377. return;
  51378. }
  51379. var index = this._rootParticleSystem.activeSubSystems.indexOf(this);
  51380. if (index !== -1) {
  51381. this._rootParticleSystem.activeSubSystems.splice(index, 1);
  51382. }
  51383. };
  51384. // end of sub system methods
  51385. ParticleSystem.prototype._update = function (newParticles) {
  51386. // Update current
  51387. this._alive = this._particles.length > 0;
  51388. this.updateFunction(this._particles);
  51389. // Add new ones
  51390. var worldMatrix;
  51391. if (this.emitter.position) {
  51392. var emitterMesh = this.emitter;
  51393. worldMatrix = emitterMesh.getWorldMatrix();
  51394. }
  51395. else {
  51396. var emitterPosition = this.emitter;
  51397. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  51398. }
  51399. var particle;
  51400. for (var index = 0; index < newParticles; index++) {
  51401. if (this._particles.length === this._capacity) {
  51402. break;
  51403. }
  51404. particle = this._createParticle();
  51405. this._particles.push(particle);
  51406. var emitPower = BABYLON.Scalar.RandomRange(this.minEmitPower, this.maxEmitPower);
  51407. if (this.startPositionFunction) {
  51408. this.startPositionFunction(worldMatrix, particle.position, particle);
  51409. }
  51410. else {
  51411. this.particleEmitterType.startPositionFunction(worldMatrix, particle.position, particle);
  51412. }
  51413. if (this.startDirectionFunction) {
  51414. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  51415. }
  51416. else {
  51417. this.particleEmitterType.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  51418. }
  51419. particle.lifeTime = BABYLON.Scalar.RandomRange(this.minLifeTime, this.maxLifeTime);
  51420. particle.size = BABYLON.Scalar.RandomRange(this.minSize, this.maxSize);
  51421. particle.angularSpeed = BABYLON.Scalar.RandomRange(this.minAngularSpeed, this.maxAngularSpeed);
  51422. var step = BABYLON.Scalar.RandomRange(0, 1.0);
  51423. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  51424. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  51425. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  51426. }
  51427. };
  51428. ParticleSystem.prototype._getEffect = function () {
  51429. if (this._customEffect) {
  51430. return this._customEffect;
  51431. }
  51432. ;
  51433. var defines = [];
  51434. if (this._scene.clipPlane) {
  51435. defines.push("#define CLIPPLANE");
  51436. }
  51437. if (this._isAnimationSheetEnabled) {
  51438. defines.push("#define ANIMATESHEET");
  51439. }
  51440. // Effect
  51441. var join = defines.join("\n");
  51442. if (this._cachedDefines !== join) {
  51443. this._cachedDefines = join;
  51444. var attributesNamesOrOptions;
  51445. var effectCreationOption;
  51446. if (this._isAnimationSheetEnabled) {
  51447. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options", "cellIndex"];
  51448. effectCreationOption = ["invView", "view", "projection", "particlesInfos", "vClipPlane", "textureMask"];
  51449. }
  51450. else {
  51451. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"];
  51452. effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask"];
  51453. }
  51454. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  51455. }
  51456. return this._effect;
  51457. };
  51458. /**
  51459. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  51460. */
  51461. ParticleSystem.prototype.animate = function () {
  51462. if (!this._started)
  51463. return;
  51464. var effect = this._getEffect();
  51465. // Check
  51466. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  51467. return;
  51468. if (this._currentRenderId === this._scene.getRenderId()) {
  51469. return;
  51470. }
  51471. this._currentRenderId = this._scene.getRenderId();
  51472. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  51473. // determine the number of particles we need to create
  51474. var newParticles;
  51475. if (this.manualEmitCount > -1) {
  51476. newParticles = this.manualEmitCount;
  51477. this._newPartsExcess = 0;
  51478. this.manualEmitCount = 0;
  51479. }
  51480. else {
  51481. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  51482. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  51483. }
  51484. if (this._newPartsExcess > 1.0) {
  51485. newParticles += this._newPartsExcess >> 0;
  51486. this._newPartsExcess -= this._newPartsExcess >> 0;
  51487. }
  51488. this._alive = false;
  51489. if (!this._stopped) {
  51490. this._actualFrame += this._scaledUpdateSpeed;
  51491. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  51492. this.stop();
  51493. }
  51494. else {
  51495. newParticles = 0;
  51496. }
  51497. this._update(newParticles);
  51498. // Stopped?
  51499. if (this._stopped) {
  51500. if (!this._alive) {
  51501. this._started = false;
  51502. if (this.onAnimationEnd) {
  51503. this.onAnimationEnd();
  51504. }
  51505. if (this.disposeOnStop) {
  51506. this._scene._toBeDisposed.push(this);
  51507. }
  51508. }
  51509. }
  51510. // Animation sheet
  51511. if (this._isAnimationSheetEnabled) {
  51512. this._appendParticleVertexes = this._appenedParticleVertexesWithSheet;
  51513. }
  51514. else {
  51515. this._appendParticleVertexes = this._appenedParticleVertexesNoSheet;
  51516. }
  51517. // Update VBO
  51518. var offset = 0;
  51519. for (var index = 0; index < this._particles.length; index++) {
  51520. var particle = this._particles[index];
  51521. this._appendParticleVertexes(offset, particle);
  51522. offset += 4;
  51523. }
  51524. if (this._vertexBuffer) {
  51525. this._vertexBuffer.update(this._vertexData);
  51526. }
  51527. if (this.manualEmitCount === 0 && this.disposeOnStop) {
  51528. this.stop();
  51529. }
  51530. };
  51531. ParticleSystem.prototype._appenedParticleVertexesWithSheet = function (offset, particle) {
  51532. this._appendParticleVertexWithAnimation(offset++, particle, 0, 0);
  51533. this._appendParticleVertexWithAnimation(offset++, particle, 1, 0);
  51534. this._appendParticleVertexWithAnimation(offset++, particle, 1, 1);
  51535. this._appendParticleVertexWithAnimation(offset++, particle, 0, 1);
  51536. };
  51537. ParticleSystem.prototype._appenedParticleVertexesNoSheet = function (offset, particle) {
  51538. this._appendParticleVertex(offset++, particle, 0, 0);
  51539. this._appendParticleVertex(offset++, particle, 1, 0);
  51540. this._appendParticleVertex(offset++, particle, 1, 1);
  51541. this._appendParticleVertex(offset++, particle, 0, 1);
  51542. };
  51543. /**
  51544. * Rebuilds the particle system.
  51545. */
  51546. ParticleSystem.prototype.rebuild = function () {
  51547. this._createIndexBuffer();
  51548. if (this._vertexBuffer) {
  51549. this._vertexBuffer._rebuild();
  51550. }
  51551. };
  51552. /**
  51553. * Is this system ready to be used/rendered
  51554. * @return true if the system is ready
  51555. */
  51556. ParticleSystem.prototype.isReady = function () {
  51557. var effect = this._getEffect();
  51558. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  51559. return false;
  51560. }
  51561. return true;
  51562. };
  51563. /**
  51564. * Renders the particle system in its current state.
  51565. * @returns the current number of particles
  51566. */
  51567. ParticleSystem.prototype.render = function () {
  51568. var effect = this._getEffect();
  51569. // Check
  51570. if (!this.isReady() || !this._particles.length) {
  51571. return 0;
  51572. }
  51573. var engine = this._scene.getEngine();
  51574. // Render
  51575. engine.enableEffect(effect);
  51576. engine.setState(false);
  51577. var viewMatrix = this._scene.getViewMatrix();
  51578. effect.setTexture("diffuseSampler", this.particleTexture);
  51579. effect.setMatrix("view", viewMatrix);
  51580. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  51581. if (this._isAnimationSheetEnabled && this.particleTexture) {
  51582. var baseSize = this.particleTexture.getBaseSize();
  51583. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  51584. }
  51585. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  51586. if (this._scene.clipPlane) {
  51587. var clipPlane = this._scene.clipPlane;
  51588. var invView = viewMatrix.clone();
  51589. invView.invert();
  51590. effect.setMatrix("invView", invView);
  51591. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  51592. }
  51593. // VBOs
  51594. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  51595. // Draw order
  51596. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  51597. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  51598. }
  51599. else {
  51600. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  51601. }
  51602. if (this.forceDepthWrite) {
  51603. engine.setDepthWrite(true);
  51604. }
  51605. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  51606. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  51607. return this._particles.length;
  51608. };
  51609. /**
  51610. * Disposes the particle system and free the associated resources
  51611. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  51612. */
  51613. ParticleSystem.prototype.dispose = function (disposeTexture) {
  51614. if (disposeTexture === void 0) { disposeTexture = true; }
  51615. if (this._vertexBuffer) {
  51616. this._vertexBuffer.dispose();
  51617. this._vertexBuffer = null;
  51618. }
  51619. if (this._indexBuffer) {
  51620. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  51621. this._indexBuffer = null;
  51622. }
  51623. if (disposeTexture && this.particleTexture) {
  51624. this.particleTexture.dispose();
  51625. this.particleTexture = null;
  51626. }
  51627. this._removeFromRoot();
  51628. // Remove from scene
  51629. var index = this._scene.particleSystems.indexOf(this);
  51630. if (index > -1) {
  51631. this._scene.particleSystems.splice(index, 1);
  51632. }
  51633. // Callback
  51634. this.onDisposeObservable.notifyObservers(this);
  51635. this.onDisposeObservable.clear();
  51636. };
  51637. /**
  51638. * Creates a Sphere Emitter for the particle system. (emits along the sphere radius)
  51639. * @param radius The radius of the sphere to emit from
  51640. * @returns the emitter
  51641. */
  51642. ParticleSystem.prototype.createSphereEmitter = function (radius) {
  51643. if (radius === void 0) { radius = 1; }
  51644. var particleEmitter = new BABYLON.SphereParticleEmitter(radius);
  51645. this.particleEmitterType = particleEmitter;
  51646. return particleEmitter;
  51647. };
  51648. /**
  51649. * Creates a Directed Sphere Emitter for the particle system. (emits between direction1 and direction2)
  51650. * @param radius The radius of the sphere to emit from
  51651. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  51652. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  51653. * @returns the emitter
  51654. */
  51655. ParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  51656. if (radius === void 0) { radius = 1; }
  51657. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  51658. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  51659. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  51660. this.particleEmitterType = particleEmitter;
  51661. return particleEmitter;
  51662. };
  51663. /**
  51664. * Creates a Cone Emitter for the particle system. (emits from the cone to the particle position)
  51665. * @param radius The radius of the cone to emit from
  51666. * @param angle The base angle of the cone
  51667. * @returns the emitter
  51668. */
  51669. ParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  51670. if (radius === void 0) { radius = 1; }
  51671. if (angle === void 0) { angle = Math.PI / 4; }
  51672. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  51673. this.particleEmitterType = particleEmitter;
  51674. return particleEmitter;
  51675. };
  51676. // 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.
  51677. /**
  51678. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  51679. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  51680. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  51681. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  51682. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  51683. * @returns the emitter
  51684. */
  51685. ParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  51686. var particleEmitter = new BABYLON.BoxParticleEmitter();
  51687. this.direction1 = direction1;
  51688. this.direction2 = direction2;
  51689. this.minEmitBox = minEmitBox;
  51690. this.maxEmitBox = maxEmitBox;
  51691. this.particleEmitterType = particleEmitter;
  51692. return particleEmitter;
  51693. };
  51694. // Clone
  51695. /**
  51696. * Clones the particle system.
  51697. * @param name The name of the cloned object
  51698. * @param newEmitter The new emitter to use
  51699. * @returns the cloned particle system
  51700. */
  51701. ParticleSystem.prototype.clone = function (name, newEmitter) {
  51702. var custom = null;
  51703. var program = null;
  51704. if (this.customShader != null) {
  51705. program = this.customShader;
  51706. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  51707. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  51708. }
  51709. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  51710. result.customShader = program;
  51711. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  51712. if (newEmitter === undefined) {
  51713. newEmitter = this.emitter;
  51714. }
  51715. result.emitter = newEmitter;
  51716. if (this.particleTexture) {
  51717. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  51718. }
  51719. if (!this.preventAutoStart) {
  51720. result.start();
  51721. }
  51722. return result;
  51723. };
  51724. /**
  51725. * Serializes the particle system to a JSON object.
  51726. * @returns the JSON object
  51727. */
  51728. ParticleSystem.prototype.serialize = function () {
  51729. var serializationObject = {};
  51730. serializationObject.name = this.name;
  51731. serializationObject.id = this.id;
  51732. // Emitter
  51733. if (this.emitter.position) {
  51734. var emitterMesh = this.emitter;
  51735. serializationObject.emitterId = emitterMesh.id;
  51736. }
  51737. else {
  51738. var emitterPosition = this.emitter;
  51739. serializationObject.emitter = emitterPosition.asArray();
  51740. }
  51741. serializationObject.capacity = this.getCapacity();
  51742. if (this.particleTexture) {
  51743. serializationObject.textureName = this.particleTexture.name;
  51744. }
  51745. // Animations
  51746. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  51747. // Particle system
  51748. serializationObject.minAngularSpeed = this.minAngularSpeed;
  51749. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  51750. serializationObject.minSize = this.minSize;
  51751. serializationObject.maxSize = this.maxSize;
  51752. serializationObject.minEmitPower = this.minEmitPower;
  51753. serializationObject.maxEmitPower = this.maxEmitPower;
  51754. serializationObject.minLifeTime = this.minLifeTime;
  51755. serializationObject.maxLifeTime = this.maxLifeTime;
  51756. serializationObject.emitRate = this.emitRate;
  51757. serializationObject.minEmitBox = this.minEmitBox.asArray();
  51758. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  51759. serializationObject.gravity = this.gravity.asArray();
  51760. serializationObject.direction1 = this.direction1.asArray();
  51761. serializationObject.direction2 = this.direction2.asArray();
  51762. serializationObject.color1 = this.color1.asArray();
  51763. serializationObject.color2 = this.color2.asArray();
  51764. serializationObject.colorDead = this.colorDead.asArray();
  51765. serializationObject.updateSpeed = this.updateSpeed;
  51766. serializationObject.targetStopDuration = this.targetStopDuration;
  51767. serializationObject.textureMask = this.textureMask.asArray();
  51768. serializationObject.blendMode = this.blendMode;
  51769. serializationObject.customShader = this.customShader;
  51770. serializationObject.preventAutoStart = this.preventAutoStart;
  51771. serializationObject.startSpriteCellID = this.startSpriteCellID;
  51772. serializationObject.endSpriteCellID = this.endSpriteCellID;
  51773. serializationObject.spriteCellLoop = this.spriteCellLoop;
  51774. serializationObject.spriteCellChangeSpeed = this.spriteCellChangeSpeed;
  51775. serializationObject.spriteCellWidth = this.spriteCellWidth;
  51776. serializationObject.spriteCellHeight = this.spriteCellHeight;
  51777. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  51778. // Emitter
  51779. if (this.particleEmitterType) {
  51780. serializationObject.particleEmitterType = this.particleEmitterType.serialize();
  51781. }
  51782. return serializationObject;
  51783. };
  51784. /**
  51785. * Parses a JSON object to create a particle system.
  51786. * @param parsedParticleSystem The JSON object to parse
  51787. * @param scene The scene to create the particle system in
  51788. * @param rootUrl The root url to use to load external dependencies like texture
  51789. * @returns the Parsed particle system
  51790. */
  51791. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  51792. var name = parsedParticleSystem.name;
  51793. var custom = null;
  51794. var program = null;
  51795. if (parsedParticleSystem.customShader) {
  51796. program = parsedParticleSystem.customShader;
  51797. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  51798. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  51799. }
  51800. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  51801. particleSystem.customShader = program;
  51802. if (parsedParticleSystem.id) {
  51803. particleSystem.id = parsedParticleSystem.id;
  51804. }
  51805. // Auto start
  51806. if (parsedParticleSystem.preventAutoStart) {
  51807. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  51808. }
  51809. // Texture
  51810. if (parsedParticleSystem.textureName) {
  51811. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  51812. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  51813. }
  51814. // Emitter
  51815. if (parsedParticleSystem.emitterId) {
  51816. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  51817. }
  51818. else {
  51819. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  51820. }
  51821. // Animations
  51822. if (parsedParticleSystem.animations) {
  51823. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  51824. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  51825. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  51826. }
  51827. }
  51828. if (parsedParticleSystem.autoAnimate) {
  51829. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  51830. }
  51831. // Particle system
  51832. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  51833. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  51834. particleSystem.minSize = parsedParticleSystem.minSize;
  51835. particleSystem.maxSize = parsedParticleSystem.maxSize;
  51836. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  51837. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  51838. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  51839. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  51840. particleSystem.emitRate = parsedParticleSystem.emitRate;
  51841. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  51842. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  51843. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  51844. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  51845. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  51846. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  51847. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  51848. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  51849. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  51850. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  51851. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  51852. particleSystem.blendMode = parsedParticleSystem.blendMode;
  51853. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  51854. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  51855. particleSystem.spriteCellLoop = parsedParticleSystem.spriteCellLoop;
  51856. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  51857. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  51858. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  51859. if (!particleSystem.preventAutoStart) {
  51860. particleSystem.start();
  51861. }
  51862. return particleSystem;
  51863. };
  51864. /**
  51865. * Source color is added to the destination color without alpha affecting the result.
  51866. */
  51867. ParticleSystem.BLENDMODE_ONEONE = 0;
  51868. /**
  51869. * Blend current color and particle color using particle’s alpha.
  51870. */
  51871. ParticleSystem.BLENDMODE_STANDARD = 1;
  51872. return ParticleSystem;
  51873. }());
  51874. BABYLON.ParticleSystem = ParticleSystem;
  51875. })(BABYLON || (BABYLON = {}));
  51876. //# sourceMappingURL=babylon.particleSystem.js.map
  51877. //# sourceMappingURL=babylon.IParticleEmitterType.js.map
  51878. var BABYLON;
  51879. (function (BABYLON) {
  51880. /**
  51881. * Particle emitter emitting particles from the inside of a box.
  51882. * It emits the particles randomly between 2 given directions.
  51883. */
  51884. var BoxParticleEmitter = /** @class */ (function () {
  51885. /**
  51886. * Creates a new instance of @see BoxParticleEmitter
  51887. */
  51888. function BoxParticleEmitter() {
  51889. /**
  51890. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  51891. */
  51892. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  51893. /**
  51894. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  51895. */
  51896. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  51897. /**
  51898. * 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.
  51899. */
  51900. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  51901. /**
  51902. * 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.
  51903. */
  51904. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  51905. }
  51906. /**
  51907. * Called by the particle System when the direction is computed for the created particle.
  51908. * @param emitPower is the power of the particle (speed)
  51909. * @param worldMatrix is the world matrix of the particle system
  51910. * @param directionToUpdate is the direction vector to update with the result
  51911. * @param particle is the particle we are computed the direction for
  51912. */
  51913. BoxParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  51914. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  51915. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  51916. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  51917. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  51918. };
  51919. /**
  51920. * Called by the particle System when the position is computed for the created particle.
  51921. * @param worldMatrix is the world matrix of the particle system
  51922. * @param positionToUpdate is the position vector to update with the result
  51923. * @param particle is the particle we are computed the position for
  51924. */
  51925. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  51926. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  51927. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  51928. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  51929. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  51930. };
  51931. /**
  51932. * Clones the current emitter and returns a copy of it
  51933. * @returns the new emitter
  51934. */
  51935. BoxParticleEmitter.prototype.clone = function () {
  51936. var newOne = new BoxParticleEmitter();
  51937. BABYLON.Tools.DeepCopy(this, newOne);
  51938. return newOne;
  51939. };
  51940. /**
  51941. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  51942. * @param effect defines the update shader
  51943. */
  51944. BoxParticleEmitter.prototype.applyToShader = function (effect) {
  51945. effect.setVector3("direction1", this.direction1);
  51946. effect.setVector3("direction2", this.direction2);
  51947. effect.setVector3("minEmitBox", this.minEmitBox);
  51948. effect.setVector3("maxEmitBox", this.maxEmitBox);
  51949. };
  51950. /**
  51951. * Returns a string to use to update the GPU particles update shader
  51952. * @returns a string containng the defines string
  51953. */
  51954. BoxParticleEmitter.prototype.getEffectDefines = function () {
  51955. return "#define BOXEMITTER";
  51956. };
  51957. /**
  51958. * Returns the string "BoxEmitter"
  51959. * @returns a string containing the class name
  51960. */
  51961. BoxParticleEmitter.prototype.getClassName = function () {
  51962. return "BoxEmitter";
  51963. };
  51964. /**
  51965. * Serializes the particle system to a JSON object.
  51966. * @returns the JSON object
  51967. */
  51968. BoxParticleEmitter.prototype.serialize = function () {
  51969. var serializationObject = {};
  51970. serializationObject.type = this.getClassName();
  51971. serializationObject.direction1 = this.direction1.asArray();
  51972. ;
  51973. serializationObject.direction2 = this.direction2.asArray();
  51974. ;
  51975. serializationObject.minEmitBox = this.minEmitBox.asArray();
  51976. ;
  51977. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  51978. ;
  51979. return serializationObject;
  51980. };
  51981. /**
  51982. * Parse properties from a JSON object
  51983. * @param serializationObject defines the JSON object
  51984. */
  51985. BoxParticleEmitter.prototype.parse = function (serializationObject) {
  51986. this.direction1.copyFrom(serializationObject.direction1);
  51987. this.direction2.copyFrom(serializationObject.direction2);
  51988. this.minEmitBox.copyFrom(serializationObject.minEmitBox);
  51989. this.maxEmitBox.copyFrom(serializationObject.maxEmitBox);
  51990. };
  51991. return BoxParticleEmitter;
  51992. }());
  51993. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  51994. })(BABYLON || (BABYLON = {}));
  51995. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  51996. var BABYLON;
  51997. (function (BABYLON) {
  51998. /**
  51999. * Particle emitter emitting particles from the inside of a cone.
  52000. * It emits the particles alongside the cone volume from the base to the particle.
  52001. * The emission direction might be randomized.
  52002. */
  52003. var ConeParticleEmitter = /** @class */ (function () {
  52004. /**
  52005. * Creates a new instance of @see ConeParticleEmitter
  52006. * @param radius the radius of the emission cone (1 by default)
  52007. * @param angles the cone base angle (PI by default)
  52008. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  52009. */
  52010. function ConeParticleEmitter(radius,
  52011. /**
  52012. * The radius of the emission cone.
  52013. */
  52014. angle,
  52015. /**
  52016. * The cone base angle.
  52017. */
  52018. directionRandomizer) {
  52019. if (radius === void 0) { radius = 1; }
  52020. if (angle === void 0) { angle = Math.PI; }
  52021. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  52022. this.angle = angle;
  52023. this.directionRandomizer = directionRandomizer;
  52024. this.radius = radius;
  52025. }
  52026. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  52027. /**
  52028. * Gets the radius of the emission cone.
  52029. */
  52030. get: function () {
  52031. return this._radius;
  52032. },
  52033. /**
  52034. * Sets the radius of the emission cone.
  52035. */
  52036. set: function (value) {
  52037. this._radius = value;
  52038. if (this.angle !== 0) {
  52039. this._height = value / Math.tan(this.angle / 2);
  52040. }
  52041. else {
  52042. this._height = 1;
  52043. }
  52044. },
  52045. enumerable: true,
  52046. configurable: true
  52047. });
  52048. /**
  52049. * Called by the particle System when the direction is computed for the created particle.
  52050. * @param emitPower is the power of the particle (speed)
  52051. * @param worldMatrix is the world matrix of the particle system
  52052. * @param directionToUpdate is the direction vector to update with the result
  52053. * @param particle is the particle we are computed the direction for
  52054. */
  52055. ConeParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  52056. if (this.angle === 0) {
  52057. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, emitPower, 0, worldMatrix, directionToUpdate);
  52058. }
  52059. else {
  52060. // measure the direction Vector from the emitter to the particle.
  52061. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  52062. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  52063. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  52064. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  52065. direction.x += randX;
  52066. direction.y += randY;
  52067. direction.z += randZ;
  52068. direction.normalize();
  52069. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  52070. }
  52071. };
  52072. /**
  52073. * Called by the particle System when the position is computed for the created particle.
  52074. * @param worldMatrix is the world matrix of the particle system
  52075. * @param positionToUpdate is the position vector to update with the result
  52076. * @param particle is the particle we are computed the position for
  52077. */
  52078. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  52079. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  52080. var h = BABYLON.Scalar.RandomRange(0, 1);
  52081. // Better distribution in a cone at normal angles.
  52082. h = 1 - h * h;
  52083. var radius = BABYLON.Scalar.RandomRange(0, this._radius);
  52084. radius = radius * h / this._height;
  52085. var randX = radius * Math.sin(s);
  52086. var randZ = radius * Math.cos(s);
  52087. var randY = h * this._height;
  52088. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  52089. };
  52090. /**
  52091. * Clones the current emitter and returns a copy of it
  52092. * @returns the new emitter
  52093. */
  52094. ConeParticleEmitter.prototype.clone = function () {
  52095. var newOne = new ConeParticleEmitter(this.radius, this.angle, this.directionRandomizer);
  52096. BABYLON.Tools.DeepCopy(this, newOne);
  52097. return newOne;
  52098. };
  52099. /**
  52100. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  52101. * @param effect defines the update shader
  52102. */
  52103. ConeParticleEmitter.prototype.applyToShader = function (effect) {
  52104. effect.setFloat("radius", this.radius);
  52105. effect.setFloat("angle", this.angle);
  52106. effect.setFloat("height", this._height);
  52107. effect.setFloat("directionRandomizer", this.directionRandomizer);
  52108. };
  52109. /**
  52110. * Returns a string to use to update the GPU particles update shader
  52111. * @returns a string containng the defines string
  52112. */
  52113. ConeParticleEmitter.prototype.getEffectDefines = function () {
  52114. return "#define CONEEMITTER";
  52115. };
  52116. /**
  52117. * Returns the string "BoxEmitter"
  52118. * @returns a string containing the class name
  52119. */
  52120. ConeParticleEmitter.prototype.getClassName = function () {
  52121. return "ConeEmitter";
  52122. };
  52123. /**
  52124. * Serializes the particle system to a JSON object.
  52125. * @returns the JSON object
  52126. */
  52127. ConeParticleEmitter.prototype.serialize = function () {
  52128. var serializationObject = {};
  52129. serializationObject.type = this.getClassName();
  52130. serializationObject.radius = this.radius;
  52131. serializationObject.angle = this.angle;
  52132. serializationObject.directionRandomizer = this.directionRandomizer;
  52133. return serializationObject;
  52134. };
  52135. /**
  52136. * Parse properties from a JSON object
  52137. * @param serializationObject defines the JSON object
  52138. */
  52139. ConeParticleEmitter.prototype.parse = function (serializationObject) {
  52140. this.radius = serializationObject.radius;
  52141. this.angle = serializationObject.angle;
  52142. this.directionRandomizer = serializationObject.directionRandomizer;
  52143. };
  52144. return ConeParticleEmitter;
  52145. }());
  52146. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  52147. })(BABYLON || (BABYLON = {}));
  52148. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  52149. var BABYLON;
  52150. (function (BABYLON) {
  52151. /**
  52152. * Particle emitter emitting particles from the inside of a sphere.
  52153. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  52154. */
  52155. var SphereParticleEmitter = /** @class */ (function () {
  52156. /**
  52157. * Creates a new instance of @see SphereParticleEmitter
  52158. * @param radius the radius of the emission sphere (1 by default)
  52159. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  52160. */
  52161. function SphereParticleEmitter(
  52162. /**
  52163. * The radius of the emission sphere.
  52164. */
  52165. radius,
  52166. /**
  52167. * How much to randomize the particle direction [0-1].
  52168. */
  52169. directionRandomizer) {
  52170. if (radius === void 0) { radius = 1; }
  52171. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  52172. this.radius = radius;
  52173. this.directionRandomizer = directionRandomizer;
  52174. }
  52175. /**
  52176. * Called by the particle System when the direction is computed for the created particle.
  52177. * @param emitPower is the power of the particle (speed)
  52178. * @param worldMatrix is the world matrix of the particle system
  52179. * @param directionToUpdate is the direction vector to update with the result
  52180. * @param particle is the particle we are computed the direction for
  52181. */
  52182. SphereParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  52183. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  52184. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  52185. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  52186. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  52187. direction.x += randX;
  52188. direction.y += randY;
  52189. direction.z += randZ;
  52190. direction.normalize();
  52191. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  52192. };
  52193. /**
  52194. * Called by the particle System when the position is computed for the created particle.
  52195. * @param worldMatrix is the world matrix of the particle system
  52196. * @param positionToUpdate is the position vector to update with the result
  52197. * @param particle is the particle we are computed the position for
  52198. */
  52199. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  52200. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  52201. var theta = BABYLON.Scalar.RandomRange(0, Math.PI);
  52202. var randRadius = BABYLON.Scalar.RandomRange(0, this.radius);
  52203. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  52204. var randY = randRadius * Math.cos(theta);
  52205. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  52206. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  52207. };
  52208. /**
  52209. * Clones the current emitter and returns a copy of it
  52210. * @returns the new emitter
  52211. */
  52212. SphereParticleEmitter.prototype.clone = function () {
  52213. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  52214. BABYLON.Tools.DeepCopy(this, newOne);
  52215. return newOne;
  52216. };
  52217. /**
  52218. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  52219. * @param effect defines the update shader
  52220. */
  52221. SphereParticleEmitter.prototype.applyToShader = function (effect) {
  52222. effect.setFloat("radius", this.radius);
  52223. effect.setFloat("directionRandomizer", this.directionRandomizer);
  52224. };
  52225. /**
  52226. * Returns a string to use to update the GPU particles update shader
  52227. * @returns a string containng the defines string
  52228. */
  52229. SphereParticleEmitter.prototype.getEffectDefines = function () {
  52230. return "#define SPHEREEMITTER";
  52231. };
  52232. /**
  52233. * Returns the string "SphereParticleEmitter"
  52234. * @returns a string containing the class name
  52235. */
  52236. SphereParticleEmitter.prototype.getClassName = function () {
  52237. return "SphereParticleEmitter";
  52238. };
  52239. /**
  52240. * Serializes the particle system to a JSON object.
  52241. * @returns the JSON object
  52242. */
  52243. SphereParticleEmitter.prototype.serialize = function () {
  52244. var serializationObject = {};
  52245. serializationObject.type = this.getClassName();
  52246. serializationObject.radius = this.radius;
  52247. serializationObject.directionRandomizer = this.directionRandomizer;
  52248. return serializationObject;
  52249. };
  52250. /**
  52251. * Parse properties from a JSON object
  52252. * @param serializationObject defines the JSON object
  52253. */
  52254. SphereParticleEmitter.prototype.parse = function (serializationObject) {
  52255. this.radius = serializationObject.radius;
  52256. this.directionRandomizer = serializationObject.directionRandomizer;
  52257. };
  52258. return SphereParticleEmitter;
  52259. }());
  52260. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  52261. /**
  52262. * Particle emitter emitting particles from the inside of a sphere.
  52263. * It emits the particles randomly between two vectors.
  52264. */
  52265. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  52266. __extends(SphereDirectedParticleEmitter, _super);
  52267. /**
  52268. * Creates a new instance of @see SphereDirectedParticleEmitter
  52269. * @param radius the radius of the emission sphere (1 by default)
  52270. * @param direction1 the min limit of the emission direction (up vector by default)
  52271. * @param direction2 the max limit of the emission direction (up vector by default)
  52272. */
  52273. function SphereDirectedParticleEmitter(radius,
  52274. /**
  52275. * The min limit of the emission direction.
  52276. */
  52277. direction1,
  52278. /**
  52279. * The max limit of the emission direction.
  52280. */
  52281. direction2) {
  52282. if (radius === void 0) { radius = 1; }
  52283. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  52284. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  52285. var _this = _super.call(this, radius) || this;
  52286. _this.direction1 = direction1;
  52287. _this.direction2 = direction2;
  52288. return _this;
  52289. }
  52290. /**
  52291. * Called by the particle System when the direction is computed for the created particle.
  52292. * @param emitPower is the power of the particle (speed)
  52293. * @param worldMatrix is the world matrix of the particle system
  52294. * @param directionToUpdate is the direction vector to update with the result
  52295. * @param particle is the particle we are computed the direction for
  52296. */
  52297. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  52298. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  52299. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  52300. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  52301. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  52302. };
  52303. /**
  52304. * Clones the current emitter and returns a copy of it
  52305. * @returns the new emitter
  52306. */
  52307. SphereDirectedParticleEmitter.prototype.clone = function () {
  52308. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  52309. BABYLON.Tools.DeepCopy(this, newOne);
  52310. return newOne;
  52311. };
  52312. /**
  52313. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  52314. * @param effect defines the update shader
  52315. */
  52316. SphereDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  52317. effect.setFloat("radius", this.radius);
  52318. effect.setVector3("direction1", this.direction1);
  52319. effect.setVector3("direction2", this.direction2);
  52320. };
  52321. /**
  52322. * Returns a string to use to update the GPU particles update shader
  52323. * @returns a string containng the defines string
  52324. */
  52325. SphereDirectedParticleEmitter.prototype.getEffectDefines = function () {
  52326. return "#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER";
  52327. };
  52328. /**
  52329. * Returns the string "SphereDirectedParticleEmitter"
  52330. * @returns a string containing the class name
  52331. */
  52332. SphereDirectedParticleEmitter.prototype.getClassName = function () {
  52333. return "SphereDirectedParticleEmitter";
  52334. };
  52335. /**
  52336. * Serializes the particle system to a JSON object.
  52337. * @returns the JSON object
  52338. */
  52339. SphereDirectedParticleEmitter.prototype.serialize = function () {
  52340. var serializationObject = _super.prototype.serialize.call(this);
  52341. ;
  52342. serializationObject.direction1 = this.direction1.asArray();
  52343. ;
  52344. serializationObject.direction2 = this.direction2.asArray();
  52345. ;
  52346. return serializationObject;
  52347. };
  52348. /**
  52349. * Parse properties from a JSON object
  52350. * @param serializationObject defines the JSON object
  52351. */
  52352. SphereDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  52353. _super.prototype.parse.call(this, serializationObject);
  52354. this.direction1.copyFrom(serializationObject.direction1);
  52355. this.direction2.copyFrom(serializationObject.direction2);
  52356. };
  52357. return SphereDirectedParticleEmitter;
  52358. }(SphereParticleEmitter));
  52359. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  52360. })(BABYLON || (BABYLON = {}));
  52361. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  52362. var __assign = (this && this.__assign) || Object.assign || function(t) {
  52363. for (var s, i = 1, n = arguments.length; i < n; i++) {
  52364. s = arguments[i];
  52365. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  52366. t[p] = s[p];
  52367. }
  52368. return t;
  52369. };
  52370. var BABYLON;
  52371. (function (BABYLON) {
  52372. /**
  52373. * This represents a GPU particle system in Babylon
  52374. * This is the fastest particle system in Babylon as it uses the GPU to update the individual particle data
  52375. * @see https://www.babylonjs-playground.com/#PU4WYI#4
  52376. */
  52377. var GPUParticleSystem = /** @class */ (function () {
  52378. /**
  52379. * Instantiates a GPU particle system.
  52380. * 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.
  52381. * @param name The name of the particle system
  52382. * @param capacity The max number of particles alive at the same time
  52383. * @param scene The scene the particle system belongs to
  52384. */
  52385. function GPUParticleSystem(name, options, scene) {
  52386. /**
  52387. * The emitter represents the Mesh or position we are attaching the particle system to.
  52388. */
  52389. this.emitter = null;
  52390. /**
  52391. * The rendering group used by the Particle system to chose when to render.
  52392. */
  52393. this.renderingGroupId = 0;
  52394. /**
  52395. * The layer mask we are rendering the particles through.
  52396. */
  52397. this.layerMask = 0x0FFFFFFF;
  52398. this._targetIndex = 0;
  52399. this._currentRenderId = -1;
  52400. this._started = false;
  52401. this._stopped = false;
  52402. this._timeDelta = 0;
  52403. this._attributesStrideSize = 14;
  52404. this._actualFrame = 0;
  52405. /**
  52406. * List of animations used by the particle system.
  52407. */
  52408. this.animations = [];
  52409. /**
  52410. * An event triggered when the system is disposed.
  52411. */
  52412. this.onDisposeObservable = new BABYLON.Observable();
  52413. /**
  52414. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  52415. */
  52416. this.updateSpeed = 0.01;
  52417. /**
  52418. * The amount of time the particle system is running (depends of the overall update speed).
  52419. */
  52420. this.targetStopDuration = 0;
  52421. /**
  52422. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  52423. */
  52424. this.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
  52425. /**
  52426. * Minimum life time of emitting particles.
  52427. */
  52428. this.minLifeTime = 1;
  52429. /**
  52430. * Maximum life time of emitting particles.
  52431. */
  52432. this.maxLifeTime = 1;
  52433. /**
  52434. * Minimum Size of emitting particles.
  52435. */
  52436. this.minSize = 1;
  52437. /**
  52438. * Maximum Size of emitting particles.
  52439. */
  52440. this.maxSize = 1;
  52441. /**
  52442. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  52443. */
  52444. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  52445. /**
  52446. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  52447. */
  52448. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  52449. /**
  52450. * Color the particle will have at the end of its lifetime.
  52451. */
  52452. this.colorDead = new BABYLON.Color4(0, 0, 0, 0);
  52453. /**
  52454. * The maximum number of particles to emit per frame until we reach the activeParticleCount value
  52455. */
  52456. this.emitRate = 100;
  52457. /**
  52458. * You can use gravity if you want to give an orientation to your particles.
  52459. */
  52460. this.gravity = BABYLON.Vector3.Zero();
  52461. /**
  52462. * Minimum power of emitting particles.
  52463. */
  52464. this.minEmitPower = 1;
  52465. /**
  52466. * Maximum power of emitting particles.
  52467. */
  52468. this.maxEmitPower = 1;
  52469. /**
  52470. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  52471. * to override the particles.
  52472. */
  52473. this.forceDepthWrite = false;
  52474. this.id = name;
  52475. this.name = name;
  52476. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  52477. this._engine = this._scene.getEngine();
  52478. var fullOptions = __assign({ capacity: 50000, randomTextureSize: this._engine.getCaps().maxTextureSize }, options);
  52479. this._capacity = fullOptions.capacity;
  52480. this._activeCount = fullOptions.capacity;
  52481. this._currentActiveCount = 0;
  52482. this._scene.particleSystems.push(this);
  52483. this._updateEffectOptions = {
  52484. attributes: ["position", "age", "life", "seed", "size", "color", "direction"],
  52485. uniformsNames: ["currentCount", "timeDelta", "generalRandoms", "emitterWM", "lifeTime", "color1", "color2", "sizeRange", "gravity", "emitPower",
  52486. "direction1", "direction2", "minEmitBox", "maxEmitBox", "radius", "directionRandomizer", "height", "angle", "stopFactor"],
  52487. uniformBuffersNames: [],
  52488. samplers: ["randomSampler"],
  52489. defines: "",
  52490. fallbacks: null,
  52491. onCompiled: null,
  52492. onError: null,
  52493. indexParameters: null,
  52494. maxSimultaneousLights: 0,
  52495. transformFeedbackVaryings: ["outPosition", "outAge", "outLife", "outSeed", "outSize", "outColor", "outDirection"]
  52496. };
  52497. // Random data
  52498. var maxTextureSize = Math.min(this._engine.getCaps().maxTextureSize, fullOptions.randomTextureSize);
  52499. var d = [];
  52500. for (var i = 0; i < maxTextureSize; ++i) {
  52501. d.push(Math.random());
  52502. d.push(Math.random());
  52503. d.push(Math.random());
  52504. d.push(Math.random());
  52505. }
  52506. 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);
  52507. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  52508. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  52509. this._randomTextureSize = maxTextureSize;
  52510. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  52511. }
  52512. Object.defineProperty(GPUParticleSystem, "IsSupported", {
  52513. /**
  52514. * Gets a boolean indicating if the GPU particles can be rendered on current browser
  52515. */
  52516. get: function () {
  52517. if (!BABYLON.Engine.LastCreatedEngine) {
  52518. return false;
  52519. }
  52520. return BABYLON.Engine.LastCreatedEngine.webGLVersion > 1;
  52521. },
  52522. enumerable: true,
  52523. configurable: true
  52524. });
  52525. Object.defineProperty(GPUParticleSystem.prototype, "direction1", {
  52526. /**
  52527. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  52528. * This only works when particleEmitterTyps is a BoxParticleEmitter
  52529. */
  52530. get: function () {
  52531. if (this.particleEmitterType.direction1) {
  52532. return this.particleEmitterType.direction1;
  52533. }
  52534. return BABYLON.Vector3.Zero();
  52535. },
  52536. set: function (value) {
  52537. if (this.particleEmitterType.direction1) {
  52538. this.particleEmitterType.direction1 = value;
  52539. }
  52540. },
  52541. enumerable: true,
  52542. configurable: true
  52543. });
  52544. Object.defineProperty(GPUParticleSystem.prototype, "direction2", {
  52545. /**
  52546. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  52547. * This only works when particleEmitterTyps is a BoxParticleEmitter
  52548. */
  52549. get: function () {
  52550. if (this.particleEmitterType.direction2) {
  52551. return this.particleEmitterType.direction2;
  52552. }
  52553. return BABYLON.Vector3.Zero();
  52554. },
  52555. set: function (value) {
  52556. if (this.particleEmitterType.direction2) {
  52557. this.particleEmitterType.direction2 = value;
  52558. }
  52559. },
  52560. enumerable: true,
  52561. configurable: true
  52562. });
  52563. Object.defineProperty(GPUParticleSystem.prototype, "minEmitBox", {
  52564. /**
  52565. * 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.
  52566. * This only works when particleEmitterTyps is a BoxParticleEmitter
  52567. */
  52568. get: function () {
  52569. if (this.particleEmitterType.minEmitBox) {
  52570. return this.particleEmitterType.minEmitBox;
  52571. }
  52572. return BABYLON.Vector3.Zero();
  52573. },
  52574. set: function (value) {
  52575. if (this.particleEmitterType.minEmitBox) {
  52576. this.particleEmitterType.minEmitBox = value;
  52577. }
  52578. },
  52579. enumerable: true,
  52580. configurable: true
  52581. });
  52582. Object.defineProperty(GPUParticleSystem.prototype, "maxEmitBox", {
  52583. /**
  52584. * 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.
  52585. * This only works when particleEmitterTyps is a BoxParticleEmitter
  52586. */
  52587. get: function () {
  52588. if (this.particleEmitterType.maxEmitBox) {
  52589. return this.particleEmitterType.maxEmitBox;
  52590. }
  52591. return BABYLON.Vector3.Zero();
  52592. },
  52593. set: function (value) {
  52594. if (this.particleEmitterType.maxEmitBox) {
  52595. this.particleEmitterType.maxEmitBox = value;
  52596. }
  52597. },
  52598. enumerable: true,
  52599. configurable: true
  52600. });
  52601. /**
  52602. * Gets the maximum number of particles active at the same time.
  52603. * @returns The max number of active particles.
  52604. */
  52605. GPUParticleSystem.prototype.getCapacity = function () {
  52606. return this._capacity;
  52607. };
  52608. Object.defineProperty(GPUParticleSystem.prototype, "activeParticleCount", {
  52609. /**
  52610. * Gets or set the number of active particles
  52611. */
  52612. get: function () {
  52613. return this._activeCount;
  52614. },
  52615. set: function (value) {
  52616. this._activeCount = Math.min(value, this._capacity);
  52617. },
  52618. enumerable: true,
  52619. configurable: true
  52620. });
  52621. /**
  52622. * Is this system ready to be used/rendered
  52623. * @return true if the system is ready
  52624. */
  52625. GPUParticleSystem.prototype.isReady = function () {
  52626. if (!this.emitter || !this._updateEffect.isReady() || !this._renderEffect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  52627. return false;
  52628. }
  52629. return true;
  52630. };
  52631. /**
  52632. * Gets Wether the system has been started.
  52633. * @returns True if it has been started, otherwise false.
  52634. */
  52635. GPUParticleSystem.prototype.isStarted = function () {
  52636. return this._started;
  52637. };
  52638. /**
  52639. * Starts the particle system and begins to emit.
  52640. */
  52641. GPUParticleSystem.prototype.start = function () {
  52642. this._started = true;
  52643. this._stopped = false;
  52644. };
  52645. /**
  52646. * Stops the particle system.
  52647. */
  52648. GPUParticleSystem.prototype.stop = function () {
  52649. this._stopped = true;
  52650. };
  52651. /**
  52652. * Remove all active particles
  52653. */
  52654. GPUParticleSystem.prototype.reset = function () {
  52655. this._releaseBuffers();
  52656. this._releaseVAOs();
  52657. this._currentActiveCount = 0;
  52658. this._targetIndex = 0;
  52659. };
  52660. /**
  52661. * Returns the string "GPUParticleSystem"
  52662. * @returns a string containing the class name
  52663. */
  52664. GPUParticleSystem.prototype.getClassName = function () {
  52665. return "GPUParticleSystem";
  52666. };
  52667. GPUParticleSystem.prototype._createUpdateVAO = function (source) {
  52668. var updateVertexBuffers = {};
  52669. updateVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3);
  52670. updateVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1);
  52671. updateVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1);
  52672. updateVertexBuffers["seed"] = source.createVertexBuffer("seed", 5, 1);
  52673. updateVertexBuffers["size"] = source.createVertexBuffer("size", 6, 1);
  52674. updateVertexBuffers["color"] = source.createVertexBuffer("color", 7, 4);
  52675. updateVertexBuffers["direction"] = source.createVertexBuffer("direction", 11, 3);
  52676. var vao = this._engine.recordVertexArrayObject(updateVertexBuffers, null, this._updateEffect);
  52677. this._engine.bindArrayBuffer(null);
  52678. return vao;
  52679. };
  52680. GPUParticleSystem.prototype._createRenderVAO = function (source, spriteSource) {
  52681. var renderVertexBuffers = {};
  52682. renderVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3, this._attributesStrideSize, true);
  52683. renderVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1, this._attributesStrideSize, true);
  52684. renderVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1, this._attributesStrideSize, true);
  52685. renderVertexBuffers["size"] = source.createVertexBuffer("size", 6, 1, this._attributesStrideSize, true);
  52686. renderVertexBuffers["color"] = source.createVertexBuffer("color", 7, 4, this._attributesStrideSize, true);
  52687. renderVertexBuffers["offset"] = spriteSource.createVertexBuffer("offset", 0, 2);
  52688. renderVertexBuffers["uv"] = spriteSource.createVertexBuffer("uv", 2, 2);
  52689. var vao = this._engine.recordVertexArrayObject(renderVertexBuffers, null, this._renderEffect);
  52690. this._engine.bindArrayBuffer(null);
  52691. return vao;
  52692. };
  52693. GPUParticleSystem.prototype._initialize = function (force) {
  52694. if (force === void 0) { force = false; }
  52695. if (this._buffer0 && !force) {
  52696. return;
  52697. }
  52698. var engine = this._scene.getEngine();
  52699. var data = new Array();
  52700. for (var particleIndex = 0; particleIndex < this._capacity; particleIndex++) {
  52701. // position
  52702. data.push(0.0);
  52703. data.push(0.0);
  52704. data.push(0.0);
  52705. // Age and life
  52706. data.push(0.0); // create the particle as a dead one to create a new one at start
  52707. data.push(0.0);
  52708. // Seed
  52709. data.push(Math.random());
  52710. // Size
  52711. data.push(0.0);
  52712. // color
  52713. data.push(0.0);
  52714. data.push(0.0);
  52715. data.push(0.0);
  52716. data.push(0.0);
  52717. // direction
  52718. data.push(0.0);
  52719. data.push(0.0);
  52720. data.push(0.0);
  52721. }
  52722. // Sprite data
  52723. var spriteData = new Float32Array([0.5, 0.5, 1, 1,
  52724. -0.5, 0.5, 0, 1,
  52725. -0.5, -0.5, 0, 0,
  52726. 0.5, -0.5, 1, 0]);
  52727. // Buffers
  52728. this._buffer0 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  52729. this._buffer1 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  52730. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 4);
  52731. // Update VAO
  52732. this._updateVAO = [];
  52733. this._updateVAO.push(this._createUpdateVAO(this._buffer0));
  52734. this._updateVAO.push(this._createUpdateVAO(this._buffer1));
  52735. // Render VAO
  52736. this._renderVAO = [];
  52737. this._renderVAO.push(this._createRenderVAO(this._buffer1, this._spriteBuffer));
  52738. this._renderVAO.push(this._createRenderVAO(this._buffer0, this._spriteBuffer));
  52739. // Links
  52740. this._sourceBuffer = this._buffer0;
  52741. this._targetBuffer = this._buffer1;
  52742. };
  52743. /** @ignore */
  52744. GPUParticleSystem.prototype._recreateUpdateEffect = function () {
  52745. var defines = this.particleEmitterType ? this.particleEmitterType.getEffectDefines() : "";
  52746. if (this._updateEffect && this._updateEffectOptions.defines === defines) {
  52747. return;
  52748. }
  52749. this._updateEffectOptions.defines = defines;
  52750. this._updateEffect = new BABYLON.Effect("gpuUpdateParticles", this._updateEffectOptions, this._scene.getEngine());
  52751. };
  52752. /** @ignore */
  52753. GPUParticleSystem.prototype._recreateRenderEffect = function () {
  52754. var defines = "";
  52755. if (this._scene.clipPlane) {
  52756. defines = "\n#define CLIPPLANE";
  52757. }
  52758. if (this._renderEffect && this._renderEffect.defines === defines) {
  52759. return;
  52760. }
  52761. this._renderEffect = new BABYLON.Effect("gpuRenderParticles", ["position", "age", "life", "size", "color", "offset", "uv"], ["view", "projection", "colorDead", "invView", "vClipPlane"], ["textureSampler"], this._scene.getEngine(), defines);
  52762. };
  52763. /**
  52764. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  52765. */
  52766. GPUParticleSystem.prototype.animate = function () {
  52767. this._timeDelta = this.updateSpeed * this._scene.getAnimationRatio();
  52768. this._actualFrame += this._timeDelta;
  52769. if (!this._stopped) {
  52770. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration) {
  52771. this.stop();
  52772. }
  52773. }
  52774. };
  52775. /**
  52776. * Renders the particle system in its current state.
  52777. * @returns the current number of particles
  52778. */
  52779. GPUParticleSystem.prototype.render = function () {
  52780. if (!this._started) {
  52781. return 0;
  52782. }
  52783. this._recreateUpdateEffect();
  52784. this._recreateRenderEffect();
  52785. if (!this.isReady()) {
  52786. return 0;
  52787. }
  52788. if (this._currentRenderId === this._scene.getRenderId()) {
  52789. return 0;
  52790. }
  52791. this._currentRenderId = this._scene.getRenderId();
  52792. // Get everything ready to render
  52793. this._initialize();
  52794. this._currentActiveCount = Math.min(this._activeCount, this._currentActiveCount + (this.emitRate * this._timeDelta) | 0);
  52795. // Enable update effect
  52796. this._engine.enableEffect(this._updateEffect);
  52797. this._engine.setState(false);
  52798. this._updateEffect.setFloat("currentCount", this._currentActiveCount);
  52799. this._updateEffect.setFloat("timeDelta", this._timeDelta);
  52800. this._updateEffect.setFloat("stopFactor", this._stopped ? 0 : 1);
  52801. this._updateEffect.setFloat3("generalRandoms", Math.random(), Math.random(), Math.random());
  52802. this._updateEffect.setTexture("randomSampler", this._randomTexture);
  52803. this._updateEffect.setFloat2("lifeTime", this.minLifeTime, this.maxLifeTime);
  52804. this._updateEffect.setFloat2("emitPower", this.minEmitPower, this.maxEmitPower);
  52805. this._updateEffect.setDirectColor4("color1", this.color1);
  52806. this._updateEffect.setDirectColor4("color2", this.color2);
  52807. this._updateEffect.setFloat2("sizeRange", this.minSize, this.maxSize);
  52808. this._updateEffect.setVector3("gravity", this.gravity);
  52809. if (this.particleEmitterType) {
  52810. this.particleEmitterType.applyToShader(this._updateEffect);
  52811. }
  52812. var emitterWM;
  52813. if (this.emitter.position) {
  52814. var emitterMesh = this.emitter;
  52815. emitterWM = emitterMesh.getWorldMatrix();
  52816. }
  52817. else {
  52818. var emitterPosition = this.emitter;
  52819. emitterWM = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  52820. }
  52821. this._updateEffect.setMatrix("emitterWM", emitterWM);
  52822. // Bind source VAO
  52823. this._engine.bindVertexArrayObject(this._updateVAO[this._targetIndex], null);
  52824. // Update
  52825. this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer());
  52826. this._engine.setRasterizerState(false);
  52827. this._engine.beginTransformFeedback();
  52828. this._engine.drawArraysType(BABYLON.Material.PointListDrawMode, 0, this._currentActiveCount);
  52829. this._engine.endTransformFeedback();
  52830. this._engine.setRasterizerState(true);
  52831. this._engine.bindTransformFeedbackBuffer(null);
  52832. // Enable render effect
  52833. this._engine.enableEffect(this._renderEffect);
  52834. var viewMatrix = this._scene.getViewMatrix();
  52835. this._renderEffect.setMatrix("view", viewMatrix);
  52836. this._renderEffect.setMatrix("projection", this._scene.getProjectionMatrix());
  52837. this._renderEffect.setTexture("textureSampler", this.particleTexture);
  52838. this._renderEffect.setDirectColor4("colorDead", this.colorDead);
  52839. if (this._scene.clipPlane) {
  52840. var clipPlane = this._scene.clipPlane;
  52841. var invView = viewMatrix.clone();
  52842. invView.invert();
  52843. this._renderEffect.setMatrix("invView", invView);
  52844. this._renderEffect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  52845. }
  52846. // Draw order
  52847. if (this.blendMode === BABYLON.ParticleSystem.BLENDMODE_ONEONE) {
  52848. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  52849. }
  52850. else {
  52851. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  52852. }
  52853. if (this.forceDepthWrite) {
  52854. this._engine.setDepthWrite(true);
  52855. }
  52856. // Bind source VAO
  52857. this._engine.bindVertexArrayObject(this._renderVAO[this._targetIndex], null);
  52858. // Render
  52859. this._engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._currentActiveCount);
  52860. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  52861. // Switch VAOs
  52862. this._targetIndex++;
  52863. if (this._targetIndex === 2) {
  52864. this._targetIndex = 0;
  52865. }
  52866. // Switch buffers
  52867. var tmpBuffer = this._sourceBuffer;
  52868. this._sourceBuffer = this._targetBuffer;
  52869. this._targetBuffer = tmpBuffer;
  52870. return this._currentActiveCount;
  52871. };
  52872. /**
  52873. * Rebuilds the particle system
  52874. */
  52875. GPUParticleSystem.prototype.rebuild = function () {
  52876. this._initialize(true);
  52877. };
  52878. GPUParticleSystem.prototype._releaseBuffers = function () {
  52879. if (this._buffer0) {
  52880. this._buffer0.dispose();
  52881. this._buffer0 = null;
  52882. }
  52883. if (this._buffer1) {
  52884. this._buffer1.dispose();
  52885. this._buffer1 = null;
  52886. }
  52887. if (this._spriteBuffer) {
  52888. this._spriteBuffer.dispose();
  52889. this._spriteBuffer = null;
  52890. }
  52891. };
  52892. GPUParticleSystem.prototype._releaseVAOs = function () {
  52893. if (!this._updateVAO) {
  52894. return;
  52895. }
  52896. for (var index = 0; index < this._updateVAO.length; index++) {
  52897. this._engine.releaseVertexArrayObject(this._updateVAO[index]);
  52898. }
  52899. this._updateVAO = [];
  52900. for (var index = 0; index < this._renderVAO.length; index++) {
  52901. this._engine.releaseVertexArrayObject(this._renderVAO[index]);
  52902. }
  52903. this._renderVAO = [];
  52904. };
  52905. /**
  52906. * Disposes the particle system and free the associated resources
  52907. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  52908. */
  52909. GPUParticleSystem.prototype.dispose = function (disposeTexture) {
  52910. if (disposeTexture === void 0) { disposeTexture = true; }
  52911. var index = this._scene.particleSystems.indexOf(this);
  52912. if (index > -1) {
  52913. this._scene.particleSystems.splice(index, 1);
  52914. }
  52915. this._releaseBuffers();
  52916. this._releaseVAOs();
  52917. if (this._randomTexture) {
  52918. this._randomTexture.dispose();
  52919. this._randomTexture = null;
  52920. }
  52921. if (disposeTexture && this.particleTexture) {
  52922. this.particleTexture.dispose();
  52923. this.particleTexture = null;
  52924. }
  52925. // Callback
  52926. this.onDisposeObservable.notifyObservers(this);
  52927. this.onDisposeObservable.clear();
  52928. };
  52929. /**
  52930. * Clones the particle system.
  52931. * @param name The name of the cloned object
  52932. * @param newEmitter The new emitter to use
  52933. * @returns the cloned particle system
  52934. */
  52935. GPUParticleSystem.prototype.clone = function (name, newEmitter) {
  52936. var result = new GPUParticleSystem(name, { capacity: this._capacity, randomTextureSize: this._randomTextureSize }, this._scene);
  52937. BABYLON.Tools.DeepCopy(this, result);
  52938. if (newEmitter === undefined) {
  52939. newEmitter = this.emitter;
  52940. }
  52941. result.emitter = newEmitter;
  52942. if (this.particleTexture) {
  52943. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  52944. }
  52945. return result;
  52946. };
  52947. /**
  52948. * Serializes the particle system to a JSON object.
  52949. * @returns the JSON object
  52950. */
  52951. GPUParticleSystem.prototype.serialize = function () {
  52952. var serializationObject = {};
  52953. serializationObject.name = this.name;
  52954. serializationObject.id = this.id;
  52955. // Emitter
  52956. if (this.emitter.position) {
  52957. var emitterMesh = this.emitter;
  52958. serializationObject.emitterId = emitterMesh.id;
  52959. }
  52960. else {
  52961. var emitterPosition = this.emitter;
  52962. serializationObject.emitter = emitterPosition.asArray();
  52963. }
  52964. serializationObject.capacity = this.getCapacity();
  52965. if (this.particleTexture) {
  52966. serializationObject.textureName = this.particleTexture.name;
  52967. }
  52968. // Animations
  52969. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  52970. // Particle system
  52971. serializationObject.activeParticleCount = this.activeParticleCount;
  52972. serializationObject.randomTextureSize = this._randomTextureSize;
  52973. serializationObject.minSize = this.minSize;
  52974. serializationObject.maxSize = this.maxSize;
  52975. serializationObject.minEmitPower = this.minEmitPower;
  52976. serializationObject.maxEmitPower = this.maxEmitPower;
  52977. serializationObject.minLifeTime = this.minLifeTime;
  52978. serializationObject.maxLifeTime = this.maxLifeTime;
  52979. serializationObject.emitRate = this.emitRate;
  52980. serializationObject.gravity = this.gravity.asArray();
  52981. serializationObject.color1 = this.color1.asArray();
  52982. serializationObject.color2 = this.color2.asArray();
  52983. serializationObject.colorDead = this.colorDead.asArray();
  52984. serializationObject.updateSpeed = this.updateSpeed;
  52985. serializationObject.targetStopDuration = this.targetStopDuration;
  52986. serializationObject.blendMode = this.blendMode;
  52987. // Emitter
  52988. if (this.particleEmitterType) {
  52989. serializationObject.particleEmitterType = this.particleEmitterType.serialize();
  52990. }
  52991. return serializationObject;
  52992. };
  52993. /**
  52994. * Parses a JSON object to create a GPU particle system.
  52995. * @param parsedParticleSystem The JSON object to parse
  52996. * @param scene The scene to create the particle system in
  52997. * @param rootUrl The root url to use to load external dependencies like texture
  52998. * @returns the parsed GPU particle system
  52999. */
  53000. GPUParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  53001. var name = parsedParticleSystem.name;
  53002. var particleSystem = new GPUParticleSystem(name, { capacity: parsedParticleSystem.capacity, randomTextureSize: parsedParticleSystem.randomTextureSize }, scene);
  53003. if (parsedParticleSystem.id) {
  53004. particleSystem.id = parsedParticleSystem.id;
  53005. }
  53006. // Texture
  53007. if (parsedParticleSystem.textureName) {
  53008. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  53009. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  53010. }
  53011. // Emitter
  53012. if (parsedParticleSystem.emitterId) {
  53013. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  53014. }
  53015. else {
  53016. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  53017. }
  53018. // Animations
  53019. if (parsedParticleSystem.animations) {
  53020. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  53021. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  53022. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  53023. }
  53024. }
  53025. // Particle system
  53026. particleSystem.activeParticleCount = parsedParticleSystem.activeParticleCount;
  53027. particleSystem.minSize = parsedParticleSystem.minSize;
  53028. particleSystem.maxSize = parsedParticleSystem.maxSize;
  53029. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  53030. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  53031. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  53032. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  53033. particleSystem.emitRate = parsedParticleSystem.emitRate;
  53034. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  53035. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  53036. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  53037. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  53038. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  53039. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  53040. particleSystem.blendMode = parsedParticleSystem.blendMode;
  53041. // Emitter
  53042. if (parsedParticleSystem.particleEmitterType) {
  53043. var emitterType = void 0;
  53044. switch (parsedParticleSystem.particleEmitterType.type) {
  53045. case "SphereEmitter":
  53046. emitterType = new BABYLON.SphereParticleEmitter();
  53047. break;
  53048. case "SphereDirectedParticleEmitter":
  53049. emitterType = new BABYLON.SphereDirectedParticleEmitter();
  53050. break;
  53051. case "ConeEmitter":
  53052. emitterType = new BABYLON.ConeParticleEmitter();
  53053. break;
  53054. case "BoxEmitter":
  53055. default:
  53056. emitterType = new BABYLON.BoxParticleEmitter();
  53057. break;
  53058. }
  53059. emitterType.parse(parsedParticleSystem.particleEmitterType);
  53060. particleSystem.particleEmitterType = emitterType;
  53061. }
  53062. return particleSystem;
  53063. };
  53064. return GPUParticleSystem;
  53065. }());
  53066. BABYLON.GPUParticleSystem = GPUParticleSystem;
  53067. })(BABYLON || (BABYLON = {}));
  53068. //# sourceMappingURL=babylon.gpuParticleSystem.js.map
  53069. var BABYLON;
  53070. (function (BABYLON) {
  53071. /**
  53072. * Represents one particle of a solid particle system.
  53073. * @see SolidParticleSystem
  53074. */
  53075. var SolidParticle = /** @class */ (function () {
  53076. /**
  53077. * Creates a Solid Particle object.
  53078. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  53079. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  53080. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  53081. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  53082. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  53083. * @param shapeId (integer) is the model shape identifier in the SPS.
  53084. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  53085. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  53086. */
  53087. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  53088. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  53089. /**
  53090. * particle global index
  53091. */
  53092. this.idx = 0;
  53093. /**
  53094. * The color of the particle
  53095. */
  53096. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  53097. /**
  53098. * The world space position of the particle.
  53099. */
  53100. this.position = BABYLON.Vector3.Zero();
  53101. /**
  53102. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  53103. */
  53104. this.rotation = BABYLON.Vector3.Zero();
  53105. /**
  53106. * The scaling of the particle.
  53107. */
  53108. this.scaling = BABYLON.Vector3.One();
  53109. /**
  53110. * The uvs of the particle.
  53111. */
  53112. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  53113. /**
  53114. * The current speed of the particle.
  53115. */
  53116. this.velocity = BABYLON.Vector3.Zero();
  53117. /**
  53118. * The pivot point in the particle local space.
  53119. */
  53120. this.pivot = BABYLON.Vector3.Zero();
  53121. /**
  53122. * Must the particle be translated from its pivot point in its local space ?
  53123. * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.
  53124. * Default : false
  53125. */
  53126. this.translateFromPivot = false;
  53127. /**
  53128. * Is the particle active or not ?
  53129. */
  53130. this.alive = true;
  53131. /**
  53132. * Is the particle visible or not ?
  53133. */
  53134. this.isVisible = true;
  53135. /**
  53136. * Index of this particle in the global "positions" array (Internal use)
  53137. */
  53138. this._pos = 0;
  53139. /**
  53140. * Index of this particle in the global "indices" array (Internal use)
  53141. */
  53142. this._ind = 0;
  53143. /**
  53144. * ModelShape id of this particle
  53145. */
  53146. this.shapeId = 0;
  53147. /**
  53148. * Index of the particle in its shape id (Internal use)
  53149. */
  53150. this.idxInShape = 0;
  53151. /**
  53152. * Still set as invisible in order to skip useless computations (Internal use)
  53153. */
  53154. this._stillInvisible = false;
  53155. /**
  53156. * Last computed particle rotation matrix
  53157. */
  53158. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  53159. /**
  53160. * Parent particle Id, if any.
  53161. * Default null.
  53162. */
  53163. this.parentId = null;
  53164. /**
  53165. * Internal global position in the SPS.
  53166. */
  53167. this._globalPosition = BABYLON.Vector3.Zero();
  53168. this.idx = particleIndex;
  53169. this._pos = positionIndex;
  53170. this._ind = indiceIndex;
  53171. this._model = model;
  53172. this.shapeId = shapeId;
  53173. this.idxInShape = idxInShape;
  53174. this._sps = sps;
  53175. if (modelBoundingInfo) {
  53176. this._modelBoundingInfo = modelBoundingInfo;
  53177. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  53178. }
  53179. }
  53180. Object.defineProperty(SolidParticle.prototype, "scale", {
  53181. /**
  53182. * Legacy support, changed scale to scaling
  53183. */
  53184. get: function () {
  53185. return this.scaling;
  53186. },
  53187. /**
  53188. * Legacy support, changed scale to scaling
  53189. */
  53190. set: function (scale) {
  53191. this.scaling = scale;
  53192. },
  53193. enumerable: true,
  53194. configurable: true
  53195. });
  53196. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  53197. /**
  53198. * Legacy support, changed quaternion to rotationQuaternion
  53199. */
  53200. get: function () {
  53201. return this.rotationQuaternion;
  53202. },
  53203. /**
  53204. * Legacy support, changed quaternion to rotationQuaternion
  53205. */
  53206. set: function (q) {
  53207. this.rotationQuaternion = q;
  53208. },
  53209. enumerable: true,
  53210. configurable: true
  53211. });
  53212. /**
  53213. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  53214. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  53215. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  53216. * @returns true if it intersects
  53217. */
  53218. SolidParticle.prototype.intersectsMesh = function (target) {
  53219. if (!this._boundingInfo || !target._boundingInfo) {
  53220. return false;
  53221. }
  53222. if (this._sps._bSphereOnly) {
  53223. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  53224. }
  53225. return this._boundingInfo.intersects(target._boundingInfo, false);
  53226. };
  53227. return SolidParticle;
  53228. }());
  53229. BABYLON.SolidParticle = SolidParticle;
  53230. /**
  53231. * Represents the shape of the model used by one particle of a solid particle system.
  53232. * SPS internal tool, don't use it manually.
  53233. * @see SolidParticleSystem
  53234. */
  53235. var ModelShape = /** @class */ (function () {
  53236. /**
  53237. * 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.
  53238. * SPS internal tool, don't use it manually.
  53239. * @ignore
  53240. */
  53241. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  53242. /**
  53243. * length of the shape in the model indices array (internal use)
  53244. */
  53245. this._indicesLength = 0;
  53246. this.shapeID = id;
  53247. this._shape = shape;
  53248. this._indicesLength = indicesLength;
  53249. this._shapeUV = shapeUV;
  53250. this._positionFunction = posFunction;
  53251. this._vertexFunction = vtxFunction;
  53252. }
  53253. return ModelShape;
  53254. }());
  53255. BABYLON.ModelShape = ModelShape;
  53256. /**
  53257. * Represents a Depth Sorted Particle in the solid particle system.
  53258. * @see SolidParticleSystem
  53259. */
  53260. var DepthSortedParticle = /** @class */ (function () {
  53261. function DepthSortedParticle() {
  53262. /**
  53263. * Index of the particle in the "indices" array
  53264. */
  53265. this.ind = 0;
  53266. /**
  53267. * Length of the particle shape in the "indices" array
  53268. */
  53269. this.indicesLength = 0;
  53270. /**
  53271. * Squared distance from the particle to the camera
  53272. */
  53273. this.sqDistance = 0.0;
  53274. }
  53275. return DepthSortedParticle;
  53276. }());
  53277. BABYLON.DepthSortedParticle = DepthSortedParticle;
  53278. })(BABYLON || (BABYLON = {}));
  53279. //# sourceMappingURL=babylon.solidParticle.js.map
  53280. var BABYLON;
  53281. (function (BABYLON) {
  53282. /**
  53283. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  53284. *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.
  53285. * The SPS is also a particle system. It provides some methods to manage the particles.
  53286. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  53287. *
  53288. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  53289. */
  53290. var SolidParticleSystem = /** @class */ (function () {
  53291. /**
  53292. * Creates a SPS (Solid Particle System) object.
  53293. * @param name (String) is the SPS name, this will be the underlying mesh name.
  53294. * @param scene (Scene) is the scene in which the SPS is added.
  53295. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  53296. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  53297. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  53298. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  53299. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  53300. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  53301. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  53302. */
  53303. function SolidParticleSystem(name, scene, options) {
  53304. /**
  53305. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  53306. * Example : var p = SPS.particles[i];
  53307. */
  53308. this.particles = new Array();
  53309. /**
  53310. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  53311. */
  53312. this.nbParticles = 0;
  53313. /**
  53314. * If the particles must ever face the camera (default false). Useful for planar particles.
  53315. */
  53316. this.billboard = false;
  53317. /**
  53318. * Recompute normals when adding a shape
  53319. */
  53320. this.recomputeNormals = true;
  53321. /**
  53322. * This a counter ofr your own usage. It's not set by any SPS functions.
  53323. */
  53324. this.counter = 0;
  53325. /**
  53326. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  53327. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  53328. */
  53329. this.vars = {};
  53330. /**
  53331. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  53332. */
  53333. this._bSphereOnly = false;
  53334. /**
  53335. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  53336. */
  53337. this._bSphereRadiusFactor = 1.0;
  53338. this._positions = new Array();
  53339. this._indices = new Array();
  53340. this._normals = new Array();
  53341. this._colors = new Array();
  53342. this._uvs = new Array();
  53343. this._index = 0; // indices index
  53344. this._updatable = true;
  53345. this._pickable = false;
  53346. this._isVisibilityBoxLocked = false;
  53347. this._alwaysVisible = false;
  53348. this._depthSort = false;
  53349. this._shapeCounter = 0;
  53350. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  53351. this._color = new BABYLON.Color4(0, 0, 0, 0);
  53352. this._computeParticleColor = true;
  53353. this._computeParticleTexture = true;
  53354. this._computeParticleRotation = true;
  53355. this._computeParticleVertex = false;
  53356. this._computeBoundingBox = false;
  53357. this._depthSortParticles = true;
  53358. this._cam_axisZ = BABYLON.Vector3.Zero();
  53359. this._cam_axisY = BABYLON.Vector3.Zero();
  53360. this._cam_axisX = BABYLON.Vector3.Zero();
  53361. this._axisZ = BABYLON.Axis.Z;
  53362. this._camDir = BABYLON.Vector3.Zero();
  53363. this._camInvertedPosition = BABYLON.Vector3.Zero();
  53364. this._rotMatrix = new BABYLON.Matrix();
  53365. this._invertMatrix = new BABYLON.Matrix();
  53366. this._rotated = BABYLON.Vector3.Zero();
  53367. this._quaternion = new BABYLON.Quaternion();
  53368. this._vertex = BABYLON.Vector3.Zero();
  53369. this._normal = BABYLON.Vector3.Zero();
  53370. this._yaw = 0.0;
  53371. this._pitch = 0.0;
  53372. this._roll = 0.0;
  53373. this._halfroll = 0.0;
  53374. this._halfpitch = 0.0;
  53375. this._halfyaw = 0.0;
  53376. this._sinRoll = 0.0;
  53377. this._cosRoll = 0.0;
  53378. this._sinPitch = 0.0;
  53379. this._cosPitch = 0.0;
  53380. this._sinYaw = 0.0;
  53381. this._cosYaw = 0.0;
  53382. this._mustUnrotateFixedNormals = false;
  53383. this._minimum = BABYLON.Vector3.Zero();
  53384. this._maximum = BABYLON.Vector3.Zero();
  53385. this._minBbox = BABYLON.Vector3.Zero();
  53386. this._maxBbox = BABYLON.Vector3.Zero();
  53387. this._particlesIntersect = false;
  53388. this._depthSortFunction = function (p1, p2) {
  53389. return (p2.sqDistance - p1.sqDistance);
  53390. };
  53391. this._needs32Bits = false;
  53392. this._pivotBackTranslation = BABYLON.Vector3.Zero();
  53393. this._scaledPivot = BABYLON.Vector3.Zero();
  53394. this._particleHasParent = false;
  53395. this.name = name;
  53396. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  53397. this._camera = scene.activeCamera;
  53398. this._pickable = options ? options.isPickable : false;
  53399. this._depthSort = options ? options.enableDepthSort : false;
  53400. this._particlesIntersect = options ? options.particleIntersection : false;
  53401. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  53402. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  53403. if (options && options.updatable) {
  53404. this._updatable = options.updatable;
  53405. }
  53406. else {
  53407. this._updatable = true;
  53408. }
  53409. if (this._pickable) {
  53410. this.pickedParticles = [];
  53411. }
  53412. if (this._depthSort) {
  53413. this.depthSortedParticles = [];
  53414. }
  53415. }
  53416. /**
  53417. * Builds the SPS underlying mesh. Returns a standard Mesh.
  53418. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  53419. * @returns the created mesh
  53420. */
  53421. SolidParticleSystem.prototype.buildMesh = function () {
  53422. if (this.nbParticles === 0) {
  53423. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  53424. this.addShape(triangle, 1);
  53425. triangle.dispose();
  53426. }
  53427. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  53428. this._positions32 = new Float32Array(this._positions);
  53429. this._uvs32 = new Float32Array(this._uvs);
  53430. this._colors32 = new Float32Array(this._colors);
  53431. if (this.recomputeNormals) {
  53432. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  53433. }
  53434. this._normals32 = new Float32Array(this._normals);
  53435. this._fixedNormal32 = new Float32Array(this._normals);
  53436. if (this._mustUnrotateFixedNormals) {
  53437. this._unrotateFixedNormals();
  53438. }
  53439. var vertexData = new BABYLON.VertexData();
  53440. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  53441. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  53442. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  53443. if (this._uvs32) {
  53444. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  53445. ;
  53446. }
  53447. if (this._colors32) {
  53448. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  53449. }
  53450. var mesh = new BABYLON.Mesh(this.name, this._scene);
  53451. vertexData.applyToMesh(mesh, this._updatable);
  53452. this.mesh = mesh;
  53453. this.mesh.isPickable = this._pickable;
  53454. // free memory
  53455. if (!this._depthSort) {
  53456. this._indices = null;
  53457. }
  53458. this._positions = null;
  53459. this._normals = null;
  53460. this._uvs = null;
  53461. this._colors = null;
  53462. if (!this._updatable) {
  53463. this.particles.length = 0;
  53464. }
  53465. return mesh;
  53466. };
  53467. /**
  53468. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  53469. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  53470. * Thus the particles generated from `digest()` have their property `position` set yet.
  53471. * @param mesh ( Mesh ) is the mesh to be digested
  53472. * @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
  53473. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  53474. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  53475. * @returns the current SPS
  53476. */
  53477. SolidParticleSystem.prototype.digest = function (mesh, options) {
  53478. var size = (options && options.facetNb) || 1;
  53479. var number = (options && options.number) || 0;
  53480. var delta = (options && options.delta) || 0;
  53481. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  53482. var meshInd = mesh.getIndices();
  53483. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  53484. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  53485. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  53486. var f = 0; // facet counter
  53487. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  53488. // compute size from number
  53489. if (number) {
  53490. number = (number > totalFacets) ? totalFacets : number;
  53491. size = Math.round(totalFacets / number);
  53492. delta = 0;
  53493. }
  53494. else {
  53495. size = (size > totalFacets) ? totalFacets : size;
  53496. }
  53497. var facetPos = []; // submesh positions
  53498. var facetInd = []; // submesh indices
  53499. var facetUV = []; // submesh UV
  53500. var facetCol = []; // submesh colors
  53501. var barycenter = BABYLON.Vector3.Zero();
  53502. var sizeO = size;
  53503. while (f < totalFacets) {
  53504. size = sizeO + Math.floor((1 + delta) * Math.random());
  53505. if (f > totalFacets - size) {
  53506. size = totalFacets - f;
  53507. }
  53508. // reset temp arrays
  53509. facetPos.length = 0;
  53510. facetInd.length = 0;
  53511. facetUV.length = 0;
  53512. facetCol.length = 0;
  53513. // iterate over "size" facets
  53514. var fi = 0;
  53515. for (var j = f * 3; j < (f + size) * 3; j++) {
  53516. facetInd.push(fi);
  53517. var i = meshInd[j];
  53518. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  53519. if (meshUV) {
  53520. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  53521. }
  53522. if (meshCol) {
  53523. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  53524. }
  53525. fi++;
  53526. }
  53527. // create a model shape for each single particle
  53528. var idx = this.nbParticles;
  53529. var shape = this._posToShape(facetPos);
  53530. var shapeUV = this._uvsToShapeUV(facetUV);
  53531. // compute the barycenter of the shape
  53532. var v;
  53533. for (v = 0; v < shape.length; v++) {
  53534. barycenter.addInPlace(shape[v]);
  53535. }
  53536. barycenter.scaleInPlace(1 / shape.length);
  53537. // shift the shape from its barycenter to the origin
  53538. for (v = 0; v < shape.length; v++) {
  53539. shape[v].subtractInPlace(barycenter);
  53540. }
  53541. var bInfo;
  53542. if (this._particlesIntersect) {
  53543. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  53544. }
  53545. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  53546. // add the particle in the SPS
  53547. var currentPos = this._positions.length;
  53548. var currentInd = this._indices.length;
  53549. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  53550. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  53551. // initialize the particle position
  53552. this.particles[this.nbParticles].position.addInPlace(barycenter);
  53553. this._index += shape.length;
  53554. idx++;
  53555. this.nbParticles++;
  53556. this._shapeCounter++;
  53557. f += size;
  53558. }
  53559. return this;
  53560. };
  53561. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  53562. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  53563. var index = 0;
  53564. var idx = 0;
  53565. for (var p = 0; p < this.particles.length; p++) {
  53566. this._particle = this.particles[p];
  53567. this._shape = this._particle._model._shape;
  53568. if (this._particle.rotationQuaternion) {
  53569. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  53570. }
  53571. else {
  53572. this._yaw = this._particle.rotation.y;
  53573. this._pitch = this._particle.rotation.x;
  53574. this._roll = this._particle.rotation.z;
  53575. this._quaternionRotationYPR();
  53576. }
  53577. this._quaternionToRotationMatrix();
  53578. this._rotMatrix.invertToRef(this._invertMatrix);
  53579. for (var pt = 0; pt < this._shape.length; pt++) {
  53580. idx = index + pt * 3;
  53581. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  53582. this._fixedNormal32[idx] = this._normal.x;
  53583. this._fixedNormal32[idx + 1] = this._normal.y;
  53584. this._fixedNormal32[idx + 2] = this._normal.z;
  53585. }
  53586. index = idx + 3;
  53587. }
  53588. };
  53589. //reset copy
  53590. SolidParticleSystem.prototype._resetCopy = function () {
  53591. this._copy.position.x = 0;
  53592. this._copy.position.y = 0;
  53593. this._copy.position.z = 0;
  53594. this._copy.rotation.x = 0;
  53595. this._copy.rotation.y = 0;
  53596. this._copy.rotation.z = 0;
  53597. this._copy.rotationQuaternion = null;
  53598. this._copy.scaling.x = 1.0;
  53599. this._copy.scaling.y = 1.0;
  53600. this._copy.scaling.z = 1.0;
  53601. this._copy.uvs.x = 0;
  53602. this._copy.uvs.y = 0;
  53603. this._copy.uvs.z = 1.0;
  53604. this._copy.uvs.w = 1.0;
  53605. this._copy.color = null;
  53606. this._copy.translateFromPivot = false;
  53607. };
  53608. // _meshBuilder : inserts the shape model in the global SPS mesh
  53609. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  53610. var i;
  53611. var u = 0;
  53612. var c = 0;
  53613. var n = 0;
  53614. this._resetCopy();
  53615. if (options && options.positionFunction) {
  53616. options.positionFunction(this._copy, idx, idxInShape);
  53617. this._mustUnrotateFixedNormals = true;
  53618. }
  53619. if (this._copy.rotationQuaternion) {
  53620. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  53621. }
  53622. else {
  53623. this._yaw = this._copy.rotation.y;
  53624. this._pitch = this._copy.rotation.x;
  53625. this._roll = this._copy.rotation.z;
  53626. this._quaternionRotationYPR();
  53627. }
  53628. this._quaternionToRotationMatrix();
  53629. this._scaledPivot.x = this._copy.pivot.x * this._copy.scaling.x;
  53630. this._scaledPivot.y = this._copy.pivot.y * this._copy.scaling.y;
  53631. this._scaledPivot.z = this._copy.pivot.z * this._copy.scaling.z;
  53632. if (this._copy.translateFromPivot) {
  53633. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  53634. }
  53635. else {
  53636. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  53637. }
  53638. for (i = 0; i < shape.length; i++) {
  53639. this._vertex.x = shape[i].x;
  53640. this._vertex.y = shape[i].y;
  53641. this._vertex.z = shape[i].z;
  53642. if (options && options.vertexFunction) {
  53643. options.vertexFunction(this._copy, this._vertex, i);
  53644. }
  53645. this._vertex.x *= this._copy.scaling.x;
  53646. this._vertex.y *= this._copy.scaling.y;
  53647. this._vertex.z *= this._copy.scaling.z;
  53648. this._vertex.x -= this._scaledPivot.x;
  53649. this._vertex.y -= this._scaledPivot.y;
  53650. this._vertex.z -= this._scaledPivot.z;
  53651. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  53652. this._rotated.addInPlace(this._pivotBackTranslation);
  53653. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  53654. if (meshUV) {
  53655. 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);
  53656. u += 2;
  53657. }
  53658. if (this._copy.color) {
  53659. this._color = this._copy.color;
  53660. }
  53661. else if (meshCol && meshCol[c] !== undefined) {
  53662. this._color.r = meshCol[c];
  53663. this._color.g = meshCol[c + 1];
  53664. this._color.b = meshCol[c + 2];
  53665. this._color.a = meshCol[c + 3];
  53666. }
  53667. else {
  53668. this._color.r = 1.0;
  53669. this._color.g = 1.0;
  53670. this._color.b = 1.0;
  53671. this._color.a = 1.0;
  53672. }
  53673. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  53674. c += 4;
  53675. if (!this.recomputeNormals && meshNor) {
  53676. this._normal.x = meshNor[n];
  53677. this._normal.y = meshNor[n + 1];
  53678. this._normal.z = meshNor[n + 2];
  53679. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  53680. normals.push(this._normal.x, this._normal.y, this._normal.z);
  53681. n += 3;
  53682. }
  53683. }
  53684. for (i = 0; i < meshInd.length; i++) {
  53685. var current_ind = p + meshInd[i];
  53686. indices.push(current_ind);
  53687. if (current_ind > 65535) {
  53688. this._needs32Bits = true;
  53689. }
  53690. }
  53691. if (this._pickable) {
  53692. var nbfaces = meshInd.length / 3;
  53693. for (i = 0; i < nbfaces; i++) {
  53694. this.pickedParticles.push({ idx: idx, faceId: i });
  53695. }
  53696. }
  53697. if (this._depthSort) {
  53698. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  53699. }
  53700. return this._copy;
  53701. };
  53702. // returns a shape array from positions array
  53703. SolidParticleSystem.prototype._posToShape = function (positions) {
  53704. var shape = [];
  53705. for (var i = 0; i < positions.length; i += 3) {
  53706. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  53707. }
  53708. return shape;
  53709. };
  53710. // returns a shapeUV array from a Vector4 uvs
  53711. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  53712. var shapeUV = [];
  53713. if (uvs) {
  53714. for (var i = 0; i < uvs.length; i++)
  53715. shapeUV.push(uvs[i]);
  53716. }
  53717. return shapeUV;
  53718. };
  53719. // adds a new particle object in the particles array
  53720. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  53721. if (bInfo === void 0) { bInfo = null; }
  53722. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  53723. this.particles.push(sp);
  53724. return sp;
  53725. };
  53726. /**
  53727. * Adds some particles to the SPS from the model shape. Returns the shape id.
  53728. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  53729. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  53730. * @param nb (positive integer) the number of particles to be created from this model
  53731. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  53732. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  53733. * @returns the number of shapes in the system
  53734. */
  53735. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  53736. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  53737. var meshInd = mesh.getIndices();
  53738. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  53739. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  53740. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  53741. var bbInfo;
  53742. if (this._particlesIntersect) {
  53743. bbInfo = mesh.getBoundingInfo();
  53744. }
  53745. var shape = this._posToShape(meshPos);
  53746. var shapeUV = this._uvsToShapeUV(meshUV);
  53747. var posfunc = options ? options.positionFunction : null;
  53748. var vtxfunc = options ? options.vertexFunction : null;
  53749. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  53750. // particles
  53751. var sp;
  53752. var currentCopy;
  53753. var idx = this.nbParticles;
  53754. for (var i = 0; i < nb; i++) {
  53755. var currentPos = this._positions.length;
  53756. var currentInd = this._indices.length;
  53757. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  53758. if (this._updatable) {
  53759. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  53760. sp.position.copyFrom(currentCopy.position);
  53761. sp.rotation.copyFrom(currentCopy.rotation);
  53762. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  53763. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  53764. }
  53765. if (currentCopy.color && sp.color) {
  53766. sp.color.copyFrom(currentCopy.color);
  53767. }
  53768. sp.scaling.copyFrom(currentCopy.scaling);
  53769. sp.uvs.copyFrom(currentCopy.uvs);
  53770. }
  53771. this._index += shape.length;
  53772. idx++;
  53773. }
  53774. this.nbParticles += nb;
  53775. this._shapeCounter++;
  53776. return this._shapeCounter - 1;
  53777. };
  53778. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  53779. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  53780. this._resetCopy();
  53781. if (particle._model._positionFunction) {
  53782. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  53783. }
  53784. if (this._copy.rotationQuaternion) {
  53785. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  53786. }
  53787. else {
  53788. this._yaw = this._copy.rotation.y;
  53789. this._pitch = this._copy.rotation.x;
  53790. this._roll = this._copy.rotation.z;
  53791. this._quaternionRotationYPR();
  53792. }
  53793. this._quaternionToRotationMatrix();
  53794. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  53795. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  53796. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  53797. if (this._copy.translateFromPivot) {
  53798. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  53799. }
  53800. else {
  53801. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  53802. }
  53803. this._shape = particle._model._shape;
  53804. for (var pt = 0; pt < this._shape.length; pt++) {
  53805. this._vertex.x = this._shape[pt].x;
  53806. this._vertex.y = this._shape[pt].y;
  53807. this._vertex.z = this._shape[pt].z;
  53808. if (particle._model._vertexFunction) {
  53809. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  53810. }
  53811. this._vertex.x *= this._copy.scaling.x;
  53812. this._vertex.y *= this._copy.scaling.y;
  53813. this._vertex.z *= this._copy.scaling.z;
  53814. this._vertex.x -= this._scaledPivot.x;
  53815. this._vertex.y -= this._scaledPivot.y;
  53816. this._vertex.z -= this._scaledPivot.z;
  53817. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  53818. this._rotated.addInPlace(this._pivotBackTranslation);
  53819. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  53820. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  53821. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  53822. }
  53823. particle.position.x = 0.0;
  53824. particle.position.y = 0.0;
  53825. particle.position.z = 0.0;
  53826. particle.rotation.x = 0.0;
  53827. particle.rotation.y = 0.0;
  53828. particle.rotation.z = 0.0;
  53829. particle.rotationQuaternion = null;
  53830. particle.scaling.x = 1.0;
  53831. particle.scaling.y = 1.0;
  53832. particle.scaling.z = 1.0;
  53833. particle.uvs.x = 0.0;
  53834. particle.uvs.y = 0.0;
  53835. particle.uvs.z = 1.0;
  53836. particle.uvs.w = 1.0;
  53837. particle.pivot.x = 0.0;
  53838. particle.pivot.y = 0.0;
  53839. particle.pivot.z = 0.0;
  53840. particle.translateFromPivot = false;
  53841. particle.parentId = null;
  53842. };
  53843. /**
  53844. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  53845. * @returns the SPS.
  53846. */
  53847. SolidParticleSystem.prototype.rebuildMesh = function () {
  53848. for (var p = 0; p < this.particles.length; p++) {
  53849. this._rebuildParticle(this.particles[p]);
  53850. }
  53851. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  53852. return this;
  53853. };
  53854. /**
  53855. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  53856. * This method calls `updateParticle()` for each particle of the SPS.
  53857. * For an animated SPS, it is usually called within the render loop.
  53858. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  53859. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  53860. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  53861. * @returns the SPS.
  53862. */
  53863. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  53864. if (start === void 0) { start = 0; }
  53865. if (end === void 0) { end = this.nbParticles - 1; }
  53866. if (update === void 0) { update = true; }
  53867. if (!this._updatable) {
  53868. return this;
  53869. }
  53870. // custom beforeUpdate
  53871. this.beforeUpdateParticles(start, end, update);
  53872. this._cam_axisX.x = 1.0;
  53873. this._cam_axisX.y = 0.0;
  53874. this._cam_axisX.z = 0.0;
  53875. this._cam_axisY.x = 0.0;
  53876. this._cam_axisY.y = 1.0;
  53877. this._cam_axisY.z = 0.0;
  53878. this._cam_axisZ.x = 0.0;
  53879. this._cam_axisZ.y = 0.0;
  53880. this._cam_axisZ.z = 1.0;
  53881. // cases when the World Matrix is to be computed first
  53882. if (this.billboard || this._depthSort) {
  53883. this.mesh.computeWorldMatrix(true);
  53884. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  53885. }
  53886. // if the particles will always face the camera
  53887. if (this.billboard) {
  53888. // compute the camera position and un-rotate it by the current mesh rotation
  53889. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  53890. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  53891. this._cam_axisZ.normalize();
  53892. // same for camera up vector extracted from the cam view matrix
  53893. var view = this._camera.getViewMatrix(true);
  53894. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  53895. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  53896. this._cam_axisY.normalize();
  53897. this._cam_axisX.normalize();
  53898. }
  53899. // if depthSort, compute the camera global position in the mesh local system
  53900. if (this._depthSort) {
  53901. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  53902. }
  53903. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  53904. var idx = 0; // current position index in the global array positions32
  53905. var index = 0; // position start index in the global array positions32 of the current particle
  53906. var colidx = 0; // current color index in the global array colors32
  53907. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  53908. var uvidx = 0; // current uv index in the global array uvs32
  53909. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  53910. var pt = 0; // current index in the particle model shape
  53911. if (this.mesh.isFacetDataEnabled) {
  53912. this._computeBoundingBox = true;
  53913. }
  53914. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  53915. if (this._computeBoundingBox) {
  53916. if (start == 0 && end == this.nbParticles - 1) {
  53917. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  53918. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  53919. }
  53920. else {
  53921. if (this.mesh._boundingInfo) {
  53922. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  53923. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  53924. }
  53925. }
  53926. }
  53927. // particle loop
  53928. index = this.particles[start]._pos;
  53929. var vpos = (index / 3) | 0;
  53930. colorIndex = vpos * 4;
  53931. uvIndex = vpos * 2;
  53932. for (var p = start; p <= end; p++) {
  53933. this._particle = this.particles[p];
  53934. this._shape = this._particle._model._shape;
  53935. this._shapeUV = this._particle._model._shapeUV;
  53936. // call to custom user function to update the particle properties
  53937. this.updateParticle(this._particle);
  53938. // camera-particle distance for depth sorting
  53939. if (this._depthSort && this._depthSortParticles) {
  53940. var dsp = this.depthSortedParticles[p];
  53941. dsp.ind = this._particle._ind;
  53942. dsp.indicesLength = this._particle._model._indicesLength;
  53943. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  53944. }
  53945. // skip the computations for inactive or already invisible particles
  53946. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  53947. // increment indexes for the next particle
  53948. pt = this._shape.length;
  53949. index += pt * 3;
  53950. colorIndex += pt * 4;
  53951. uvIndex += pt * 2;
  53952. continue;
  53953. }
  53954. if (this._particle.isVisible) {
  53955. this._particle._stillInvisible = false; // un-mark permanent invisibility
  53956. this._particleHasParent = (this._particle.parentId !== null);
  53957. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  53958. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  53959. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  53960. // particle rotation matrix
  53961. if (this.billboard) {
  53962. this._particle.rotation.x = 0.0;
  53963. this._particle.rotation.y = 0.0;
  53964. }
  53965. if (this._computeParticleRotation || this.billboard) {
  53966. if (this._particle.rotationQuaternion) {
  53967. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  53968. }
  53969. else {
  53970. this._yaw = this._particle.rotation.y;
  53971. this._pitch = this._particle.rotation.x;
  53972. this._roll = this._particle.rotation.z;
  53973. this._quaternionRotationYPR();
  53974. }
  53975. this._quaternionToRotationMatrix();
  53976. }
  53977. if (this._particleHasParent) {
  53978. this._parent = this.particles[this._particle.parentId];
  53979. 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];
  53980. 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];
  53981. 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];
  53982. this._particle._globalPosition.x = this._parent._globalPosition.x + this._rotated.x;
  53983. this._particle._globalPosition.y = this._parent._globalPosition.y + this._rotated.y;
  53984. this._particle._globalPosition.z = this._parent._globalPosition.z + this._rotated.z;
  53985. if (this._computeParticleRotation || this.billboard) {
  53986. 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];
  53987. 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];
  53988. 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];
  53989. 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];
  53990. 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];
  53991. 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];
  53992. 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];
  53993. 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];
  53994. 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];
  53995. }
  53996. }
  53997. else {
  53998. this._particle._globalPosition.x = this._particle.position.x;
  53999. this._particle._globalPosition.y = this._particle.position.y;
  54000. this._particle._globalPosition.z = this._particle.position.z;
  54001. if (this._computeParticleRotation || this.billboard) {
  54002. this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
  54003. this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
  54004. this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
  54005. this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
  54006. this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
  54007. this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
  54008. this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
  54009. this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
  54010. this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
  54011. }
  54012. }
  54013. if (this._particle.translateFromPivot) {
  54014. this._pivotBackTranslation.x = 0.0;
  54015. this._pivotBackTranslation.y = 0.0;
  54016. this._pivotBackTranslation.z = 0.0;
  54017. }
  54018. else {
  54019. this._pivotBackTranslation.x = this._scaledPivot.x;
  54020. this._pivotBackTranslation.y = this._scaledPivot.y;
  54021. this._pivotBackTranslation.z = this._scaledPivot.z;
  54022. }
  54023. // particle vertex loop
  54024. for (pt = 0; pt < this._shape.length; pt++) {
  54025. idx = index + pt * 3;
  54026. colidx = colorIndex + pt * 4;
  54027. uvidx = uvIndex + pt * 2;
  54028. this._vertex.x = this._shape[pt].x;
  54029. this._vertex.y = this._shape[pt].y;
  54030. this._vertex.z = this._shape[pt].z;
  54031. if (this._computeParticleVertex) {
  54032. this.updateParticleVertex(this._particle, this._vertex, pt);
  54033. }
  54034. // positions
  54035. this._vertex.x *= this._particle.scaling.x;
  54036. this._vertex.y *= this._particle.scaling.y;
  54037. this._vertex.z *= this._particle.scaling.z;
  54038. this._vertex.x -= this._scaledPivot.x;
  54039. this._vertex.y -= this._scaledPivot.y;
  54040. this._vertex.z -= this._scaledPivot.z;
  54041. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  54042. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  54043. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  54044. this._rotated.x += this._pivotBackTranslation.x;
  54045. this._rotated.y += this._pivotBackTranslation.y;
  54046. this._rotated.z += this._pivotBackTranslation.z;
  54047. 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;
  54048. 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;
  54049. 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;
  54050. if (this._computeBoundingBox) {
  54051. if (this._positions32[idx] < this._minimum.x) {
  54052. this._minimum.x = this._positions32[idx];
  54053. }
  54054. if (this._positions32[idx] > this._maximum.x) {
  54055. this._maximum.x = this._positions32[idx];
  54056. }
  54057. if (this._positions32[idx + 1] < this._minimum.y) {
  54058. this._minimum.y = this._positions32[idx + 1];
  54059. }
  54060. if (this._positions32[idx + 1] > this._maximum.y) {
  54061. this._maximum.y = this._positions32[idx + 1];
  54062. }
  54063. if (this._positions32[idx + 2] < this._minimum.z) {
  54064. this._minimum.z = this._positions32[idx + 2];
  54065. }
  54066. if (this._positions32[idx + 2] > this._maximum.z) {
  54067. this._maximum.z = this._positions32[idx + 2];
  54068. }
  54069. }
  54070. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  54071. if (!this._computeParticleVertex) {
  54072. this._normal.x = this._fixedNormal32[idx];
  54073. this._normal.y = this._fixedNormal32[idx + 1];
  54074. this._normal.z = this._fixedNormal32[idx + 2];
  54075. this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
  54076. this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
  54077. this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
  54078. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  54079. 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;
  54080. 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;
  54081. }
  54082. if (this._computeParticleColor && this._particle.color) {
  54083. this._colors32[colidx] = this._particle.color.r;
  54084. this._colors32[colidx + 1] = this._particle.color.g;
  54085. this._colors32[colidx + 2] = this._particle.color.b;
  54086. this._colors32[colidx + 3] = this._particle.color.a;
  54087. }
  54088. if (this._computeParticleTexture) {
  54089. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  54090. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  54091. }
  54092. }
  54093. }
  54094. else {
  54095. this._particle._stillInvisible = true; // mark the particle as invisible
  54096. for (pt = 0; pt < this._shape.length; pt++) {
  54097. idx = index + pt * 3;
  54098. colidx = colorIndex + pt * 4;
  54099. uvidx = uvIndex + pt * 2;
  54100. this._positions32[idx] = 0.0;
  54101. this._positions32[idx + 1] = 0.0;
  54102. this._positions32[idx + 2] = 0.0;
  54103. this._normals32[idx] = 0.0;
  54104. this._normals32[idx + 1] = 0.0;
  54105. this._normals32[idx + 2] = 0.0;
  54106. if (this._computeParticleColor && this._particle.color) {
  54107. this._colors32[colidx] = this._particle.color.r;
  54108. this._colors32[colidx + 1] = this._particle.color.g;
  54109. this._colors32[colidx + 2] = this._particle.color.b;
  54110. this._colors32[colidx + 3] = this._particle.color.a;
  54111. }
  54112. if (this._computeParticleTexture) {
  54113. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  54114. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  54115. }
  54116. }
  54117. }
  54118. // if the particle intersections must be computed : update the bbInfo
  54119. if (this._particlesIntersect) {
  54120. var bInfo = this._particle._boundingInfo;
  54121. var bBox = bInfo.boundingBox;
  54122. var bSphere = bInfo.boundingSphere;
  54123. if (!this._bSphereOnly) {
  54124. // place, scale and rotate the particle bbox within the SPS local system, then update it
  54125. for (var b = 0; b < bBox.vectors.length; b++) {
  54126. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  54127. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  54128. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  54129. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  54130. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  54131. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  54132. 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;
  54133. 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;
  54134. 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;
  54135. }
  54136. bBox._update(this.mesh._worldMatrix);
  54137. }
  54138. // place and scale the particle bouding sphere in the SPS local system, then update it
  54139. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  54140. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  54141. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  54142. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  54143. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  54144. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  54145. bSphere.center.x = this._particle._globalPosition.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  54146. bSphere.center.y = this._particle._globalPosition.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  54147. bSphere.center.z = this._particle._globalPosition.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  54148. 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));
  54149. bSphere._update(this.mesh._worldMatrix);
  54150. }
  54151. // increment indexes for the next particle
  54152. index = idx + 3;
  54153. colorIndex = colidx + 4;
  54154. uvIndex = uvidx + 2;
  54155. }
  54156. // if the VBO must be updated
  54157. if (update) {
  54158. if (this._computeParticleColor) {
  54159. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  54160. }
  54161. if (this._computeParticleTexture) {
  54162. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  54163. }
  54164. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  54165. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  54166. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  54167. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  54168. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  54169. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  54170. for (var i = 0; i < this._normals32.length; i++) {
  54171. this._fixedNormal32[i] = this._normals32[i];
  54172. }
  54173. }
  54174. if (!this.mesh.areNormalsFrozen) {
  54175. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  54176. }
  54177. }
  54178. if (this._depthSort && this._depthSortParticles) {
  54179. this.depthSortedParticles.sort(this._depthSortFunction);
  54180. var dspl = this.depthSortedParticles.length;
  54181. var sorted = 0;
  54182. var lind = 0;
  54183. var sind = 0;
  54184. var sid = 0;
  54185. for (sorted = 0; sorted < dspl; sorted++) {
  54186. lind = this.depthSortedParticles[sorted].indicesLength;
  54187. sind = this.depthSortedParticles[sorted].ind;
  54188. for (var i = 0; i < lind; i++) {
  54189. this._indices32[sid] = this._indices[sind + i];
  54190. sid++;
  54191. }
  54192. }
  54193. this.mesh.updateIndices(this._indices32);
  54194. }
  54195. }
  54196. if (this._computeBoundingBox) {
  54197. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  54198. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  54199. }
  54200. this.afterUpdateParticles(start, end, update);
  54201. return this;
  54202. };
  54203. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  54204. this._halfroll = this._roll * 0.5;
  54205. this._halfpitch = this._pitch * 0.5;
  54206. this._halfyaw = this._yaw * 0.5;
  54207. this._sinRoll = Math.sin(this._halfroll);
  54208. this._cosRoll = Math.cos(this._halfroll);
  54209. this._sinPitch = Math.sin(this._halfpitch);
  54210. this._cosPitch = Math.cos(this._halfpitch);
  54211. this._sinYaw = Math.sin(this._halfyaw);
  54212. this._cosYaw = Math.cos(this._halfyaw);
  54213. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  54214. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  54215. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  54216. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  54217. };
  54218. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  54219. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  54220. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  54221. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  54222. this._rotMatrix.m[3] = 0;
  54223. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  54224. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  54225. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  54226. this._rotMatrix.m[7] = 0;
  54227. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  54228. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  54229. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  54230. this._rotMatrix.m[11] = 0;
  54231. this._rotMatrix.m[12] = 0;
  54232. this._rotMatrix.m[13] = 0;
  54233. this._rotMatrix.m[14] = 0;
  54234. this._rotMatrix.m[15] = 1.0;
  54235. };
  54236. /**
  54237. * Disposes the SPS.
  54238. */
  54239. SolidParticleSystem.prototype.dispose = function () {
  54240. this.mesh.dispose();
  54241. this.vars = null;
  54242. // drop references to internal big arrays for the GC
  54243. this._positions = null;
  54244. this._indices = null;
  54245. this._normals = null;
  54246. this._uvs = null;
  54247. this._colors = null;
  54248. this._indices32 = null;
  54249. this._positions32 = null;
  54250. this._normals32 = null;
  54251. this._fixedNormal32 = null;
  54252. this._uvs32 = null;
  54253. this._colors32 = null;
  54254. this.pickedParticles = null;
  54255. };
  54256. /**
  54257. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  54258. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  54259. * @returns the SPS.
  54260. */
  54261. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  54262. if (!this._isVisibilityBoxLocked) {
  54263. this.mesh.refreshBoundingInfo();
  54264. }
  54265. return this;
  54266. };
  54267. /**
  54268. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  54269. * @param size the size (float) of the visibility box
  54270. * note : this doesn't lock the SPS mesh bounding box.
  54271. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  54272. */
  54273. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  54274. var vis = size / 2;
  54275. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  54276. };
  54277. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  54278. /**
  54279. * Gets whether the SPS as always visible or not
  54280. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  54281. */
  54282. get: function () {
  54283. return this._alwaysVisible;
  54284. },
  54285. /**
  54286. * Sets the SPS as always visible or not
  54287. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  54288. */
  54289. set: function (val) {
  54290. this._alwaysVisible = val;
  54291. this.mesh.alwaysSelectAsActiveMesh = val;
  54292. },
  54293. enumerable: true,
  54294. configurable: true
  54295. });
  54296. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  54297. /**
  54298. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  54299. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  54300. */
  54301. get: function () {
  54302. return this._isVisibilityBoxLocked;
  54303. },
  54304. /**
  54305. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  54306. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  54307. */
  54308. set: function (val) {
  54309. this._isVisibilityBoxLocked = val;
  54310. var boundingInfo = this.mesh.getBoundingInfo();
  54311. boundingInfo.isLocked = val;
  54312. },
  54313. enumerable: true,
  54314. configurable: true
  54315. });
  54316. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  54317. /**
  54318. * Gets if `setParticles()` computes the particle rotations or not.
  54319. * Default value : true. The SPS is faster when it's set to false.
  54320. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  54321. */
  54322. get: function () {
  54323. return this._computeParticleRotation;
  54324. },
  54325. /**
  54326. * Tells to `setParticles()` to compute the particle rotations or not.
  54327. * Default value : true. The SPS is faster when it's set to false.
  54328. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  54329. */
  54330. set: function (val) {
  54331. this._computeParticleRotation = val;
  54332. },
  54333. enumerable: true,
  54334. configurable: true
  54335. });
  54336. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  54337. /**
  54338. * Gets if `setParticles()` computes the particle colors or not.
  54339. * Default value : true. The SPS is faster when it's set to false.
  54340. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  54341. */
  54342. get: function () {
  54343. return this._computeParticleColor;
  54344. },
  54345. /**
  54346. * Tells to `setParticles()` to compute the particle colors or not.
  54347. * Default value : true. The SPS is faster when it's set to false.
  54348. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  54349. */
  54350. set: function (val) {
  54351. this._computeParticleColor = val;
  54352. },
  54353. enumerable: true,
  54354. configurable: true
  54355. });
  54356. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  54357. /**
  54358. * Gets if `setParticles()` computes the particle textures or not.
  54359. * Default value : true. The SPS is faster when it's set to false.
  54360. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  54361. */
  54362. get: function () {
  54363. return this._computeParticleTexture;
  54364. },
  54365. set: function (val) {
  54366. this._computeParticleTexture = val;
  54367. },
  54368. enumerable: true,
  54369. configurable: true
  54370. });
  54371. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  54372. /**
  54373. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  54374. * Default value : false. The SPS is faster when it's set to false.
  54375. * Note : the particle custom vertex positions aren't stored values.
  54376. */
  54377. get: function () {
  54378. return this._computeParticleVertex;
  54379. },
  54380. /**
  54381. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  54382. * Default value : false. The SPS is faster when it's set to false.
  54383. * Note : the particle custom vertex positions aren't stored values.
  54384. */
  54385. set: function (val) {
  54386. this._computeParticleVertex = val;
  54387. },
  54388. enumerable: true,
  54389. configurable: true
  54390. });
  54391. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  54392. /**
  54393. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  54394. */
  54395. get: function () {
  54396. return this._computeBoundingBox;
  54397. },
  54398. /**
  54399. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  54400. */
  54401. set: function (val) {
  54402. this._computeBoundingBox = val;
  54403. },
  54404. enumerable: true,
  54405. configurable: true
  54406. });
  54407. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  54408. /**
  54409. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  54410. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  54411. * Default : `true`
  54412. */
  54413. get: function () {
  54414. return this._depthSortParticles;
  54415. },
  54416. /**
  54417. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  54418. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  54419. * Default : `true`
  54420. */
  54421. set: function (val) {
  54422. this._depthSortParticles = val;
  54423. },
  54424. enumerable: true,
  54425. configurable: true
  54426. });
  54427. // =======================================================================
  54428. // Particle behavior logic
  54429. // these following methods may be overwritten by the user to fit his needs
  54430. /**
  54431. * This function does nothing. It may be overwritten to set all the particle first values.
  54432. * The SPS doesn't call this function, you may have to call it by your own.
  54433. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  54434. */
  54435. SolidParticleSystem.prototype.initParticles = function () {
  54436. };
  54437. /**
  54438. * This function does nothing. It may be overwritten to recycle a particle.
  54439. * The SPS doesn't call this function, you may have to call it by your own.
  54440. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  54441. * @param particle The particle to recycle
  54442. * @returns the recycled particle
  54443. */
  54444. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  54445. return particle;
  54446. };
  54447. /**
  54448. * Updates a particle : this function should be overwritten by the user.
  54449. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  54450. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  54451. * @example : just set a particle position or velocity and recycle conditions
  54452. * @param particle The particle to update
  54453. * @returns the updated particle
  54454. */
  54455. SolidParticleSystem.prototype.updateParticle = function (particle) {
  54456. return particle;
  54457. };
  54458. /**
  54459. * Updates a vertex of a particle : it can be overwritten by the user.
  54460. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  54461. * @param particle the current particle
  54462. * @param vertex the current index of the current particle
  54463. * @param pt the index of the current vertex in the particle shape
  54464. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  54465. * @example : just set a vertex particle position
  54466. * @returns the updated vertex
  54467. */
  54468. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  54469. return vertex;
  54470. };
  54471. /**
  54472. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  54473. * This does nothing and may be overwritten by the user.
  54474. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  54475. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  54476. * @param update the boolean update value actually passed to setParticles()
  54477. */
  54478. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  54479. };
  54480. /**
  54481. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  54482. * This will be passed three parameters.
  54483. * This does nothing and may be overwritten by the user.
  54484. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  54485. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  54486. * @param update the boolean update value actually passed to setParticles()
  54487. */
  54488. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  54489. };
  54490. return SolidParticleSystem;
  54491. }());
  54492. BABYLON.SolidParticleSystem = SolidParticleSystem;
  54493. })(BABYLON || (BABYLON = {}));
  54494. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  54495. var BABYLON;
  54496. (function (BABYLON) {
  54497. var ShaderMaterial = /** @class */ (function (_super) {
  54498. __extends(ShaderMaterial, _super);
  54499. function ShaderMaterial(name, scene, shaderPath, options) {
  54500. var _this = _super.call(this, name, scene) || this;
  54501. _this._textures = {};
  54502. _this._textureArrays = {};
  54503. _this._floats = {};
  54504. _this._ints = {};
  54505. _this._floatsArrays = {};
  54506. _this._colors3 = {};
  54507. _this._colors3Arrays = {};
  54508. _this._colors4 = {};
  54509. _this._vectors2 = {};
  54510. _this._vectors3 = {};
  54511. _this._vectors4 = {};
  54512. _this._matrices = {};
  54513. _this._matrices3x3 = {};
  54514. _this._matrices2x2 = {};
  54515. _this._vectors2Arrays = {};
  54516. _this._vectors3Arrays = {};
  54517. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  54518. _this._shaderPath = shaderPath;
  54519. options.needAlphaBlending = options.needAlphaBlending || false;
  54520. options.needAlphaTesting = options.needAlphaTesting || false;
  54521. options.attributes = options.attributes || ["position", "normal", "uv"];
  54522. options.uniforms = options.uniforms || ["worldViewProjection"];
  54523. options.uniformBuffers = options.uniformBuffers || [];
  54524. options.samplers = options.samplers || [];
  54525. options.defines = options.defines || [];
  54526. _this._options = options;
  54527. return _this;
  54528. }
  54529. ShaderMaterial.prototype.getClassName = function () {
  54530. return "ShaderMaterial";
  54531. };
  54532. ShaderMaterial.prototype.needAlphaBlending = function () {
  54533. return this._options.needAlphaBlending;
  54534. };
  54535. ShaderMaterial.prototype.needAlphaTesting = function () {
  54536. return this._options.needAlphaTesting;
  54537. };
  54538. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  54539. if (this._options.uniforms.indexOf(uniformName) === -1) {
  54540. this._options.uniforms.push(uniformName);
  54541. }
  54542. };
  54543. ShaderMaterial.prototype.setTexture = function (name, texture) {
  54544. if (this._options.samplers.indexOf(name) === -1) {
  54545. this._options.samplers.push(name);
  54546. }
  54547. this._textures[name] = texture;
  54548. return this;
  54549. };
  54550. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  54551. if (this._options.samplers.indexOf(name) === -1) {
  54552. this._options.samplers.push(name);
  54553. }
  54554. this._checkUniform(name);
  54555. this._textureArrays[name] = textures;
  54556. return this;
  54557. };
  54558. ShaderMaterial.prototype.setFloat = function (name, value) {
  54559. this._checkUniform(name);
  54560. this._floats[name] = value;
  54561. return this;
  54562. };
  54563. ShaderMaterial.prototype.setInt = function (name, value) {
  54564. this._checkUniform(name);
  54565. this._ints[name] = value;
  54566. return this;
  54567. };
  54568. ShaderMaterial.prototype.setFloats = function (name, value) {
  54569. this._checkUniform(name);
  54570. this._floatsArrays[name] = value;
  54571. return this;
  54572. };
  54573. ShaderMaterial.prototype.setColor3 = function (name, value) {
  54574. this._checkUniform(name);
  54575. this._colors3[name] = value;
  54576. return this;
  54577. };
  54578. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  54579. this._checkUniform(name);
  54580. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  54581. color.toArray(arr, arr.length);
  54582. return arr;
  54583. }, []);
  54584. return this;
  54585. };
  54586. ShaderMaterial.prototype.setColor4 = function (name, value) {
  54587. this._checkUniform(name);
  54588. this._colors4[name] = value;
  54589. return this;
  54590. };
  54591. ShaderMaterial.prototype.setVector2 = function (name, value) {
  54592. this._checkUniform(name);
  54593. this._vectors2[name] = value;
  54594. return this;
  54595. };
  54596. ShaderMaterial.prototype.setVector3 = function (name, value) {
  54597. this._checkUniform(name);
  54598. this._vectors3[name] = value;
  54599. return this;
  54600. };
  54601. ShaderMaterial.prototype.setVector4 = function (name, value) {
  54602. this._checkUniform(name);
  54603. this._vectors4[name] = value;
  54604. return this;
  54605. };
  54606. ShaderMaterial.prototype.setMatrix = function (name, value) {
  54607. this._checkUniform(name);
  54608. this._matrices[name] = value;
  54609. return this;
  54610. };
  54611. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  54612. this._checkUniform(name);
  54613. this._matrices3x3[name] = value;
  54614. return this;
  54615. };
  54616. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  54617. this._checkUniform(name);
  54618. this._matrices2x2[name] = value;
  54619. return this;
  54620. };
  54621. ShaderMaterial.prototype.setArray2 = function (name, value) {
  54622. this._checkUniform(name);
  54623. this._vectors2Arrays[name] = value;
  54624. return this;
  54625. };
  54626. ShaderMaterial.prototype.setArray3 = function (name, value) {
  54627. this._checkUniform(name);
  54628. this._vectors3Arrays[name] = value;
  54629. return this;
  54630. };
  54631. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  54632. if (!mesh) {
  54633. return true;
  54634. }
  54635. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  54636. return false;
  54637. }
  54638. return false;
  54639. };
  54640. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  54641. var scene = this.getScene();
  54642. var engine = scene.getEngine();
  54643. if (!this.checkReadyOnEveryCall) {
  54644. if (this._renderId === scene.getRenderId()) {
  54645. if (this._checkCache(scene, mesh, useInstances)) {
  54646. return true;
  54647. }
  54648. }
  54649. }
  54650. // Instances
  54651. var defines = [];
  54652. var attribs = [];
  54653. var fallbacks = new BABYLON.EffectFallbacks();
  54654. if (useInstances) {
  54655. defines.push("#define INSTANCES");
  54656. }
  54657. for (var index = 0; index < this._options.defines.length; index++) {
  54658. defines.push(this._options.defines[index]);
  54659. }
  54660. for (var index = 0; index < this._options.attributes.length; index++) {
  54661. attribs.push(this._options.attributes[index]);
  54662. }
  54663. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  54664. attribs.push(BABYLON.VertexBuffer.ColorKind);
  54665. defines.push("#define VERTEXCOLOR");
  54666. }
  54667. // Bones
  54668. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  54669. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  54670. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  54671. if (mesh.numBoneInfluencers > 4) {
  54672. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  54673. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  54674. }
  54675. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  54676. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  54677. fallbacks.addCPUSkinningFallback(0, mesh);
  54678. if (this._options.uniforms.indexOf("mBones") === -1) {
  54679. this._options.uniforms.push("mBones");
  54680. }
  54681. }
  54682. else {
  54683. defines.push("#define NUM_BONE_INFLUENCERS 0");
  54684. }
  54685. // Textures
  54686. for (var name in this._textures) {
  54687. if (!this._textures[name].isReady()) {
  54688. return false;
  54689. }
  54690. }
  54691. // Alpha test
  54692. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  54693. defines.push("#define ALPHATEST");
  54694. }
  54695. var previousEffect = this._effect;
  54696. var join = defines.join("\n");
  54697. this._effect = engine.createEffect(this._shaderPath, {
  54698. attributes: attribs,
  54699. uniformsNames: this._options.uniforms,
  54700. uniformBuffersNames: this._options.uniformBuffers,
  54701. samplers: this._options.samplers,
  54702. defines: join,
  54703. fallbacks: fallbacks,
  54704. onCompiled: this.onCompiled,
  54705. onError: this.onError
  54706. }, engine);
  54707. if (!this._effect.isReady()) {
  54708. return false;
  54709. }
  54710. if (previousEffect !== this._effect) {
  54711. scene.resetCachedMaterial();
  54712. }
  54713. this._renderId = scene.getRenderId();
  54714. return true;
  54715. };
  54716. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  54717. var scene = this.getScene();
  54718. if (!this._effect) {
  54719. return;
  54720. }
  54721. if (this._options.uniforms.indexOf("world") !== -1) {
  54722. this._effect.setMatrix("world", world);
  54723. }
  54724. if (this._options.uniforms.indexOf("worldView") !== -1) {
  54725. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  54726. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  54727. }
  54728. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  54729. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  54730. }
  54731. };
  54732. ShaderMaterial.prototype.bind = function (world, mesh) {
  54733. // Std values
  54734. this.bindOnlyWorldMatrix(world);
  54735. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  54736. if (this._options.uniforms.indexOf("view") !== -1) {
  54737. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  54738. }
  54739. if (this._options.uniforms.indexOf("projection") !== -1) {
  54740. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  54741. }
  54742. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  54743. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  54744. }
  54745. // Bones
  54746. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  54747. var name;
  54748. // Texture
  54749. for (name in this._textures) {
  54750. this._effect.setTexture(name, this._textures[name]);
  54751. }
  54752. // Texture arrays
  54753. for (name in this._textureArrays) {
  54754. this._effect.setTextureArray(name, this._textureArrays[name]);
  54755. }
  54756. // Int
  54757. for (name in this._ints) {
  54758. this._effect.setInt(name, this._ints[name]);
  54759. }
  54760. // Float
  54761. for (name in this._floats) {
  54762. this._effect.setFloat(name, this._floats[name]);
  54763. }
  54764. // Floats
  54765. for (name in this._floatsArrays) {
  54766. this._effect.setArray(name, this._floatsArrays[name]);
  54767. }
  54768. // Color3
  54769. for (name in this._colors3) {
  54770. this._effect.setColor3(name, this._colors3[name]);
  54771. }
  54772. for (name in this._colors3Arrays) {
  54773. this._effect.setArray3(name, this._colors3Arrays[name]);
  54774. }
  54775. // Color4
  54776. for (name in this._colors4) {
  54777. var color = this._colors4[name];
  54778. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  54779. }
  54780. // Vector2
  54781. for (name in this._vectors2) {
  54782. this._effect.setVector2(name, this._vectors2[name]);
  54783. }
  54784. // Vector3
  54785. for (name in this._vectors3) {
  54786. this._effect.setVector3(name, this._vectors3[name]);
  54787. }
  54788. // Vector4
  54789. for (name in this._vectors4) {
  54790. this._effect.setVector4(name, this._vectors4[name]);
  54791. }
  54792. // Matrix
  54793. for (name in this._matrices) {
  54794. this._effect.setMatrix(name, this._matrices[name]);
  54795. }
  54796. // Matrix 3x3
  54797. for (name in this._matrices3x3) {
  54798. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  54799. }
  54800. // Matrix 2x2
  54801. for (name in this._matrices2x2) {
  54802. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  54803. }
  54804. // Vector2Array
  54805. for (name in this._vectors2Arrays) {
  54806. this._effect.setArray2(name, this._vectors2Arrays[name]);
  54807. }
  54808. // Vector3Array
  54809. for (name in this._vectors3Arrays) {
  54810. this._effect.setArray3(name, this._vectors3Arrays[name]);
  54811. }
  54812. }
  54813. this._afterBind(mesh);
  54814. };
  54815. ShaderMaterial.prototype.getActiveTextures = function () {
  54816. var activeTextures = _super.prototype.getActiveTextures.call(this);
  54817. for (var name in this._textures) {
  54818. activeTextures.push(this._textures[name]);
  54819. }
  54820. for (var name in this._textureArrays) {
  54821. var array = this._textureArrays[name];
  54822. for (var index = 0; index < array.length; index++) {
  54823. activeTextures.push(array[index]);
  54824. }
  54825. }
  54826. return activeTextures;
  54827. };
  54828. ShaderMaterial.prototype.hasTexture = function (texture) {
  54829. if (_super.prototype.hasTexture.call(this, texture)) {
  54830. return true;
  54831. }
  54832. for (var name in this._textures) {
  54833. if (this._textures[name] === texture) {
  54834. return true;
  54835. }
  54836. }
  54837. for (var name in this._textureArrays) {
  54838. var array = this._textureArrays[name];
  54839. for (var index = 0; index < array.length; index++) {
  54840. if (array[index] === texture) {
  54841. return true;
  54842. }
  54843. }
  54844. }
  54845. return false;
  54846. };
  54847. ShaderMaterial.prototype.clone = function (name) {
  54848. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  54849. return newShaderMaterial;
  54850. };
  54851. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  54852. if (forceDisposeTextures) {
  54853. var name;
  54854. for (name in this._textures) {
  54855. this._textures[name].dispose();
  54856. }
  54857. for (name in this._textureArrays) {
  54858. var array = this._textureArrays[name];
  54859. for (var index = 0; index < array.length; index++) {
  54860. array[index].dispose();
  54861. }
  54862. }
  54863. }
  54864. this._textures = {};
  54865. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  54866. };
  54867. ShaderMaterial.prototype.serialize = function () {
  54868. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  54869. serializationObject.customType = "BABYLON.ShaderMaterial";
  54870. serializationObject.options = this._options;
  54871. serializationObject.shaderPath = this._shaderPath;
  54872. var name;
  54873. // Texture
  54874. serializationObject.textures = {};
  54875. for (name in this._textures) {
  54876. serializationObject.textures[name] = this._textures[name].serialize();
  54877. }
  54878. // Texture arrays
  54879. serializationObject.textureArrays = {};
  54880. for (name in this._textureArrays) {
  54881. serializationObject.textureArrays[name] = [];
  54882. var array = this._textureArrays[name];
  54883. for (var index = 0; index < array.length; index++) {
  54884. serializationObject.textureArrays[name].push(array[index].serialize());
  54885. }
  54886. }
  54887. // Float
  54888. serializationObject.floats = {};
  54889. for (name in this._floats) {
  54890. serializationObject.floats[name] = this._floats[name];
  54891. }
  54892. // Float s
  54893. serializationObject.FloatArrays = {};
  54894. for (name in this._floatsArrays) {
  54895. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  54896. }
  54897. // Color3
  54898. serializationObject.colors3 = {};
  54899. for (name in this._colors3) {
  54900. serializationObject.colors3[name] = this._colors3[name].asArray();
  54901. }
  54902. // Color3 array
  54903. serializationObject.colors3Arrays = {};
  54904. for (name in this._colors3Arrays) {
  54905. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  54906. }
  54907. // Color4
  54908. serializationObject.colors4 = {};
  54909. for (name in this._colors4) {
  54910. serializationObject.colors4[name] = this._colors4[name].asArray();
  54911. }
  54912. // Vector2
  54913. serializationObject.vectors2 = {};
  54914. for (name in this._vectors2) {
  54915. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  54916. }
  54917. // Vector3
  54918. serializationObject.vectors3 = {};
  54919. for (name in this._vectors3) {
  54920. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  54921. }
  54922. // Vector4
  54923. serializationObject.vectors4 = {};
  54924. for (name in this._vectors4) {
  54925. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  54926. }
  54927. // Matrix
  54928. serializationObject.matrices = {};
  54929. for (name in this._matrices) {
  54930. serializationObject.matrices[name] = this._matrices[name].asArray();
  54931. }
  54932. // Matrix 3x3
  54933. serializationObject.matrices3x3 = {};
  54934. for (name in this._matrices3x3) {
  54935. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  54936. }
  54937. // Matrix 2x2
  54938. serializationObject.matrices2x2 = {};
  54939. for (name in this._matrices2x2) {
  54940. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  54941. }
  54942. // Vector2Array
  54943. serializationObject.vectors2Arrays = {};
  54944. for (name in this._vectors2Arrays) {
  54945. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  54946. }
  54947. // Vector3Array
  54948. serializationObject.vectors3Arrays = {};
  54949. for (name in this._vectors3Arrays) {
  54950. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  54951. }
  54952. return serializationObject;
  54953. };
  54954. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  54955. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  54956. var name;
  54957. // Texture
  54958. for (name in source.textures) {
  54959. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  54960. }
  54961. // Texture arrays
  54962. for (name in source.textureArrays) {
  54963. var array = source.textureArrays[name];
  54964. var textureArray = new Array();
  54965. for (var index = 0; index < array.length; index++) {
  54966. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  54967. }
  54968. material.setTextureArray(name, textureArray);
  54969. }
  54970. // Float
  54971. for (name in source.floats) {
  54972. material.setFloat(name, source.floats[name]);
  54973. }
  54974. // Float s
  54975. for (name in source.floatsArrays) {
  54976. material.setFloats(name, source.floatsArrays[name]);
  54977. }
  54978. // Color3
  54979. for (name in source.colors3) {
  54980. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  54981. }
  54982. // Color3 arrays
  54983. for (name in source.colors3Arrays) {
  54984. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  54985. if (i % 3 === 0) {
  54986. arr.push([num]);
  54987. }
  54988. else {
  54989. arr[arr.length - 1].push(num);
  54990. }
  54991. return arr;
  54992. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  54993. material.setColor3Array(name, colors);
  54994. }
  54995. // Color4
  54996. for (name in source.colors4) {
  54997. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  54998. }
  54999. // Vector2
  55000. for (name in source.vectors2) {
  55001. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  55002. }
  55003. // Vector3
  55004. for (name in source.vectors3) {
  55005. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  55006. }
  55007. // Vector4
  55008. for (name in source.vectors4) {
  55009. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  55010. }
  55011. // Matrix
  55012. for (name in source.matrices) {
  55013. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  55014. }
  55015. // Matrix 3x3
  55016. for (name in source.matrices3x3) {
  55017. material.setMatrix3x3(name, source.matrices3x3[name]);
  55018. }
  55019. // Matrix 2x2
  55020. for (name in source.matrices2x2) {
  55021. material.setMatrix2x2(name, source.matrices2x2[name]);
  55022. }
  55023. // Vector2Array
  55024. for (name in source.vectors2Arrays) {
  55025. material.setArray2(name, source.vectors2Arrays[name]);
  55026. }
  55027. // Vector3Array
  55028. for (name in source.vectors3Arrays) {
  55029. material.setArray3(name, source.vectors3Arrays[name]);
  55030. }
  55031. return material;
  55032. };
  55033. return ShaderMaterial;
  55034. }(BABYLON.Material));
  55035. BABYLON.ShaderMaterial = ShaderMaterial;
  55036. })(BABYLON || (BABYLON = {}));
  55037. //# sourceMappingURL=babylon.shaderMaterial.js.map
  55038. var BABYLON;
  55039. (function (BABYLON) {
  55040. var GroundMesh = /** @class */ (function (_super) {
  55041. __extends(GroundMesh, _super);
  55042. function GroundMesh(name, scene) {
  55043. var _this = _super.call(this, name, scene) || this;
  55044. _this.generateOctree = false;
  55045. return _this;
  55046. }
  55047. GroundMesh.prototype.getClassName = function () {
  55048. return "GroundMesh";
  55049. };
  55050. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  55051. get: function () {
  55052. return Math.min(this._subdivisionsX, this._subdivisionsY);
  55053. },
  55054. enumerable: true,
  55055. configurable: true
  55056. });
  55057. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  55058. get: function () {
  55059. return this._subdivisionsX;
  55060. },
  55061. enumerable: true,
  55062. configurable: true
  55063. });
  55064. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  55065. get: function () {
  55066. return this._subdivisionsY;
  55067. },
  55068. enumerable: true,
  55069. configurable: true
  55070. });
  55071. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  55072. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  55073. this._subdivisionsX = chunksCount;
  55074. this._subdivisionsY = chunksCount;
  55075. this.subdivide(chunksCount);
  55076. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  55077. };
  55078. /**
  55079. * Returns a height (y) value in the Worl system :
  55080. * the ground altitude at the coordinates (x, z) expressed in the World system.
  55081. * Returns the ground y position if (x, z) are outside the ground surface.
  55082. */
  55083. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  55084. var world = this.getWorldMatrix();
  55085. var invMat = BABYLON.Tmp.Matrix[5];
  55086. world.invertToRef(invMat);
  55087. var tmpVect = BABYLON.Tmp.Vector3[8];
  55088. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  55089. x = tmpVect.x;
  55090. z = tmpVect.z;
  55091. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  55092. return this.position.y;
  55093. }
  55094. if (!this._heightQuads || this._heightQuads.length == 0) {
  55095. this._initHeightQuads();
  55096. this._computeHeightQuads();
  55097. }
  55098. var facet = this._getFacetAt(x, z);
  55099. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  55100. // return y in the World system
  55101. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  55102. return tmpVect.y;
  55103. };
  55104. /**
  55105. * Returns a normalized vector (Vector3) orthogonal to the ground
  55106. * at the ground coordinates (x, z) expressed in the World system.
  55107. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  55108. */
  55109. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  55110. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  55111. this.getNormalAtCoordinatesToRef(x, z, normal);
  55112. return normal;
  55113. };
  55114. /**
  55115. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  55116. * at the ground coordinates (x, z) expressed in the World system.
  55117. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  55118. * Returns the GroundMesh.
  55119. */
  55120. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  55121. var world = this.getWorldMatrix();
  55122. var tmpMat = BABYLON.Tmp.Matrix[5];
  55123. world.invertToRef(tmpMat);
  55124. var tmpVect = BABYLON.Tmp.Vector3[8];
  55125. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  55126. x = tmpVect.x;
  55127. z = tmpVect.z;
  55128. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  55129. return this;
  55130. }
  55131. if (!this._heightQuads || this._heightQuads.length == 0) {
  55132. this._initHeightQuads();
  55133. this._computeHeightQuads();
  55134. }
  55135. var facet = this._getFacetAt(x, z);
  55136. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  55137. return this;
  55138. };
  55139. /**
  55140. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  55141. * if the ground has been updated.
  55142. * This can be used in the render loop.
  55143. * Returns the GroundMesh.
  55144. */
  55145. GroundMesh.prototype.updateCoordinateHeights = function () {
  55146. if (!this._heightQuads || this._heightQuads.length == 0) {
  55147. this._initHeightQuads();
  55148. }
  55149. this._computeHeightQuads();
  55150. return this;
  55151. };
  55152. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  55153. GroundMesh.prototype._getFacetAt = function (x, z) {
  55154. // retrieve col and row from x, z coordinates in the ground local system
  55155. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  55156. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  55157. var quad = this._heightQuads[row * this._subdivisionsX + col];
  55158. var facet;
  55159. if (z < quad.slope.x * x + quad.slope.y) {
  55160. facet = quad.facet1;
  55161. }
  55162. else {
  55163. facet = quad.facet2;
  55164. }
  55165. return facet;
  55166. };
  55167. // Creates and populates the heightMap array with "facet" elements :
  55168. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  55169. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  55170. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  55171. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  55172. // Returns the GroundMesh.
  55173. GroundMesh.prototype._initHeightQuads = function () {
  55174. var subdivisionsX = this._subdivisionsX;
  55175. var subdivisionsY = this._subdivisionsY;
  55176. this._heightQuads = new Array();
  55177. for (var row = 0; row < subdivisionsY; row++) {
  55178. for (var col = 0; col < subdivisionsX; col++) {
  55179. 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) };
  55180. this._heightQuads[row * subdivisionsX + col] = quad;
  55181. }
  55182. }
  55183. return this;
  55184. };
  55185. // Compute each quad element values and update the the heightMap array :
  55186. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  55187. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  55188. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  55189. // Returns the GroundMesh.
  55190. GroundMesh.prototype._computeHeightQuads = function () {
  55191. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  55192. if (!positions) {
  55193. return this;
  55194. }
  55195. var v1 = BABYLON.Tmp.Vector3[3];
  55196. var v2 = BABYLON.Tmp.Vector3[2];
  55197. var v3 = BABYLON.Tmp.Vector3[1];
  55198. var v4 = BABYLON.Tmp.Vector3[0];
  55199. var v1v2 = BABYLON.Tmp.Vector3[4];
  55200. var v1v3 = BABYLON.Tmp.Vector3[5];
  55201. var v1v4 = BABYLON.Tmp.Vector3[6];
  55202. var norm1 = BABYLON.Tmp.Vector3[7];
  55203. var norm2 = BABYLON.Tmp.Vector3[8];
  55204. var i = 0;
  55205. var j = 0;
  55206. var k = 0;
  55207. var cd = 0; // 2D slope coefficient : z = cd * x + h
  55208. var h = 0;
  55209. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  55210. var d2 = 0;
  55211. var subdivisionsX = this._subdivisionsX;
  55212. var subdivisionsY = this._subdivisionsY;
  55213. for (var row = 0; row < subdivisionsY; row++) {
  55214. for (var col = 0; col < subdivisionsX; col++) {
  55215. i = col * 3;
  55216. j = row * (subdivisionsX + 1) * 3;
  55217. k = (row + 1) * (subdivisionsX + 1) * 3;
  55218. v1.x = positions[j + i];
  55219. v1.y = positions[j + i + 1];
  55220. v1.z = positions[j + i + 2];
  55221. v2.x = positions[j + i + 3];
  55222. v2.y = positions[j + i + 4];
  55223. v2.z = positions[j + i + 5];
  55224. v3.x = positions[k + i];
  55225. v3.y = positions[k + i + 1];
  55226. v3.z = positions[k + i + 2];
  55227. v4.x = positions[k + i + 3];
  55228. v4.y = positions[k + i + 4];
  55229. v4.z = positions[k + i + 5];
  55230. // 2D slope V1V4
  55231. cd = (v4.z - v1.z) / (v4.x - v1.x);
  55232. h = v1.z - cd * v1.x; // v1 belongs to the slope
  55233. // facet equations :
  55234. // we compute each facet normal vector
  55235. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  55236. // we compute the value d by applying the equation to v1 which belongs to the plane
  55237. // then we store the facet equation in a Vector4
  55238. v2.subtractToRef(v1, v1v2);
  55239. v3.subtractToRef(v1, v1v3);
  55240. v4.subtractToRef(v1, v1v4);
  55241. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  55242. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  55243. norm1.normalize();
  55244. norm2.normalize();
  55245. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  55246. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  55247. var quad = this._heightQuads[row * subdivisionsX + col];
  55248. quad.slope.copyFromFloats(cd, h);
  55249. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  55250. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  55251. }
  55252. }
  55253. return this;
  55254. };
  55255. GroundMesh.prototype.serialize = function (serializationObject) {
  55256. _super.prototype.serialize.call(this, serializationObject);
  55257. serializationObject.subdivisionsX = this._subdivisionsX;
  55258. serializationObject.subdivisionsY = this._subdivisionsY;
  55259. serializationObject.minX = this._minX;
  55260. serializationObject.maxX = this._maxX;
  55261. serializationObject.minZ = this._minZ;
  55262. serializationObject.maxZ = this._maxZ;
  55263. serializationObject.width = this._width;
  55264. serializationObject.height = this._height;
  55265. };
  55266. GroundMesh.Parse = function (parsedMesh, scene) {
  55267. var result = new GroundMesh(parsedMesh.name, scene);
  55268. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  55269. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  55270. result._minX = parsedMesh.minX;
  55271. result._maxX = parsedMesh.maxX;
  55272. result._minZ = parsedMesh.minZ;
  55273. result._maxZ = parsedMesh.maxZ;
  55274. result._width = parsedMesh.width;
  55275. result._height = parsedMesh.height;
  55276. return result;
  55277. };
  55278. return GroundMesh;
  55279. }(BABYLON.Mesh));
  55280. BABYLON.GroundMesh = GroundMesh;
  55281. })(BABYLON || (BABYLON = {}));
  55282. //# sourceMappingURL=babylon.groundMesh.js.map
  55283. var BABYLON;
  55284. (function (BABYLON) {
  55285. /**
  55286. * Creates an instance based on a source mesh.
  55287. */
  55288. var InstancedMesh = /** @class */ (function (_super) {
  55289. __extends(InstancedMesh, _super);
  55290. function InstancedMesh(name, source) {
  55291. var _this = _super.call(this, name, source.getScene()) || this;
  55292. source.instances.push(_this);
  55293. _this._sourceMesh = source;
  55294. _this.position.copyFrom(source.position);
  55295. _this.rotation.copyFrom(source.rotation);
  55296. _this.scaling.copyFrom(source.scaling);
  55297. if (source.rotationQuaternion) {
  55298. _this.rotationQuaternion = source.rotationQuaternion.clone();
  55299. }
  55300. _this.infiniteDistance = source.infiniteDistance;
  55301. _this.setPivotMatrix(source.getPivotMatrix());
  55302. _this.refreshBoundingInfo();
  55303. _this._syncSubMeshes();
  55304. return _this;
  55305. }
  55306. /**
  55307. * Returns the string "InstancedMesh".
  55308. */
  55309. InstancedMesh.prototype.getClassName = function () {
  55310. return "InstancedMesh";
  55311. };
  55312. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  55313. // Methods
  55314. get: function () {
  55315. return this._sourceMesh.receiveShadows;
  55316. },
  55317. enumerable: true,
  55318. configurable: true
  55319. });
  55320. Object.defineProperty(InstancedMesh.prototype, "material", {
  55321. get: function () {
  55322. return this._sourceMesh.material;
  55323. },
  55324. enumerable: true,
  55325. configurable: true
  55326. });
  55327. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  55328. get: function () {
  55329. return this._sourceMesh.visibility;
  55330. },
  55331. enumerable: true,
  55332. configurable: true
  55333. });
  55334. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  55335. get: function () {
  55336. return this._sourceMesh.skeleton;
  55337. },
  55338. enumerable: true,
  55339. configurable: true
  55340. });
  55341. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  55342. get: function () {
  55343. return this._sourceMesh.renderingGroupId;
  55344. },
  55345. set: function (value) {
  55346. if (!this._sourceMesh || value === this._sourceMesh.renderingGroupId) {
  55347. return;
  55348. }
  55349. //no-op with warning
  55350. BABYLON.Tools.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene");
  55351. },
  55352. enumerable: true,
  55353. configurable: true
  55354. });
  55355. /**
  55356. * Returns the total number of vertices (integer).
  55357. */
  55358. InstancedMesh.prototype.getTotalVertices = function () {
  55359. return this._sourceMesh.getTotalVertices();
  55360. };
  55361. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  55362. get: function () {
  55363. return this._sourceMesh;
  55364. },
  55365. enumerable: true,
  55366. configurable: true
  55367. });
  55368. /**
  55369. * Is this node ready to be used/rendered
  55370. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  55371. * @return {boolean} is it ready
  55372. */
  55373. InstancedMesh.prototype.isReady = function (completeCheck) {
  55374. if (completeCheck === void 0) { completeCheck = false; }
  55375. return this._sourceMesh.isReady(completeCheck, true);
  55376. };
  55377. /**
  55378. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  55379. */
  55380. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  55381. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  55382. };
  55383. /**
  55384. * Sets the vertex data of the mesh geometry for the requested `kind`.
  55385. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  55386. * The `data` are either a numeric array either a Float32Array.
  55387. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  55388. * 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).
  55389. * Note that a new underlying VertexBuffer object is created each call.
  55390. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  55391. *
  55392. * Possible `kind` values :
  55393. * - BABYLON.VertexBuffer.PositionKind
  55394. * - BABYLON.VertexBuffer.UVKind
  55395. * - BABYLON.VertexBuffer.UV2Kind
  55396. * - BABYLON.VertexBuffer.UV3Kind
  55397. * - BABYLON.VertexBuffer.UV4Kind
  55398. * - BABYLON.VertexBuffer.UV5Kind
  55399. * - BABYLON.VertexBuffer.UV6Kind
  55400. * - BABYLON.VertexBuffer.ColorKind
  55401. * - BABYLON.VertexBuffer.MatricesIndicesKind
  55402. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  55403. * - BABYLON.VertexBuffer.MatricesWeightsKind
  55404. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  55405. *
  55406. * Returns the Mesh.
  55407. */
  55408. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  55409. if (this.sourceMesh) {
  55410. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  55411. }
  55412. return this.sourceMesh;
  55413. };
  55414. /**
  55415. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  55416. * If the mesh has no geometry, it is simply returned as it is.
  55417. * The `data` are either a numeric array either a Float32Array.
  55418. * No new underlying VertexBuffer object is created.
  55419. * 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.
  55420. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  55421. *
  55422. * Possible `kind` values :
  55423. * - BABYLON.VertexBuffer.PositionKind
  55424. * - BABYLON.VertexBuffer.UVKind
  55425. * - BABYLON.VertexBuffer.UV2Kind
  55426. * - BABYLON.VertexBuffer.UV3Kind
  55427. * - BABYLON.VertexBuffer.UV4Kind
  55428. * - BABYLON.VertexBuffer.UV5Kind
  55429. * - BABYLON.VertexBuffer.UV6Kind
  55430. * - BABYLON.VertexBuffer.ColorKind
  55431. * - BABYLON.VertexBuffer.MatricesIndicesKind
  55432. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  55433. * - BABYLON.VertexBuffer.MatricesWeightsKind
  55434. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  55435. *
  55436. * Returns the Mesh.
  55437. */
  55438. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  55439. if (this.sourceMesh) {
  55440. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  55441. }
  55442. return this.sourceMesh;
  55443. };
  55444. /**
  55445. * Sets the mesh indices.
  55446. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  55447. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  55448. * This method creates a new index buffer each call.
  55449. * Returns the Mesh.
  55450. */
  55451. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  55452. if (totalVertices === void 0) { totalVertices = null; }
  55453. if (this.sourceMesh) {
  55454. this.sourceMesh.setIndices(indices, totalVertices);
  55455. }
  55456. return this.sourceMesh;
  55457. };
  55458. /**
  55459. * Boolean : True if the mesh owns the requested kind of data.
  55460. */
  55461. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  55462. return this._sourceMesh.isVerticesDataPresent(kind);
  55463. };
  55464. /**
  55465. * Returns an array of indices (IndicesArray).
  55466. */
  55467. InstancedMesh.prototype.getIndices = function () {
  55468. return this._sourceMesh.getIndices();
  55469. };
  55470. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  55471. get: function () {
  55472. return this._sourceMesh._positions;
  55473. },
  55474. enumerable: true,
  55475. configurable: true
  55476. });
  55477. /**
  55478. * Sets a new updated BoundingInfo to the mesh.
  55479. * Returns the mesh.
  55480. */
  55481. InstancedMesh.prototype.refreshBoundingInfo = function () {
  55482. var meshBB = this._sourceMesh.getBoundingInfo();
  55483. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  55484. this._updateBoundingInfo();
  55485. return this;
  55486. };
  55487. InstancedMesh.prototype._preActivate = function () {
  55488. if (this._currentLOD) {
  55489. this._currentLOD._preActivate();
  55490. }
  55491. return this;
  55492. };
  55493. InstancedMesh.prototype._activate = function (renderId) {
  55494. if (this._currentLOD) {
  55495. this._currentLOD._registerInstanceForRenderId(this, renderId);
  55496. }
  55497. return this;
  55498. };
  55499. /**
  55500. * Returns the current associated LOD AbstractMesh.
  55501. */
  55502. InstancedMesh.prototype.getLOD = function (camera) {
  55503. if (!camera) {
  55504. return this;
  55505. }
  55506. var boundingInfo = this.getBoundingInfo();
  55507. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  55508. if (this._currentLOD === this.sourceMesh) {
  55509. return this;
  55510. }
  55511. return this._currentLOD;
  55512. };
  55513. InstancedMesh.prototype._syncSubMeshes = function () {
  55514. this.releaseSubMeshes();
  55515. if (this._sourceMesh.subMeshes) {
  55516. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  55517. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  55518. }
  55519. }
  55520. return this;
  55521. };
  55522. InstancedMesh.prototype._generatePointsArray = function () {
  55523. return this._sourceMesh._generatePointsArray();
  55524. };
  55525. /**
  55526. * Creates a new InstancedMesh from the current mesh.
  55527. * - name (string) : the cloned mesh name
  55528. * - newParent (optional Node) : the optional Node to parent the clone to.
  55529. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  55530. *
  55531. * Returns the clone.
  55532. */
  55533. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  55534. var result = this._sourceMesh.createInstance(name);
  55535. // Deep copy
  55536. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  55537. // Bounding info
  55538. this.refreshBoundingInfo();
  55539. // Parent
  55540. if (newParent) {
  55541. result.parent = newParent;
  55542. }
  55543. if (!doNotCloneChildren) {
  55544. // Children
  55545. for (var index = 0; index < this.getScene().meshes.length; index++) {
  55546. var mesh = this.getScene().meshes[index];
  55547. if (mesh.parent === this) {
  55548. mesh.clone(mesh.name, result);
  55549. }
  55550. }
  55551. }
  55552. result.computeWorldMatrix(true);
  55553. return result;
  55554. };
  55555. /**
  55556. * Disposes the InstancedMesh.
  55557. * Returns nothing.
  55558. */
  55559. InstancedMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  55560. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  55561. // Remove from mesh
  55562. var index = this._sourceMesh.instances.indexOf(this);
  55563. this._sourceMesh.instances.splice(index, 1);
  55564. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  55565. };
  55566. return InstancedMesh;
  55567. }(BABYLON.AbstractMesh));
  55568. BABYLON.InstancedMesh = InstancedMesh;
  55569. })(BABYLON || (BABYLON = {}));
  55570. //# sourceMappingURL=babylon.instancedMesh.js.map
  55571. var BABYLON;
  55572. (function (BABYLON) {
  55573. var LinesMesh = /** @class */ (function (_super) {
  55574. __extends(LinesMesh, _super);
  55575. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  55576. if (scene === void 0) { scene = null; }
  55577. if (parent === void 0) { parent = null; }
  55578. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  55579. _this.useVertexColor = useVertexColor;
  55580. _this.useVertexAlpha = useVertexAlpha;
  55581. _this.color = new BABYLON.Color3(1, 1, 1);
  55582. _this.alpha = 1;
  55583. if (source) {
  55584. _this.color = source.color.clone();
  55585. _this.alpha = source.alpha;
  55586. _this.useVertexColor = source.useVertexColor;
  55587. _this.useVertexAlpha = source.useVertexAlpha;
  55588. }
  55589. _this._intersectionThreshold = 0.1;
  55590. var defines = [];
  55591. var options = {
  55592. attributes: [BABYLON.VertexBuffer.PositionKind],
  55593. uniforms: ["world", "viewProjection"],
  55594. needAlphaBlending: true,
  55595. defines: defines
  55596. };
  55597. if (useVertexAlpha === false) {
  55598. options.needAlphaBlending = false;
  55599. }
  55600. if (!useVertexColor) {
  55601. options.uniforms.push("color");
  55602. }
  55603. else {
  55604. options.defines.push("#define VERTEXCOLOR");
  55605. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  55606. }
  55607. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  55608. return _this;
  55609. }
  55610. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  55611. /**
  55612. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  55613. * This margin is expressed in world space coordinates, so its value may vary.
  55614. * Default value is 0.1
  55615. * @returns the intersection Threshold value.
  55616. */
  55617. get: function () {
  55618. return this._intersectionThreshold;
  55619. },
  55620. /**
  55621. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  55622. * This margin is expressed in world space coordinates, so its value may vary.
  55623. * @param value the new threshold to apply
  55624. */
  55625. set: function (value) {
  55626. if (this._intersectionThreshold === value) {
  55627. return;
  55628. }
  55629. this._intersectionThreshold = value;
  55630. if (this.geometry) {
  55631. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  55632. }
  55633. },
  55634. enumerable: true,
  55635. configurable: true
  55636. });
  55637. /**
  55638. * Returns the string "LineMesh"
  55639. */
  55640. LinesMesh.prototype.getClassName = function () {
  55641. return "LinesMesh";
  55642. };
  55643. Object.defineProperty(LinesMesh.prototype, "material", {
  55644. get: function () {
  55645. return this._colorShader;
  55646. },
  55647. set: function (value) {
  55648. // Do nothing
  55649. },
  55650. enumerable: true,
  55651. configurable: true
  55652. });
  55653. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  55654. get: function () {
  55655. return false;
  55656. },
  55657. enumerable: true,
  55658. configurable: true
  55659. });
  55660. LinesMesh.prototype.createInstance = function (name) {
  55661. throw new Error("LinesMeshes do not support createInstance.");
  55662. };
  55663. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  55664. if (!this._geometry) {
  55665. return this;
  55666. }
  55667. // VBOs
  55668. this._geometry._bind(this._colorShader.getEffect());
  55669. // Color
  55670. if (!this.useVertexColor) {
  55671. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  55672. }
  55673. return this;
  55674. };
  55675. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  55676. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  55677. return this;
  55678. }
  55679. var engine = this.getScene().getEngine();
  55680. // Draw order
  55681. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  55682. return this;
  55683. };
  55684. LinesMesh.prototype.dispose = function (doNotRecurse) {
  55685. this._colorShader.dispose();
  55686. _super.prototype.dispose.call(this, doNotRecurse);
  55687. };
  55688. /**
  55689. * Returns a new LineMesh object cloned from the current one.
  55690. */
  55691. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  55692. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  55693. };
  55694. return LinesMesh;
  55695. }(BABYLON.Mesh));
  55696. BABYLON.LinesMesh = LinesMesh;
  55697. })(BABYLON || (BABYLON = {}));
  55698. //# sourceMappingURL=babylon.linesMesh.js.map
  55699. var BABYLON;
  55700. (function (BABYLON) {
  55701. var MeshBuilder = /** @class */ (function () {
  55702. function MeshBuilder() {
  55703. }
  55704. MeshBuilder.updateSideOrientation = function (orientation) {
  55705. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  55706. return BABYLON.Mesh.DOUBLESIDE;
  55707. }
  55708. if (orientation === undefined || orientation === null) {
  55709. return BABYLON.Mesh.FRONTSIDE;
  55710. }
  55711. return orientation;
  55712. };
  55713. /**
  55714. * Creates a box mesh.
  55715. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  55716. * The parameter `size` sets the size (float) of each box side (default 1).
  55717. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  55718. * 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).
  55719. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  55720. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55721. * 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).
  55722. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55723. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55724. */
  55725. MeshBuilder.CreateBox = function (name, options, scene) {
  55726. if (scene === void 0) { scene = null; }
  55727. var box = new BABYLON.Mesh(name, scene);
  55728. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55729. box._originalBuilderSideOrientation = options.sideOrientation;
  55730. var vertexData = BABYLON.VertexData.CreateBox(options);
  55731. vertexData.applyToMesh(box, options.updatable);
  55732. return box;
  55733. };
  55734. /**
  55735. * Creates a sphere mesh.
  55736. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  55737. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  55738. * 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`).
  55739. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  55740. * 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
  55741. * 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).
  55742. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55743. * 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).
  55744. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55745. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55746. */
  55747. MeshBuilder.CreateSphere = function (name, options, scene) {
  55748. var sphere = new BABYLON.Mesh(name, scene);
  55749. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55750. sphere._originalBuilderSideOrientation = options.sideOrientation;
  55751. var vertexData = BABYLON.VertexData.CreateSphere(options);
  55752. vertexData.applyToMesh(sphere, options.updatable);
  55753. return sphere;
  55754. };
  55755. /**
  55756. * Creates a plane polygonal mesh. By default, this is a disc.
  55757. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  55758. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  55759. * 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.
  55760. * 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
  55761. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55762. * 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).
  55763. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55764. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55765. */
  55766. MeshBuilder.CreateDisc = function (name, options, scene) {
  55767. if (scene === void 0) { scene = null; }
  55768. var disc = new BABYLON.Mesh(name, scene);
  55769. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55770. disc._originalBuilderSideOrientation = options.sideOrientation;
  55771. var vertexData = BABYLON.VertexData.CreateDisc(options);
  55772. vertexData.applyToMesh(disc, options.updatable);
  55773. return disc;
  55774. };
  55775. /**
  55776. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  55777. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  55778. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  55779. * 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`).
  55780. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  55781. * 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.
  55782. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55783. * 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).
  55784. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55785. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55786. */
  55787. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  55788. var sphere = new BABYLON.Mesh(name, scene);
  55789. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55790. sphere._originalBuilderSideOrientation = options.sideOrientation;
  55791. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  55792. vertexData.applyToMesh(sphere, options.updatable);
  55793. return sphere;
  55794. };
  55795. ;
  55796. /**
  55797. * Creates a ribbon mesh.
  55798. * 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.
  55799. *
  55800. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  55801. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  55802. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  55803. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  55804. * 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.
  55805. * 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.
  55806. * 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
  55807. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55808. * 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).
  55809. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55810. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  55811. * 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.
  55812. * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values.
  55813. * 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
  55814. * if you set `closePath` to `true`, there's one extra vertex per path in the geometry.
  55815. * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time.
  55816. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55817. */
  55818. MeshBuilder.CreateRibbon = function (name, options, scene) {
  55819. if (scene === void 0) { scene = null; }
  55820. var pathArray = options.pathArray;
  55821. var closeArray = options.closeArray;
  55822. var closePath = options.closePath;
  55823. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55824. var instance = options.instance;
  55825. var updatable = options.updatable;
  55826. if (instance) {
  55827. // positionFunction : ribbon case
  55828. // only pathArray and sideOrientation parameters are taken into account for positions update
  55829. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  55830. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  55831. var positionFunction = function (positions) {
  55832. var minlg = pathArray[0].length;
  55833. var i = 0;
  55834. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  55835. for (var si = 1; si <= ns; si++) {
  55836. for (var p = 0; p < pathArray.length; p++) {
  55837. var path = pathArray[p];
  55838. var l = path.length;
  55839. minlg = (minlg < l) ? minlg : l;
  55840. var j = 0;
  55841. while (j < minlg) {
  55842. positions[i] = path[j].x;
  55843. positions[i + 1] = path[j].y;
  55844. positions[i + 2] = path[j].z;
  55845. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  55846. BABYLON.Tmp.Vector3[0].x = path[j].x;
  55847. }
  55848. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  55849. BABYLON.Tmp.Vector3[1].x = path[j].x;
  55850. }
  55851. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  55852. BABYLON.Tmp.Vector3[0].y = path[j].y;
  55853. }
  55854. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  55855. BABYLON.Tmp.Vector3[1].y = path[j].y;
  55856. }
  55857. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  55858. BABYLON.Tmp.Vector3[0].z = path[j].z;
  55859. }
  55860. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  55861. BABYLON.Tmp.Vector3[1].z = path[j].z;
  55862. }
  55863. j++;
  55864. i += 3;
  55865. }
  55866. if (instance._closePath) {
  55867. positions[i] = path[0].x;
  55868. positions[i + 1] = path[0].y;
  55869. positions[i + 2] = path[0].z;
  55870. i += 3;
  55871. }
  55872. }
  55873. }
  55874. };
  55875. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  55876. positionFunction(positions);
  55877. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  55878. instance._boundingInfo.update(instance._worldMatrix);
  55879. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  55880. if (options.colors) {
  55881. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  55882. for (var c = 0; c < options.colors.length; c++) {
  55883. colors[c * 4] = options.colors[c].r;
  55884. colors[c * 4 + 1] = options.colors[c].g;
  55885. colors[c * 4 + 2] = options.colors[c].b;
  55886. colors[c * 4 + 3] = options.colors[c].a;
  55887. }
  55888. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  55889. }
  55890. if (options.uvs) {
  55891. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  55892. for (var i = 0; i < options.uvs.length; i++) {
  55893. uvs[i * 2] = options.uvs[i].x;
  55894. uvs[i * 2 + 1] = options.uvs[i].y;
  55895. }
  55896. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  55897. }
  55898. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  55899. var indices = instance.getIndices();
  55900. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  55901. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  55902. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  55903. if (instance._closePath) {
  55904. var indexFirst = 0;
  55905. var indexLast = 0;
  55906. for (var p = 0; p < pathArray.length; p++) {
  55907. indexFirst = instance._idx[p] * 3;
  55908. if (p + 1 < pathArray.length) {
  55909. indexLast = (instance._idx[p + 1] - 1) * 3;
  55910. }
  55911. else {
  55912. indexLast = normals.length - 3;
  55913. }
  55914. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  55915. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  55916. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  55917. normals[indexLast] = normals[indexFirst];
  55918. normals[indexLast + 1] = normals[indexFirst + 1];
  55919. normals[indexLast + 2] = normals[indexFirst + 2];
  55920. }
  55921. }
  55922. if (!(instance.areNormalsFrozen)) {
  55923. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  55924. }
  55925. }
  55926. return instance;
  55927. }
  55928. else {
  55929. var ribbon = new BABYLON.Mesh(name, scene);
  55930. ribbon._originalBuilderSideOrientation = sideOrientation;
  55931. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  55932. if (closePath) {
  55933. ribbon._idx = vertexData._idx;
  55934. }
  55935. ribbon._closePath = closePath;
  55936. ribbon._closeArray = closeArray;
  55937. vertexData.applyToMesh(ribbon, updatable);
  55938. return ribbon;
  55939. }
  55940. };
  55941. /**
  55942. * Creates a cylinder or a cone mesh.
  55943. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  55944. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  55945. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  55946. * 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.
  55947. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  55948. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  55949. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  55950. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  55951. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  55952. * 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).
  55953. * 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
  55954. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  55955. * 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
  55956. * 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.
  55957. * If `enclose` is false, a ring surface is one element.
  55958. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  55959. * 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
  55960. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55961. * 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).
  55962. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55963. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55964. */
  55965. MeshBuilder.CreateCylinder = function (name, options, scene) {
  55966. var cylinder = new BABYLON.Mesh(name, scene);
  55967. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55968. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  55969. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  55970. vertexData.applyToMesh(cylinder, options.updatable);
  55971. return cylinder;
  55972. };
  55973. /**
  55974. * Creates a torus mesh.
  55975. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  55976. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  55977. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  55978. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  55979. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55980. * 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).
  55981. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55982. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55983. */
  55984. MeshBuilder.CreateTorus = function (name, options, scene) {
  55985. var torus = new BABYLON.Mesh(name, scene);
  55986. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55987. torus._originalBuilderSideOrientation = options.sideOrientation;
  55988. var vertexData = BABYLON.VertexData.CreateTorus(options);
  55989. vertexData.applyToMesh(torus, options.updatable);
  55990. return torus;
  55991. };
  55992. /**
  55993. * Creates a torus knot mesh.
  55994. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  55995. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  55996. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  55997. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  55998. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  55999. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56000. * 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).
  56001. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56002. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56003. */
  56004. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  56005. var torusKnot = new BABYLON.Mesh(name, scene);
  56006. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56007. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  56008. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  56009. vertexData.applyToMesh(torusKnot, options.updatable);
  56010. return torusKnot;
  56011. };
  56012. /**
  56013. * Creates a line system mesh.
  56014. * A line system is a pool of many lines gathered in a single mesh.
  56015. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  56016. * 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.
  56017. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  56018. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  56019. * 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
  56020. * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point.
  56021. * The optional parameter `useVertexAlpha' is to be set to `false` (default `true`) when you don't need the alpha blending (faster).
  56022. * 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
  56023. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  56024. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56025. */
  56026. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  56027. var instance = options.instance;
  56028. var lines = options.lines;
  56029. var colors = options.colors;
  56030. if (instance) {
  56031. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  56032. var vertexColor;
  56033. var lineColors;
  56034. if (colors) {
  56035. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  56036. }
  56037. var i = 0;
  56038. var c = 0;
  56039. for (var l = 0; l < lines.length; l++) {
  56040. var points = lines[l];
  56041. for (var p = 0; p < points.length; p++) {
  56042. positions[i] = points[p].x;
  56043. positions[i + 1] = points[p].y;
  56044. positions[i + 2] = points[p].z;
  56045. if (colors && vertexColor) {
  56046. lineColors = colors[l];
  56047. vertexColor[c] = lineColors[p].r;
  56048. vertexColor[c + 1] = lineColors[p].g;
  56049. vertexColor[c + 2] = lineColors[p].b;
  56050. vertexColor[c + 3] = lineColors[p].a;
  56051. c += 4;
  56052. }
  56053. i += 3;
  56054. }
  56055. }
  56056. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  56057. if (colors && vertexColor) {
  56058. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  56059. }
  56060. return instance;
  56061. }
  56062. // line system creation
  56063. var useVertexColor = (colors) ? true : false;
  56064. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  56065. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  56066. vertexData.applyToMesh(lineSystem, options.updatable);
  56067. return lineSystem;
  56068. };
  56069. /**
  56070. * Creates a line mesh.
  56071. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  56072. * 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.
  56073. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  56074. * The parameter `points` is an array successive Vector3.
  56075. * 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
  56076. * The optional parameter `colors` is an array of successive Color4, one per line point.
  56077. * The optional parameter `useVertexAlpha' is to be set to `false` (default `true`) when you don't need alpha blending (faster).
  56078. * When updating an instance, remember that only point positions can change, not the number of points.
  56079. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56080. */
  56081. MeshBuilder.CreateLines = function (name, options, scene) {
  56082. if (scene === void 0) { scene = null; }
  56083. var colors = (options.colors) ? [options.colors] : null;
  56084. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  56085. return lines;
  56086. };
  56087. /**
  56088. * Creates a dashed line mesh.
  56089. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  56090. * 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.
  56091. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  56092. * The parameter `points` is an array successive Vector3.
  56093. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  56094. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  56095. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  56096. * 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
  56097. * When updating an instance, remember that only point positions can change, not the number of points.
  56098. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56099. */
  56100. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  56101. if (scene === void 0) { scene = null; }
  56102. var points = options.points;
  56103. var instance = options.instance;
  56104. var gapSize = options.gapSize || 1;
  56105. var dashSize = options.dashSize || 3;
  56106. if (instance) {
  56107. var positionFunction = function (positions) {
  56108. var curvect = BABYLON.Vector3.Zero();
  56109. var nbSeg = positions.length / 6;
  56110. var lg = 0;
  56111. var nb = 0;
  56112. var shft = 0;
  56113. var dashshft = 0;
  56114. var curshft = 0;
  56115. var p = 0;
  56116. var i = 0;
  56117. var j = 0;
  56118. for (i = 0; i < points.length - 1; i++) {
  56119. points[i + 1].subtractToRef(points[i], curvect);
  56120. lg += curvect.length();
  56121. }
  56122. shft = lg / nbSeg;
  56123. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  56124. for (i = 0; i < points.length - 1; i++) {
  56125. points[i + 1].subtractToRef(points[i], curvect);
  56126. nb = Math.floor(curvect.length() / shft);
  56127. curvect.normalize();
  56128. j = 0;
  56129. while (j < nb && p < positions.length) {
  56130. curshft = shft * j;
  56131. positions[p] = points[i].x + curshft * curvect.x;
  56132. positions[p + 1] = points[i].y + curshft * curvect.y;
  56133. positions[p + 2] = points[i].z + curshft * curvect.z;
  56134. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  56135. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  56136. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  56137. p += 6;
  56138. j++;
  56139. }
  56140. }
  56141. while (p < positions.length) {
  56142. positions[p] = points[i].x;
  56143. positions[p + 1] = points[i].y;
  56144. positions[p + 2] = points[i].z;
  56145. p += 3;
  56146. }
  56147. };
  56148. instance.updateMeshPositions(positionFunction, false);
  56149. return instance;
  56150. }
  56151. // dashed lines creation
  56152. var dashedLines = new BABYLON.LinesMesh(name, scene);
  56153. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  56154. vertexData.applyToMesh(dashedLines, options.updatable);
  56155. dashedLines.dashSize = dashSize;
  56156. dashedLines.gapSize = gapSize;
  56157. return dashedLines;
  56158. };
  56159. /**
  56160. * Creates an extruded shape mesh.
  56161. * 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.
  56162. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  56163. *
  56164. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  56165. * 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
  56166. * extruded along the Z axis.
  56167. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  56168. * 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.
  56169. * The parameter `scale` (float, default 1) is the value to scale the shape.
  56170. * 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
  56171. * 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
  56172. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  56173. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56174. * 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).
  56175. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56176. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  56177. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56178. */
  56179. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  56180. if (scene === void 0) { scene = null; }
  56181. var path = options.path;
  56182. var shape = options.shape;
  56183. var scale = options.scale || 1;
  56184. var rotation = options.rotation || 0;
  56185. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  56186. var updatable = options.updatable;
  56187. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56188. var instance = options.instance || null;
  56189. var invertUV = options.invertUV || false;
  56190. 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);
  56191. };
  56192. /**
  56193. * Creates an custom extruded shape mesh.
  56194. * 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.
  56195. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  56196. *
  56197. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  56198. * 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
  56199. * extruded along the Z axis.
  56200. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  56201. * 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
  56202. * and the distance of this point from the begining of the path :
  56203. * ```javascript
  56204. * var rotationFunction = function(i, distance) {
  56205. * // do things
  56206. * return rotationValue; }
  56207. * ```
  56208. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  56209. * 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
  56210. * and the distance of this point from the begining of the path :
  56211. * ```javascript
  56212. * var scaleFunction = function(i, distance) {
  56213. * // do things
  56214. * return scaleValue;}
  56215. * ```
  56216. * It must returns a float value that will be the scale value applied to the shape on each path point.
  56217. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  56218. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  56219. * 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
  56220. * 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
  56221. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  56222. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56223. * 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).
  56224. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56225. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  56226. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56227. */
  56228. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  56229. var path = options.path;
  56230. var shape = options.shape;
  56231. var scaleFunction = options.scaleFunction || (function () { return 1; });
  56232. var rotationFunction = options.rotationFunction || (function () { return 0; });
  56233. var ribbonCloseArray = options.ribbonCloseArray || false;
  56234. var ribbonClosePath = options.ribbonClosePath || false;
  56235. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  56236. var updatable = options.updatable;
  56237. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56238. var instance = options.instance;
  56239. var invertUV = options.invertUV || false;
  56240. 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);
  56241. };
  56242. /**
  56243. * Creates lathe mesh.
  56244. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  56245. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  56246. *
  56247. * 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
  56248. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  56249. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  56250. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  56251. * 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.
  56252. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  56253. * 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
  56254. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56255. * 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).
  56256. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56257. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  56258. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56259. */
  56260. MeshBuilder.CreateLathe = function (name, options, scene) {
  56261. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  56262. var closed = (options.closed === undefined) ? true : options.closed;
  56263. var shape = options.shape;
  56264. var radius = options.radius || 1;
  56265. var tessellation = options.tessellation || 64;
  56266. var updatable = options.updatable;
  56267. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56268. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  56269. var pi2 = Math.PI * 2;
  56270. var paths = new Array();
  56271. var invertUV = options.invertUV || false;
  56272. var i = 0;
  56273. var p = 0;
  56274. var step = pi2 / tessellation * arc;
  56275. var rotated;
  56276. var path = new Array();
  56277. ;
  56278. for (i = 0; i <= tessellation; i++) {
  56279. var path = [];
  56280. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  56281. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  56282. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  56283. }
  56284. for (p = 0; p < shape.length; p++) {
  56285. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  56286. path.push(rotated);
  56287. }
  56288. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  56289. 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));
  56290. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  56291. }
  56292. paths.push(path);
  56293. }
  56294. // lathe ribbon
  56295. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  56296. return lathe;
  56297. };
  56298. /**
  56299. * Creates a plane mesh.
  56300. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  56301. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  56302. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  56303. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  56304. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56305. * 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).
  56306. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56307. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56308. */
  56309. MeshBuilder.CreatePlane = function (name, options, scene) {
  56310. var plane = new BABYLON.Mesh(name, scene);
  56311. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56312. plane._originalBuilderSideOrientation = options.sideOrientation;
  56313. var vertexData = BABYLON.VertexData.CreatePlane(options);
  56314. vertexData.applyToMesh(plane, options.updatable);
  56315. if (options.sourcePlane) {
  56316. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  56317. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  56318. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  56319. plane.rotate(vectorProduct, product);
  56320. }
  56321. return plane;
  56322. };
  56323. /**
  56324. * Creates a ground mesh.
  56325. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  56326. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  56327. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  56328. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56329. */
  56330. MeshBuilder.CreateGround = function (name, options, scene) {
  56331. var ground = new BABYLON.GroundMesh(name, scene);
  56332. ground._setReady(false);
  56333. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  56334. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  56335. ground._width = options.width || 1;
  56336. ground._height = options.height || 1;
  56337. ground._maxX = ground._width / 2;
  56338. ground._maxZ = ground._height / 2;
  56339. ground._minX = -ground._maxX;
  56340. ground._minZ = -ground._maxZ;
  56341. var vertexData = BABYLON.VertexData.CreateGround(options);
  56342. vertexData.applyToMesh(ground, options.updatable);
  56343. ground._setReady(true);
  56344. return ground;
  56345. };
  56346. /**
  56347. * Creates a tiled ground mesh.
  56348. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  56349. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  56350. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  56351. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  56352. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  56353. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  56354. * numbers of subdivisions on the ground width and height of each tile.
  56355. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56356. */
  56357. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  56358. var tiledGround = new BABYLON.Mesh(name, scene);
  56359. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  56360. vertexData.applyToMesh(tiledGround, options.updatable);
  56361. return tiledGround;
  56362. };
  56363. /**
  56364. * Creates a ground mesh from a height map.
  56365. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  56366. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  56367. * The parameter `url` sets the URL of the height map image resource.
  56368. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  56369. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  56370. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  56371. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  56372. * 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.
  56373. * 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).
  56374. * This function is passed the newly built mesh :
  56375. * ```javascript
  56376. * function(mesh) { // do things
  56377. * return; }
  56378. * ```
  56379. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56380. */
  56381. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  56382. var width = options.width || 10.0;
  56383. var height = options.height || 10.0;
  56384. var subdivisions = options.subdivisions || 1 | 0;
  56385. var minHeight = options.minHeight || 0.0;
  56386. var maxHeight = options.maxHeight || 1.0;
  56387. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  56388. var updatable = options.updatable;
  56389. var onReady = options.onReady;
  56390. var ground = new BABYLON.GroundMesh(name, scene);
  56391. ground._subdivisionsX = subdivisions;
  56392. ground._subdivisionsY = subdivisions;
  56393. ground._width = width;
  56394. ground._height = height;
  56395. ground._maxX = ground._width / 2.0;
  56396. ground._maxZ = ground._height / 2.0;
  56397. ground._minX = -ground._maxX;
  56398. ground._minZ = -ground._maxZ;
  56399. ground._setReady(false);
  56400. var onload = function (img) {
  56401. // Getting height map data
  56402. var canvas = document.createElement("canvas");
  56403. var context = canvas.getContext("2d");
  56404. if (!context) {
  56405. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  56406. }
  56407. if (scene.isDisposed) {
  56408. return;
  56409. }
  56410. var bufferWidth = img.width;
  56411. var bufferHeight = img.height;
  56412. canvas.width = bufferWidth;
  56413. canvas.height = bufferHeight;
  56414. context.drawImage(img, 0, 0);
  56415. // Create VertexData from map data
  56416. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  56417. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  56418. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  56419. width: width, height: height,
  56420. subdivisions: subdivisions,
  56421. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  56422. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  56423. });
  56424. vertexData.applyToMesh(ground, updatable);
  56425. ground._setReady(true);
  56426. //execute ready callback, if set
  56427. if (onReady) {
  56428. onReady(ground);
  56429. }
  56430. };
  56431. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  56432. return ground;
  56433. };
  56434. /**
  56435. * Creates a polygon mesh.
  56436. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  56437. * 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.
  56438. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56439. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56440. * 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).
  56441. * Remember you can only change the shape positions, not their number when updating a polygon.
  56442. */
  56443. MeshBuilder.CreatePolygon = function (name, options, scene) {
  56444. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56445. var shape = options.shape;
  56446. var holes = options.holes || [];
  56447. var depth = options.depth || 0;
  56448. var contours = [];
  56449. var hole = [];
  56450. for (var i = 0; i < shape.length; i++) {
  56451. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  56452. }
  56453. var epsilon = 0.00000001;
  56454. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  56455. contours.pop();
  56456. }
  56457. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  56458. for (var hNb = 0; hNb < holes.length; hNb++) {
  56459. hole = [];
  56460. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  56461. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  56462. }
  56463. polygonTriangulation.addHole(hole);
  56464. }
  56465. var polygon = polygonTriangulation.build(options.updatable, depth);
  56466. polygon._originalBuilderSideOrientation = options.sideOrientation;
  56467. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  56468. vertexData.applyToMesh(polygon, options.updatable);
  56469. return polygon;
  56470. };
  56471. ;
  56472. /**
  56473. * Creates an extruded polygon mesh, with depth in the Y direction.
  56474. * 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).
  56475. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  56476. */
  56477. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  56478. return MeshBuilder.CreatePolygon(name, options, scene);
  56479. };
  56480. ;
  56481. /**
  56482. * Creates a tube mesh.
  56483. * 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.
  56484. *
  56485. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  56486. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  56487. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  56488. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  56489. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  56490. * 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.
  56491. * It must return a radius value (positive float) :
  56492. * ```javascript
  56493. * var radiusFunction = function(i, distance) {
  56494. * // do things
  56495. * return radius; }
  56496. * ```
  56497. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  56498. * 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
  56499. * 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
  56500. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56501. * 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).
  56502. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56503. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  56504. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56505. */
  56506. MeshBuilder.CreateTube = function (name, options, scene) {
  56507. var path = options.path;
  56508. var instance = options.instance;
  56509. var radius = 1.0;
  56510. if (instance) {
  56511. radius = instance.radius;
  56512. }
  56513. if (options.radius !== undefined) {
  56514. radius = options.radius;
  56515. }
  56516. ;
  56517. var tessellation = options.tessellation || 64 | 0;
  56518. var radiusFunction = options.radiusFunction || null;
  56519. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  56520. var invertUV = options.invertUV || false;
  56521. var updatable = options.updatable;
  56522. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56523. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  56524. // tube geometry
  56525. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  56526. var tangents = path3D.getTangents();
  56527. var normals = path3D.getNormals();
  56528. var distances = path3D.getDistances();
  56529. var pi2 = Math.PI * 2;
  56530. var step = pi2 / tessellation * arc;
  56531. var returnRadius = function () { return radius; };
  56532. var radiusFunctionFinal = radiusFunction || returnRadius;
  56533. var circlePath;
  56534. var rad;
  56535. var normal;
  56536. var rotated;
  56537. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  56538. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  56539. for (var i = 0; i < path.length; i++) {
  56540. rad = radiusFunctionFinal(i, distances[i]); // current radius
  56541. circlePath = Array(); // current circle array
  56542. normal = normals[i]; // current normal
  56543. for (var t = 0; t < tessellation; t++) {
  56544. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  56545. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  56546. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  56547. rotated.scaleInPlace(rad).addInPlace(path[i]);
  56548. circlePath[t] = rotated;
  56549. }
  56550. circlePaths[index] = circlePath;
  56551. index++;
  56552. }
  56553. // cap
  56554. var capPath = function (nbPoints, pathIndex) {
  56555. var pointCap = Array();
  56556. for (var i = 0; i < nbPoints; i++) {
  56557. pointCap.push(path[pathIndex]);
  56558. }
  56559. return pointCap;
  56560. };
  56561. switch (cap) {
  56562. case BABYLON.Mesh.NO_CAP:
  56563. break;
  56564. case BABYLON.Mesh.CAP_START:
  56565. circlePaths[0] = capPath(tessellation, 0);
  56566. circlePaths[1] = circlePaths[2].slice(0);
  56567. break;
  56568. case BABYLON.Mesh.CAP_END:
  56569. circlePaths[index] = circlePaths[index - 1].slice(0);
  56570. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  56571. break;
  56572. case BABYLON.Mesh.CAP_ALL:
  56573. circlePaths[0] = capPath(tessellation, 0);
  56574. circlePaths[1] = circlePaths[2].slice(0);
  56575. circlePaths[index] = circlePaths[index - 1].slice(0);
  56576. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  56577. break;
  56578. default:
  56579. break;
  56580. }
  56581. return circlePaths;
  56582. };
  56583. var path3D;
  56584. var pathArray;
  56585. if (instance) {
  56586. var arc = options.arc || instance.arc;
  56587. path3D = (instance.path3D).update(path);
  56588. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  56589. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  56590. instance.path3D = path3D;
  56591. instance.pathArray = pathArray;
  56592. instance.arc = arc;
  56593. instance.radius = radius;
  56594. return instance;
  56595. }
  56596. // tube creation
  56597. path3D = new BABYLON.Path3D(path);
  56598. var newPathArray = new Array();
  56599. cap = (cap < 0 || cap > 3) ? 0 : cap;
  56600. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  56601. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  56602. tube.pathArray = pathArray;
  56603. tube.path3D = path3D;
  56604. tube.tessellation = tessellation;
  56605. tube.cap = cap;
  56606. tube.arc = options.arc;
  56607. tube.radius = radius;
  56608. return tube;
  56609. };
  56610. /**
  56611. * Creates a polyhedron mesh.
  56612. *
  56613. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  56614. * 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
  56615. * to choose the wanted type.
  56616. * The parameter `size` (positive float, default 1) sets the polygon size.
  56617. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  56618. * 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`.
  56619. * 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
  56620. * 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)`).
  56621. * 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
  56622. * 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.
  56623. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56624. * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4).
  56625. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56626. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56627. */
  56628. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  56629. var polyhedron = new BABYLON.Mesh(name, scene);
  56630. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56631. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  56632. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  56633. vertexData.applyToMesh(polyhedron, options.updatable);
  56634. return polyhedron;
  56635. };
  56636. /**
  56637. * Creates a decal mesh.
  56638. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  56639. * 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.
  56640. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  56641. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  56642. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  56643. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  56644. */
  56645. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  56646. var indices = sourceMesh.getIndices();
  56647. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  56648. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  56649. var position = options.position || BABYLON.Vector3.Zero();
  56650. var normal = options.normal || BABYLON.Vector3.Up();
  56651. var size = options.size || BABYLON.Vector3.One();
  56652. var angle = options.angle || 0;
  56653. // Getting correct rotation
  56654. if (!normal) {
  56655. var target = new BABYLON.Vector3(0, 0, 1);
  56656. var camera = sourceMesh.getScene().activeCamera;
  56657. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  56658. normal = camera.globalPosition.subtract(cameraWorldTarget);
  56659. }
  56660. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  56661. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  56662. var pitch = Math.atan2(normal.y, len);
  56663. // Matrix
  56664. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  56665. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  56666. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  56667. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  56668. var vertexData = new BABYLON.VertexData();
  56669. vertexData.indices = [];
  56670. vertexData.positions = [];
  56671. vertexData.normals = [];
  56672. vertexData.uvs = [];
  56673. var currentVertexDataIndex = 0;
  56674. var extractDecalVector3 = function (indexId) {
  56675. var result = new BABYLON.PositionNormalVertex();
  56676. if (!indices || !positions || !normals) {
  56677. return result;
  56678. }
  56679. var vertexId = indices[indexId];
  56680. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  56681. // Send vector to decal local world
  56682. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  56683. // Get normal
  56684. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  56685. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  56686. return result;
  56687. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  56688. var clip = function (vertices, axis) {
  56689. if (vertices.length === 0) {
  56690. return vertices;
  56691. }
  56692. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  56693. var clipVertices = function (v0, v1) {
  56694. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  56695. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  56696. };
  56697. var result = new Array();
  56698. for (var index = 0; index < vertices.length; index += 3) {
  56699. var v1Out;
  56700. var v2Out;
  56701. var v3Out;
  56702. var total = 0;
  56703. var nV1 = null;
  56704. var nV2 = null;
  56705. var nV3 = null;
  56706. var nV4 = null;
  56707. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  56708. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  56709. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  56710. v1Out = d1 > 0;
  56711. v2Out = d2 > 0;
  56712. v3Out = d3 > 0;
  56713. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  56714. switch (total) {
  56715. case 0:
  56716. result.push(vertices[index]);
  56717. result.push(vertices[index + 1]);
  56718. result.push(vertices[index + 2]);
  56719. break;
  56720. case 1:
  56721. if (v1Out) {
  56722. nV1 = vertices[index + 1];
  56723. nV2 = vertices[index + 2];
  56724. nV3 = clipVertices(vertices[index], nV1);
  56725. nV4 = clipVertices(vertices[index], nV2);
  56726. }
  56727. if (v2Out) {
  56728. nV1 = vertices[index];
  56729. nV2 = vertices[index + 2];
  56730. nV3 = clipVertices(vertices[index + 1], nV1);
  56731. nV4 = clipVertices(vertices[index + 1], nV2);
  56732. result.push(nV3);
  56733. result.push(nV2.clone());
  56734. result.push(nV1.clone());
  56735. result.push(nV2.clone());
  56736. result.push(nV3.clone());
  56737. result.push(nV4);
  56738. break;
  56739. }
  56740. if (v3Out) {
  56741. nV1 = vertices[index];
  56742. nV2 = vertices[index + 1];
  56743. nV3 = clipVertices(vertices[index + 2], nV1);
  56744. nV4 = clipVertices(vertices[index + 2], nV2);
  56745. }
  56746. if (nV1 && nV2 && nV3 && nV4) {
  56747. result.push(nV1.clone());
  56748. result.push(nV2.clone());
  56749. result.push(nV3);
  56750. result.push(nV4);
  56751. result.push(nV3.clone());
  56752. result.push(nV2.clone());
  56753. }
  56754. break;
  56755. case 2:
  56756. if (!v1Out) {
  56757. nV1 = vertices[index].clone();
  56758. nV2 = clipVertices(nV1, vertices[index + 1]);
  56759. nV3 = clipVertices(nV1, vertices[index + 2]);
  56760. result.push(nV1);
  56761. result.push(nV2);
  56762. result.push(nV3);
  56763. }
  56764. if (!v2Out) {
  56765. nV1 = vertices[index + 1].clone();
  56766. nV2 = clipVertices(nV1, vertices[index + 2]);
  56767. nV3 = clipVertices(nV1, vertices[index]);
  56768. result.push(nV1);
  56769. result.push(nV2);
  56770. result.push(nV3);
  56771. }
  56772. if (!v3Out) {
  56773. nV1 = vertices[index + 2].clone();
  56774. nV2 = clipVertices(nV1, vertices[index]);
  56775. nV3 = clipVertices(nV1, vertices[index + 1]);
  56776. result.push(nV1);
  56777. result.push(nV2);
  56778. result.push(nV3);
  56779. }
  56780. break;
  56781. case 3:
  56782. break;
  56783. }
  56784. }
  56785. return result;
  56786. };
  56787. for (var index = 0; index < indices.length; index += 3) {
  56788. var faceVertices = new Array();
  56789. faceVertices.push(extractDecalVector3(index));
  56790. faceVertices.push(extractDecalVector3(index + 1));
  56791. faceVertices.push(extractDecalVector3(index + 2));
  56792. // Clip
  56793. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  56794. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  56795. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  56796. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  56797. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  56798. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  56799. if (faceVertices.length === 0) {
  56800. continue;
  56801. }
  56802. // Add UVs and get back to world
  56803. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  56804. var vertex = faceVertices[vIndex];
  56805. //TODO check for Int32Array | Uint32Array | Uint16Array
  56806. vertexData.indices.push(currentVertexDataIndex);
  56807. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  56808. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  56809. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  56810. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  56811. currentVertexDataIndex++;
  56812. }
  56813. }
  56814. // Return mesh
  56815. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  56816. vertexData.applyToMesh(decal);
  56817. decal.position = position.clone();
  56818. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  56819. return decal;
  56820. };
  56821. // Privates
  56822. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  56823. // extrusion geometry
  56824. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  56825. var tangents = path3D.getTangents();
  56826. var normals = path3D.getNormals();
  56827. var binormals = path3D.getBinormals();
  56828. var distances = path3D.getDistances();
  56829. var angle = 0;
  56830. var returnScale = function () { return scale !== null ? scale : 1; };
  56831. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  56832. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  56833. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  56834. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  56835. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  56836. for (var i = 0; i < curve.length; i++) {
  56837. var shapePath = new Array();
  56838. var angleStep = rotate(i, distances[i]);
  56839. var scaleRatio = scl(i, distances[i]);
  56840. for (var p = 0; p < shape.length; p++) {
  56841. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  56842. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  56843. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  56844. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  56845. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  56846. shapePath[p] = rotated;
  56847. }
  56848. shapePaths[index] = shapePath;
  56849. angle += angleStep;
  56850. index++;
  56851. }
  56852. // cap
  56853. var capPath = function (shapePath) {
  56854. var pointCap = Array();
  56855. var barycenter = BABYLON.Vector3.Zero();
  56856. var i;
  56857. for (i = 0; i < shapePath.length; i++) {
  56858. barycenter.addInPlace(shapePath[i]);
  56859. }
  56860. barycenter.scaleInPlace(1.0 / shapePath.length);
  56861. for (i = 0; i < shapePath.length; i++) {
  56862. pointCap.push(barycenter);
  56863. }
  56864. return pointCap;
  56865. };
  56866. switch (cap) {
  56867. case BABYLON.Mesh.NO_CAP:
  56868. break;
  56869. case BABYLON.Mesh.CAP_START:
  56870. shapePaths[0] = capPath(shapePaths[2]);
  56871. shapePaths[1] = shapePaths[2];
  56872. break;
  56873. case BABYLON.Mesh.CAP_END:
  56874. shapePaths[index] = shapePaths[index - 1];
  56875. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  56876. break;
  56877. case BABYLON.Mesh.CAP_ALL:
  56878. shapePaths[0] = capPath(shapePaths[2]);
  56879. shapePaths[1] = shapePaths[2];
  56880. shapePaths[index] = shapePaths[index - 1];
  56881. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  56882. break;
  56883. default:
  56884. break;
  56885. }
  56886. return shapePaths;
  56887. };
  56888. var path3D;
  56889. var pathArray;
  56890. if (instance) {
  56891. path3D = (instance.path3D).update(curve);
  56892. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  56893. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  56894. return instance;
  56895. }
  56896. // extruded shape creation
  56897. path3D = new BABYLON.Path3D(curve);
  56898. var newShapePaths = new Array();
  56899. cap = (cap < 0 || cap > 3) ? 0 : cap;
  56900. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  56901. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  56902. extrudedGeneric.pathArray = pathArray;
  56903. extrudedGeneric.path3D = path3D;
  56904. extrudedGeneric.cap = cap;
  56905. return extrudedGeneric;
  56906. };
  56907. return MeshBuilder;
  56908. }());
  56909. BABYLON.MeshBuilder = MeshBuilder;
  56910. })(BABYLON || (BABYLON = {}));
  56911. //# sourceMappingURL=babylon.meshBuilder.js.map
  56912. var BABYLON;
  56913. (function (BABYLON) {
  56914. /**
  56915. * Draco compression (https://google.github.io/draco/)
  56916. */
  56917. var DracoCompression = /** @class */ (function () {
  56918. /**
  56919. * Constructor
  56920. * @param numWorkers The number of workers for async operations
  56921. */
  56922. function DracoCompression(numWorkers) {
  56923. if (numWorkers === void 0) { numWorkers = (navigator.hardwareConcurrency || 4); }
  56924. var workerBlobUrl = URL && URL.createObjectURL && URL.createObjectURL(new Blob(["(" + DracoCompression._Worker.toString() + ")()"], { type: "application/javascript" }));
  56925. if (!workerBlobUrl || !Worker) {
  56926. BABYLON.Tools.Error("Draco Compression disabled. The current context doesn't support worker creation or URL.createObjectURL");
  56927. return;
  56928. }
  56929. var workers = new Array(numWorkers);
  56930. for (var i = 0; i < workers.length; i++) {
  56931. var worker = new Worker(workerBlobUrl);
  56932. worker.postMessage({ id: "initDecoder", url: DracoCompression.DecoderUrl });
  56933. workers[i] = worker;
  56934. }
  56935. this._workerPool = new BABYLON.WorkerPool(workers);
  56936. }
  56937. /**
  56938. * Stop all async operations and release resources.
  56939. */
  56940. DracoCompression.prototype.dispose = function () {
  56941. this._workerPool.dispose();
  56942. delete this._workerPool;
  56943. };
  56944. /**
  56945. * Decode Draco compressed mesh data to vertex data.
  56946. * @param data The array buffer view for the Draco compression data
  56947. * @param attributes A map of attributes from vertex buffer kinds to Draco unique ids
  56948. * @returns A promise that resolves with the decoded vertex data
  56949. */
  56950. DracoCompression.prototype.decodeMeshAsync = function (data, attributes) {
  56951. var _this = this;
  56952. return new Promise(function (resolve, reject) {
  56953. _this._workerPool.push(function (worker, onComplete) {
  56954. var vertexData = new BABYLON.VertexData();
  56955. var onError = function (error) {
  56956. worker.removeEventListener("error", onError);
  56957. worker.removeEventListener("message", onMessage);
  56958. reject(error);
  56959. onComplete();
  56960. };
  56961. var onMessage = function (message) {
  56962. if (message.data === "done") {
  56963. worker.removeEventListener("error", onError);
  56964. worker.removeEventListener("message", onMessage);
  56965. resolve(vertexData);
  56966. onComplete();
  56967. }
  56968. else if (message.data.id === "indices") {
  56969. vertexData.indices = message.data.value;
  56970. }
  56971. else {
  56972. vertexData.set(message.data.value, message.data.id);
  56973. }
  56974. };
  56975. worker.addEventListener("error", onError);
  56976. worker.addEventListener("message", onMessage);
  56977. var dataCopy = new Uint8Array(data.byteLength);
  56978. dataCopy.set(new Uint8Array(data.buffer, data.byteOffset, data.byteLength));
  56979. worker.postMessage({ id: "decodeMesh", data: dataCopy, attributes: attributes }, [dataCopy.buffer]);
  56980. });
  56981. });
  56982. };
  56983. /**
  56984. * The worker function that gets converted to a blob url to pass into a worker.
  56985. */
  56986. DracoCompression._Worker = function () {
  56987. // self is actually a DedicatedWorkerGlobalScope
  56988. var _self = self;
  56989. var decodeMesh = function (data, attributes) {
  56990. var dracoModule = new DracoDecoderModule();
  56991. var buffer = new dracoModule.DecoderBuffer();
  56992. buffer.Init(data, data.byteLength);
  56993. var decoder = new dracoModule.Decoder();
  56994. var geometry;
  56995. var status;
  56996. try {
  56997. var type = decoder.GetEncodedGeometryType(buffer);
  56998. switch (type) {
  56999. case dracoModule.TRIANGULAR_MESH:
  57000. geometry = new dracoModule.Mesh();
  57001. status = decoder.DecodeBufferToMesh(buffer, geometry);
  57002. break;
  57003. case dracoModule.POINT_CLOUD:
  57004. geometry = new dracoModule.PointCloud();
  57005. status = decoder.DecodeBufferToPointCloud(buffer, geometry);
  57006. break;
  57007. default:
  57008. throw new Error("Invalid geometry type " + type);
  57009. }
  57010. if (!status.ok() || !geometry.ptr) {
  57011. throw new Error(status.error_msg());
  57012. }
  57013. var numPoints = geometry.num_points();
  57014. if (type === dracoModule.TRIANGULAR_MESH) {
  57015. var numFaces = geometry.num_faces();
  57016. var faceIndices = new dracoModule.DracoInt32Array();
  57017. try {
  57018. var indices = new Uint32Array(numFaces * 3);
  57019. for (var i = 0; i < numFaces; i++) {
  57020. decoder.GetFaceFromMesh(geometry, i, faceIndices);
  57021. var offset = i * 3;
  57022. indices[offset + 0] = faceIndices.GetValue(0);
  57023. indices[offset + 1] = faceIndices.GetValue(1);
  57024. indices[offset + 2] = faceIndices.GetValue(2);
  57025. }
  57026. _self.postMessage({ id: "indices", value: indices }, [indices.buffer]);
  57027. }
  57028. finally {
  57029. dracoModule.destroy(faceIndices);
  57030. }
  57031. }
  57032. for (var kind in attributes) {
  57033. var uniqueId = attributes[kind];
  57034. var attribute = decoder.GetAttributeByUniqueId(geometry, uniqueId);
  57035. var dracoData = new dracoModule.DracoFloat32Array();
  57036. try {
  57037. decoder.GetAttributeFloatForAllPoints(geometry, attribute, dracoData);
  57038. var babylonData = new Float32Array(numPoints * attribute.num_components());
  57039. for (var i = 0; i < babylonData.length; i++) {
  57040. babylonData[i] = dracoData.GetValue(i);
  57041. }
  57042. _self.postMessage({ id: kind, value: babylonData }, [babylonData.buffer]);
  57043. }
  57044. finally {
  57045. dracoModule.destroy(dracoData);
  57046. }
  57047. }
  57048. }
  57049. finally {
  57050. if (geometry) {
  57051. dracoModule.destroy(geometry);
  57052. }
  57053. dracoModule.destroy(decoder);
  57054. dracoModule.destroy(buffer);
  57055. }
  57056. _self.postMessage("done");
  57057. };
  57058. _self.onmessage = function (event) {
  57059. switch (event.data.id) {
  57060. case "initDecoder": {
  57061. importScripts(event.data.url);
  57062. break;
  57063. }
  57064. case "decodeMesh": {
  57065. decodeMesh(event.data.data, event.data.attributes);
  57066. break;
  57067. }
  57068. }
  57069. };
  57070. };
  57071. DracoCompression._GetDefaultDecoderUrl = function () {
  57072. if (!BABYLON.Tools.IsWindowObjectExist) {
  57073. return null;
  57074. }
  57075. for (var i = 0; i < document.scripts.length; i++) {
  57076. if (document.scripts[i].type === "text/x-draco-decoder") {
  57077. return document.scripts[i].src;
  57078. }
  57079. }
  57080. return null;
  57081. };
  57082. /**
  57083. * Gets the url to the draco decoder if available.
  57084. */
  57085. DracoCompression.DecoderUrl = DracoCompression._GetDefaultDecoderUrl();
  57086. return DracoCompression;
  57087. }());
  57088. BABYLON.DracoCompression = DracoCompression;
  57089. })(BABYLON || (BABYLON = {}));
  57090. //# sourceMappingURL=babylon.dracoCompression.js.map
  57091. var BABYLON;
  57092. (function (BABYLON) {
  57093. var AudioEngine = /** @class */ (function () {
  57094. function AudioEngine() {
  57095. this._audioContext = null;
  57096. this._audioContextInitialized = false;
  57097. this.canUseWebAudio = false;
  57098. this.WarnedWebAudioUnsupported = false;
  57099. this.unlocked = false;
  57100. this.isMP3supported = false;
  57101. this.isOGGsupported = false;
  57102. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  57103. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  57104. this.canUseWebAudio = true;
  57105. }
  57106. var audioElem = document.createElement('audio');
  57107. try {
  57108. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  57109. this.isMP3supported = true;
  57110. }
  57111. }
  57112. catch (e) {
  57113. // protect error during capability check.
  57114. }
  57115. try {
  57116. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  57117. this.isOGGsupported = true;
  57118. }
  57119. }
  57120. catch (e) {
  57121. // protect error during capability check.
  57122. }
  57123. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  57124. this._unlockiOSaudio();
  57125. }
  57126. else {
  57127. this.unlocked = true;
  57128. }
  57129. }
  57130. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  57131. get: function () {
  57132. if (!this._audioContextInitialized) {
  57133. this._initializeAudioContext();
  57134. }
  57135. return this._audioContext;
  57136. },
  57137. enumerable: true,
  57138. configurable: true
  57139. });
  57140. AudioEngine.prototype._unlockiOSaudio = function () {
  57141. var _this = this;
  57142. var unlockaudio = function () {
  57143. if (!_this.audioContext) {
  57144. return;
  57145. }
  57146. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  57147. var source = _this.audioContext.createBufferSource();
  57148. source.buffer = buffer;
  57149. source.connect(_this.audioContext.destination);
  57150. source.start(0);
  57151. setTimeout(function () {
  57152. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  57153. _this.unlocked = true;
  57154. window.removeEventListener('touchend', unlockaudio, false);
  57155. if (_this.onAudioUnlocked) {
  57156. _this.onAudioUnlocked();
  57157. }
  57158. }
  57159. }, 0);
  57160. };
  57161. window.addEventListener('touchend', unlockaudio, false);
  57162. };
  57163. AudioEngine.prototype._initializeAudioContext = function () {
  57164. try {
  57165. if (this.canUseWebAudio) {
  57166. this._audioContext = new AudioContext();
  57167. // create a global volume gain node
  57168. this.masterGain = this._audioContext.createGain();
  57169. this.masterGain.gain.value = 1;
  57170. this.masterGain.connect(this._audioContext.destination);
  57171. this._audioContextInitialized = true;
  57172. }
  57173. }
  57174. catch (e) {
  57175. this.canUseWebAudio = false;
  57176. BABYLON.Tools.Error("Web Audio: " + e.message);
  57177. }
  57178. };
  57179. AudioEngine.prototype.dispose = function () {
  57180. if (this.canUseWebAudio && this._audioContextInitialized) {
  57181. if (this._connectedAnalyser && this._audioContext) {
  57182. this._connectedAnalyser.stopDebugCanvas();
  57183. this._connectedAnalyser.dispose();
  57184. this.masterGain.disconnect();
  57185. this.masterGain.connect(this._audioContext.destination);
  57186. this._connectedAnalyser = null;
  57187. }
  57188. this.masterGain.gain.value = 1;
  57189. }
  57190. this.WarnedWebAudioUnsupported = false;
  57191. };
  57192. AudioEngine.prototype.getGlobalVolume = function () {
  57193. if (this.canUseWebAudio && this._audioContextInitialized) {
  57194. return this.masterGain.gain.value;
  57195. }
  57196. else {
  57197. return -1;
  57198. }
  57199. };
  57200. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  57201. if (this.canUseWebAudio && this._audioContextInitialized) {
  57202. this.masterGain.gain.value = newVolume;
  57203. }
  57204. };
  57205. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  57206. if (this._connectedAnalyser) {
  57207. this._connectedAnalyser.stopDebugCanvas();
  57208. }
  57209. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  57210. this._connectedAnalyser = analyser;
  57211. this.masterGain.disconnect();
  57212. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  57213. }
  57214. };
  57215. return AudioEngine;
  57216. }());
  57217. BABYLON.AudioEngine = AudioEngine;
  57218. })(BABYLON || (BABYLON = {}));
  57219. //# sourceMappingURL=babylon.audioEngine.js.map
  57220. var BABYLON;
  57221. (function (BABYLON) {
  57222. var Sound = /** @class */ (function () {
  57223. /**
  57224. * Create a sound and attach it to a scene
  57225. * @param name Name of your sound
  57226. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  57227. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  57228. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  57229. */
  57230. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  57231. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  57232. var _this = this;
  57233. this.autoplay = false;
  57234. this.loop = false;
  57235. this.useCustomAttenuation = false;
  57236. this.spatialSound = false;
  57237. this.refDistance = 1;
  57238. this.rolloffFactor = 1;
  57239. this.maxDistance = 100;
  57240. this.distanceModel = "linear";
  57241. this._panningModel = "equalpower";
  57242. this._playbackRate = 1;
  57243. this._streaming = false;
  57244. this._startTime = 0;
  57245. this._startOffset = 0;
  57246. this._position = BABYLON.Vector3.Zero();
  57247. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  57248. this._volume = 1;
  57249. this._isReadyToPlay = false;
  57250. this.isPlaying = false;
  57251. this.isPaused = false;
  57252. this._isDirectional = false;
  57253. // Used if you'd like to create a directional sound.
  57254. // If not set, the sound will be omnidirectional
  57255. this._coneInnerAngle = 360;
  57256. this._coneOuterAngle = 360;
  57257. this._coneOuterGain = 0;
  57258. this._isOutputConnected = false;
  57259. this._urlType = "Unknown";
  57260. this.name = name;
  57261. this._scene = scene;
  57262. this._readyToPlayCallback = readyToPlayCallback;
  57263. // Default custom attenuation function is a linear attenuation
  57264. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  57265. if (currentDistance < maxDistance) {
  57266. return currentVolume * (1 - currentDistance / maxDistance);
  57267. }
  57268. else {
  57269. return 0;
  57270. }
  57271. };
  57272. if (options) {
  57273. this.autoplay = options.autoplay || false;
  57274. this.loop = options.loop || false;
  57275. // if volume === 0, we need another way to check this option
  57276. if (options.volume !== undefined) {
  57277. this._volume = options.volume;
  57278. }
  57279. this.spatialSound = options.spatialSound || false;
  57280. this.maxDistance = options.maxDistance || 100;
  57281. this.useCustomAttenuation = options.useCustomAttenuation || false;
  57282. this.rolloffFactor = options.rolloffFactor || 1;
  57283. this.refDistance = options.refDistance || 1;
  57284. this.distanceModel = options.distanceModel || "linear";
  57285. this._playbackRate = options.playbackRate || 1;
  57286. this._streaming = options.streaming || false;
  57287. }
  57288. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  57289. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  57290. this._soundGain.gain.value = this._volume;
  57291. this._inputAudioNode = this._soundGain;
  57292. this._ouputAudioNode = this._soundGain;
  57293. if (this.spatialSound) {
  57294. this._createSpatialParameters();
  57295. }
  57296. this._scene.mainSoundTrack.AddSound(this);
  57297. var validParameter = true;
  57298. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  57299. if (urlOrArrayBuffer) {
  57300. if (typeof (urlOrArrayBuffer) === "string")
  57301. this._urlType = "String";
  57302. if (Array.isArray(urlOrArrayBuffer))
  57303. this._urlType = "Array";
  57304. if (urlOrArrayBuffer instanceof ArrayBuffer)
  57305. this._urlType = "ArrayBuffer";
  57306. var urls = [];
  57307. var codecSupportedFound = false;
  57308. switch (this._urlType) {
  57309. case "ArrayBuffer":
  57310. if (urlOrArrayBuffer.byteLength > 0) {
  57311. codecSupportedFound = true;
  57312. this._soundLoaded(urlOrArrayBuffer);
  57313. }
  57314. break;
  57315. case "String":
  57316. urls.push(urlOrArrayBuffer);
  57317. case "Array":
  57318. if (urls.length === 0)
  57319. urls = urlOrArrayBuffer;
  57320. // If we found a supported format, we load it immediately and stop the loop
  57321. for (var i = 0; i < urls.length; i++) {
  57322. var url = urls[i];
  57323. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  57324. codecSupportedFound = true;
  57325. }
  57326. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  57327. codecSupportedFound = true;
  57328. }
  57329. if (url.indexOf(".wav", url.length - 4) !== -1) {
  57330. codecSupportedFound = true;
  57331. }
  57332. if (url.indexOf("blob:") !== -1) {
  57333. codecSupportedFound = true;
  57334. }
  57335. if (codecSupportedFound) {
  57336. // Loading sound using XHR2
  57337. if (!this._streaming) {
  57338. this._scene._loadFile(url, function (data) { _this._soundLoaded(data); }, undefined, true, true);
  57339. }
  57340. else {
  57341. this._htmlAudioElement = new Audio(url);
  57342. this._htmlAudioElement.controls = false;
  57343. this._htmlAudioElement.loop = this.loop;
  57344. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  57345. this._htmlAudioElement.preload = "auto";
  57346. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  57347. _this._isReadyToPlay = true;
  57348. if (_this.autoplay) {
  57349. _this.play();
  57350. }
  57351. if (_this._readyToPlayCallback) {
  57352. _this._readyToPlayCallback();
  57353. }
  57354. });
  57355. document.body.appendChild(this._htmlAudioElement);
  57356. }
  57357. break;
  57358. }
  57359. }
  57360. break;
  57361. default:
  57362. validParameter = false;
  57363. break;
  57364. }
  57365. if (!validParameter) {
  57366. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  57367. }
  57368. else {
  57369. if (!codecSupportedFound) {
  57370. this._isReadyToPlay = true;
  57371. // Simulating a ready to play event to avoid breaking code path
  57372. if (this._readyToPlayCallback) {
  57373. window.setTimeout(function () {
  57374. if (_this._readyToPlayCallback) {
  57375. _this._readyToPlayCallback();
  57376. }
  57377. }, 1000);
  57378. }
  57379. }
  57380. }
  57381. }
  57382. }
  57383. else {
  57384. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  57385. this._scene.mainSoundTrack.AddSound(this);
  57386. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  57387. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  57388. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  57389. }
  57390. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  57391. if (this._readyToPlayCallback) {
  57392. window.setTimeout(function () {
  57393. if (_this._readyToPlayCallback) {
  57394. _this._readyToPlayCallback();
  57395. }
  57396. }, 1000);
  57397. }
  57398. }
  57399. }
  57400. Sound.prototype.dispose = function () {
  57401. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  57402. if (this.isPlaying) {
  57403. this.stop();
  57404. }
  57405. this._isReadyToPlay = false;
  57406. if (this.soundTrackId === -1) {
  57407. this._scene.mainSoundTrack.RemoveSound(this);
  57408. }
  57409. else {
  57410. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  57411. }
  57412. if (this._soundGain) {
  57413. this._soundGain.disconnect();
  57414. this._soundGain = null;
  57415. }
  57416. if (this._soundPanner) {
  57417. this._soundPanner.disconnect();
  57418. this._soundPanner = null;
  57419. }
  57420. if (this._soundSource) {
  57421. this._soundSource.disconnect();
  57422. this._soundSource = null;
  57423. }
  57424. this._audioBuffer = null;
  57425. if (this._htmlAudioElement) {
  57426. this._htmlAudioElement.pause();
  57427. this._htmlAudioElement.src = "";
  57428. document.body.removeChild(this._htmlAudioElement);
  57429. }
  57430. if (this._connectedMesh && this._registerFunc) {
  57431. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  57432. this._connectedMesh = null;
  57433. }
  57434. }
  57435. };
  57436. Sound.prototype.isReady = function () {
  57437. return this._isReadyToPlay;
  57438. };
  57439. Sound.prototype._soundLoaded = function (audioData) {
  57440. var _this = this;
  57441. if (!BABYLON.Engine.audioEngine.audioContext) {
  57442. return;
  57443. }
  57444. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  57445. _this._audioBuffer = buffer;
  57446. _this._isReadyToPlay = true;
  57447. if (_this.autoplay) {
  57448. _this.play();
  57449. }
  57450. if (_this._readyToPlayCallback) {
  57451. _this._readyToPlayCallback();
  57452. }
  57453. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  57454. };
  57455. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  57456. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  57457. this._audioBuffer = audioBuffer;
  57458. this._isReadyToPlay = true;
  57459. }
  57460. };
  57461. Sound.prototype.updateOptions = function (options) {
  57462. if (options) {
  57463. this.loop = options.loop || this.loop;
  57464. this.maxDistance = options.maxDistance || this.maxDistance;
  57465. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  57466. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  57467. this.refDistance = options.refDistance || this.refDistance;
  57468. this.distanceModel = options.distanceModel || this.distanceModel;
  57469. this._playbackRate = options.playbackRate || this._playbackRate;
  57470. this._updateSpatialParameters();
  57471. if (this.isPlaying) {
  57472. if (this._streaming) {
  57473. this._htmlAudioElement.playbackRate = this._playbackRate;
  57474. }
  57475. else {
  57476. if (this._soundSource) {
  57477. this._soundSource.playbackRate.value = this._playbackRate;
  57478. }
  57479. }
  57480. }
  57481. }
  57482. };
  57483. Sound.prototype._createSpatialParameters = function () {
  57484. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  57485. if (this._scene.headphone) {
  57486. this._panningModel = "HRTF";
  57487. }
  57488. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  57489. this._updateSpatialParameters();
  57490. this._soundPanner.connect(this._ouputAudioNode);
  57491. this._inputAudioNode = this._soundPanner;
  57492. }
  57493. };
  57494. Sound.prototype._updateSpatialParameters = function () {
  57495. if (this.spatialSound && this._soundPanner) {
  57496. if (this.useCustomAttenuation) {
  57497. // Tricks to disable in a way embedded Web Audio attenuation
  57498. this._soundPanner.distanceModel = "linear";
  57499. this._soundPanner.maxDistance = Number.MAX_VALUE;
  57500. this._soundPanner.refDistance = 1;
  57501. this._soundPanner.rolloffFactor = 1;
  57502. this._soundPanner.panningModel = this._panningModel;
  57503. }
  57504. else {
  57505. this._soundPanner.distanceModel = this.distanceModel;
  57506. this._soundPanner.maxDistance = this.maxDistance;
  57507. this._soundPanner.refDistance = this.refDistance;
  57508. this._soundPanner.rolloffFactor = this.rolloffFactor;
  57509. this._soundPanner.panningModel = this._panningModel;
  57510. }
  57511. }
  57512. };
  57513. Sound.prototype.switchPanningModelToHRTF = function () {
  57514. this._panningModel = "HRTF";
  57515. this._switchPanningModel();
  57516. };
  57517. Sound.prototype.switchPanningModelToEqualPower = function () {
  57518. this._panningModel = "equalpower";
  57519. this._switchPanningModel();
  57520. };
  57521. Sound.prototype._switchPanningModel = function () {
  57522. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  57523. this._soundPanner.panningModel = this._panningModel;
  57524. }
  57525. };
  57526. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  57527. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  57528. if (this._isOutputConnected) {
  57529. this._ouputAudioNode.disconnect();
  57530. }
  57531. this._ouputAudioNode.connect(soundTrackAudioNode);
  57532. this._isOutputConnected = true;
  57533. }
  57534. };
  57535. /**
  57536. * Transform this sound into a directional source
  57537. * @param coneInnerAngle Size of the inner cone in degree
  57538. * @param coneOuterAngle Size of the outer cone in degree
  57539. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  57540. */
  57541. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  57542. if (coneOuterAngle < coneInnerAngle) {
  57543. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  57544. return;
  57545. }
  57546. this._coneInnerAngle = coneInnerAngle;
  57547. this._coneOuterAngle = coneOuterAngle;
  57548. this._coneOuterGain = coneOuterGain;
  57549. this._isDirectional = true;
  57550. if (this.isPlaying && this.loop) {
  57551. this.stop();
  57552. this.play();
  57553. }
  57554. };
  57555. Sound.prototype.setPosition = function (newPosition) {
  57556. this._position = newPosition;
  57557. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  57558. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  57559. }
  57560. };
  57561. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  57562. this._localDirection = newLocalDirection;
  57563. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  57564. this._updateDirection();
  57565. }
  57566. };
  57567. Sound.prototype._updateDirection = function () {
  57568. if (!this._connectedMesh || !this._soundPanner) {
  57569. return;
  57570. }
  57571. var mat = this._connectedMesh.getWorldMatrix();
  57572. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  57573. direction.normalize();
  57574. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  57575. };
  57576. Sound.prototype.updateDistanceFromListener = function () {
  57577. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  57578. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  57579. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  57580. }
  57581. };
  57582. Sound.prototype.setAttenuationFunction = function (callback) {
  57583. this._customAttenuationFunction = callback;
  57584. };
  57585. /**
  57586. * Play the sound
  57587. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  57588. * @param offset (optional) Start the sound setting it at a specific time
  57589. */
  57590. Sound.prototype.play = function (time, offset) {
  57591. var _this = this;
  57592. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  57593. try {
  57594. if (this._startOffset < 0) {
  57595. time = -this._startOffset;
  57596. this._startOffset = 0;
  57597. }
  57598. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  57599. if (!this._soundSource || !this._streamingSource) {
  57600. if (this.spatialSound && this._soundPanner) {
  57601. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  57602. if (this._isDirectional) {
  57603. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  57604. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  57605. this._soundPanner.coneOuterGain = this._coneOuterGain;
  57606. if (this._connectedMesh) {
  57607. this._updateDirection();
  57608. }
  57609. else {
  57610. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  57611. }
  57612. }
  57613. }
  57614. }
  57615. if (this._streaming) {
  57616. if (!this._streamingSource) {
  57617. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  57618. this._htmlAudioElement.onended = function () { _this._onended(); };
  57619. this._htmlAudioElement.playbackRate = this._playbackRate;
  57620. }
  57621. this._streamingSource.disconnect();
  57622. this._streamingSource.connect(this._inputAudioNode);
  57623. this._htmlAudioElement.play();
  57624. }
  57625. else {
  57626. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  57627. this._soundSource.buffer = this._audioBuffer;
  57628. this._soundSource.connect(this._inputAudioNode);
  57629. this._soundSource.loop = this.loop;
  57630. this._soundSource.playbackRate.value = this._playbackRate;
  57631. this._soundSource.onended = function () { _this._onended(); };
  57632. if (this._soundSource.buffer) {
  57633. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  57634. }
  57635. }
  57636. this._startTime = startTime;
  57637. this.isPlaying = true;
  57638. this.isPaused = false;
  57639. }
  57640. catch (ex) {
  57641. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  57642. }
  57643. }
  57644. };
  57645. Sound.prototype._onended = function () {
  57646. this.isPlaying = false;
  57647. if (this.onended) {
  57648. this.onended();
  57649. }
  57650. };
  57651. /**
  57652. * Stop the sound
  57653. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  57654. */
  57655. Sound.prototype.stop = function (time) {
  57656. if (this.isPlaying) {
  57657. if (this._streaming) {
  57658. this._htmlAudioElement.pause();
  57659. // Test needed for Firefox or it will generate an Invalid State Error
  57660. if (this._htmlAudioElement.currentTime > 0) {
  57661. this._htmlAudioElement.currentTime = 0;
  57662. }
  57663. }
  57664. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  57665. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  57666. this._soundSource.stop(stopTime);
  57667. this._soundSource.onended = function () { };
  57668. if (!this.isPaused) {
  57669. this._startOffset = 0;
  57670. }
  57671. }
  57672. this.isPlaying = false;
  57673. }
  57674. };
  57675. Sound.prototype.pause = function () {
  57676. if (this.isPlaying) {
  57677. this.isPaused = true;
  57678. if (this._streaming) {
  57679. this._htmlAudioElement.pause();
  57680. }
  57681. else if (BABYLON.Engine.audioEngine.audioContext) {
  57682. this.stop(0);
  57683. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  57684. }
  57685. }
  57686. };
  57687. Sound.prototype.setVolume = function (newVolume, time) {
  57688. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  57689. if (time && BABYLON.Engine.audioEngine.audioContext) {
  57690. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  57691. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  57692. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  57693. }
  57694. else {
  57695. this._soundGain.gain.value = newVolume;
  57696. }
  57697. }
  57698. this._volume = newVolume;
  57699. };
  57700. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  57701. this._playbackRate = newPlaybackRate;
  57702. if (this.isPlaying) {
  57703. if (this._streaming) {
  57704. this._htmlAudioElement.playbackRate = this._playbackRate;
  57705. }
  57706. else if (this._soundSource) {
  57707. this._soundSource.playbackRate.value = this._playbackRate;
  57708. }
  57709. }
  57710. };
  57711. Sound.prototype.getVolume = function () {
  57712. return this._volume;
  57713. };
  57714. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  57715. var _this = this;
  57716. if (this._connectedMesh && this._registerFunc) {
  57717. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  57718. this._registerFunc = null;
  57719. }
  57720. this._connectedMesh = meshToConnectTo;
  57721. if (!this.spatialSound) {
  57722. this.spatialSound = true;
  57723. this._createSpatialParameters();
  57724. if (this.isPlaying && this.loop) {
  57725. this.stop();
  57726. this.play();
  57727. }
  57728. }
  57729. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  57730. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  57731. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  57732. };
  57733. Sound.prototype.detachFromMesh = function () {
  57734. if (this._connectedMesh && this._registerFunc) {
  57735. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  57736. this._registerFunc = null;
  57737. this._connectedMesh = null;
  57738. }
  57739. };
  57740. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  57741. if (!node.getBoundingInfo) {
  57742. return;
  57743. }
  57744. var mesh = node;
  57745. var boundingInfo = mesh.getBoundingInfo();
  57746. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  57747. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  57748. this._updateDirection();
  57749. }
  57750. };
  57751. Sound.prototype.clone = function () {
  57752. var _this = this;
  57753. if (!this._streaming) {
  57754. var setBufferAndRun = function () {
  57755. if (_this._isReadyToPlay) {
  57756. clonedSound._audioBuffer = _this.getAudioBuffer();
  57757. clonedSound._isReadyToPlay = true;
  57758. if (clonedSound.autoplay) {
  57759. clonedSound.play();
  57760. }
  57761. }
  57762. else {
  57763. window.setTimeout(setBufferAndRun, 300);
  57764. }
  57765. };
  57766. var currentOptions = {
  57767. autoplay: this.autoplay, loop: this.loop,
  57768. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  57769. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  57770. refDistance: this.refDistance, distanceModel: this.distanceModel
  57771. };
  57772. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  57773. if (this.useCustomAttenuation) {
  57774. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  57775. }
  57776. clonedSound.setPosition(this._position);
  57777. clonedSound.setPlaybackRate(this._playbackRate);
  57778. setBufferAndRun();
  57779. return clonedSound;
  57780. }
  57781. else {
  57782. return null;
  57783. }
  57784. };
  57785. Sound.prototype.getAudioBuffer = function () {
  57786. return this._audioBuffer;
  57787. };
  57788. Sound.prototype.serialize = function () {
  57789. var serializationObject = {
  57790. name: this.name,
  57791. url: this.name,
  57792. autoplay: this.autoplay,
  57793. loop: this.loop,
  57794. volume: this._volume,
  57795. spatialSound: this.spatialSound,
  57796. maxDistance: this.maxDistance,
  57797. rolloffFactor: this.rolloffFactor,
  57798. refDistance: this.refDistance,
  57799. distanceModel: this.distanceModel,
  57800. playbackRate: this._playbackRate,
  57801. panningModel: this._panningModel,
  57802. soundTrackId: this.soundTrackId
  57803. };
  57804. if (this.spatialSound) {
  57805. if (this._connectedMesh)
  57806. serializationObject.connectedMeshId = this._connectedMesh.id;
  57807. serializationObject.position = this._position.asArray();
  57808. serializationObject.refDistance = this.refDistance;
  57809. serializationObject.distanceModel = this.distanceModel;
  57810. serializationObject.isDirectional = this._isDirectional;
  57811. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  57812. serializationObject.coneInnerAngle = this._coneInnerAngle;
  57813. serializationObject.coneOuterAngle = this._coneOuterAngle;
  57814. serializationObject.coneOuterGain = this._coneOuterGain;
  57815. }
  57816. return serializationObject;
  57817. };
  57818. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  57819. var soundName = parsedSound.name;
  57820. var soundUrl;
  57821. if (parsedSound.url) {
  57822. soundUrl = rootUrl + parsedSound.url;
  57823. }
  57824. else {
  57825. soundUrl = rootUrl + soundName;
  57826. }
  57827. var options = {
  57828. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  57829. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  57830. rolloffFactor: parsedSound.rolloffFactor,
  57831. refDistance: parsedSound.refDistance,
  57832. distanceModel: parsedSound.distanceModel,
  57833. playbackRate: parsedSound.playbackRate
  57834. };
  57835. var newSound;
  57836. if (!sourceSound) {
  57837. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  57838. scene._addPendingData(newSound);
  57839. }
  57840. else {
  57841. var setBufferAndRun = function () {
  57842. if (sourceSound._isReadyToPlay) {
  57843. newSound._audioBuffer = sourceSound.getAudioBuffer();
  57844. newSound._isReadyToPlay = true;
  57845. if (newSound.autoplay) {
  57846. newSound.play();
  57847. }
  57848. }
  57849. else {
  57850. window.setTimeout(setBufferAndRun, 300);
  57851. }
  57852. };
  57853. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  57854. setBufferAndRun();
  57855. }
  57856. if (parsedSound.position) {
  57857. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  57858. newSound.setPosition(soundPosition);
  57859. }
  57860. if (parsedSound.isDirectional) {
  57861. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  57862. if (parsedSound.localDirectionToMesh) {
  57863. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  57864. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  57865. }
  57866. }
  57867. if (parsedSound.connectedMeshId) {
  57868. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  57869. if (connectedMesh) {
  57870. newSound.attachToMesh(connectedMesh);
  57871. }
  57872. }
  57873. return newSound;
  57874. };
  57875. return Sound;
  57876. }());
  57877. BABYLON.Sound = Sound;
  57878. })(BABYLON || (BABYLON = {}));
  57879. //# sourceMappingURL=babylon.sound.js.map
  57880. var BABYLON;
  57881. (function (BABYLON) {
  57882. var SoundTrack = /** @class */ (function () {
  57883. function SoundTrack(scene, options) {
  57884. this.id = -1;
  57885. this._isMainTrack = false;
  57886. this._isInitialized = false;
  57887. this._scene = scene;
  57888. this.soundCollection = new Array();
  57889. this._options = options;
  57890. if (!this._isMainTrack) {
  57891. this._scene.soundTracks.push(this);
  57892. this.id = this._scene.soundTracks.length - 1;
  57893. }
  57894. }
  57895. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  57896. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  57897. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  57898. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  57899. if (this._options) {
  57900. if (this._options.volume) {
  57901. this._outputAudioNode.gain.value = this._options.volume;
  57902. }
  57903. if (this._options.mainTrack) {
  57904. this._isMainTrack = this._options.mainTrack;
  57905. }
  57906. }
  57907. this._isInitialized = true;
  57908. }
  57909. };
  57910. SoundTrack.prototype.dispose = function () {
  57911. if (BABYLON.Engine.audioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  57912. if (this._connectedAnalyser) {
  57913. this._connectedAnalyser.stopDebugCanvas();
  57914. }
  57915. while (this.soundCollection.length) {
  57916. this.soundCollection[0].dispose();
  57917. }
  57918. if (this._outputAudioNode) {
  57919. this._outputAudioNode.disconnect();
  57920. }
  57921. this._outputAudioNode = null;
  57922. }
  57923. };
  57924. SoundTrack.prototype.AddSound = function (sound) {
  57925. if (!this._isInitialized) {
  57926. this._initializeSoundTrackAudioGraph();
  57927. }
  57928. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  57929. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  57930. }
  57931. if (sound.soundTrackId) {
  57932. if (sound.soundTrackId === -1) {
  57933. this._scene.mainSoundTrack.RemoveSound(sound);
  57934. }
  57935. else {
  57936. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  57937. }
  57938. }
  57939. this.soundCollection.push(sound);
  57940. sound.soundTrackId = this.id;
  57941. };
  57942. SoundTrack.prototype.RemoveSound = function (sound) {
  57943. var index = this.soundCollection.indexOf(sound);
  57944. if (index !== -1) {
  57945. this.soundCollection.splice(index, 1);
  57946. }
  57947. };
  57948. SoundTrack.prototype.setVolume = function (newVolume) {
  57949. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  57950. this._outputAudioNode.gain.value = newVolume;
  57951. }
  57952. };
  57953. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  57954. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  57955. for (var i = 0; i < this.soundCollection.length; i++) {
  57956. this.soundCollection[i].switchPanningModelToHRTF();
  57957. }
  57958. }
  57959. };
  57960. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  57961. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  57962. for (var i = 0; i < this.soundCollection.length; i++) {
  57963. this.soundCollection[i].switchPanningModelToEqualPower();
  57964. }
  57965. }
  57966. };
  57967. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  57968. if (this._connectedAnalyser) {
  57969. this._connectedAnalyser.stopDebugCanvas();
  57970. }
  57971. this._connectedAnalyser = analyser;
  57972. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  57973. this._outputAudioNode.disconnect();
  57974. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  57975. }
  57976. };
  57977. return SoundTrack;
  57978. }());
  57979. BABYLON.SoundTrack = SoundTrack;
  57980. })(BABYLON || (BABYLON = {}));
  57981. //# sourceMappingURL=babylon.soundtrack.js.map
  57982. var BABYLON;
  57983. (function (BABYLON) {
  57984. var Analyser = /** @class */ (function () {
  57985. function Analyser(scene) {
  57986. this.SMOOTHING = 0.75;
  57987. this.FFT_SIZE = 512;
  57988. this.BARGRAPHAMPLITUDE = 256;
  57989. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  57990. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  57991. this._scene = scene;
  57992. this._audioEngine = BABYLON.Engine.audioEngine;
  57993. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  57994. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  57995. this._webAudioAnalyser.minDecibels = -140;
  57996. this._webAudioAnalyser.maxDecibels = 0;
  57997. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  57998. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  57999. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  58000. }
  58001. }
  58002. Analyser.prototype.getFrequencyBinCount = function () {
  58003. if (this._audioEngine.canUseWebAudio) {
  58004. return this._webAudioAnalyser.frequencyBinCount;
  58005. }
  58006. else {
  58007. return 0;
  58008. }
  58009. };
  58010. Analyser.prototype.getByteFrequencyData = function () {
  58011. if (this._audioEngine.canUseWebAudio) {
  58012. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  58013. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  58014. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  58015. }
  58016. return this._byteFreqs;
  58017. };
  58018. Analyser.prototype.getByteTimeDomainData = function () {
  58019. if (this._audioEngine.canUseWebAudio) {
  58020. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  58021. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  58022. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  58023. }
  58024. return this._byteTime;
  58025. };
  58026. Analyser.prototype.getFloatFrequencyData = function () {
  58027. if (this._audioEngine.canUseWebAudio) {
  58028. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  58029. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  58030. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  58031. }
  58032. return this._floatFreqs;
  58033. };
  58034. Analyser.prototype.drawDebugCanvas = function () {
  58035. var _this = this;
  58036. if (this._audioEngine.canUseWebAudio) {
  58037. if (!this._debugCanvas) {
  58038. this._debugCanvas = document.createElement("canvas");
  58039. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  58040. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  58041. this._debugCanvas.style.position = "absolute";
  58042. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  58043. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  58044. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  58045. document.body.appendChild(this._debugCanvas);
  58046. this._registerFunc = function () {
  58047. _this.drawDebugCanvas();
  58048. };
  58049. this._scene.registerBeforeRender(this._registerFunc);
  58050. }
  58051. if (this._registerFunc && this._debugCanvasContext) {
  58052. var workingArray = this.getByteFrequencyData();
  58053. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  58054. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  58055. // Draw the frequency domain chart.
  58056. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  58057. var value = workingArray[i];
  58058. var percent = value / this.BARGRAPHAMPLITUDE;
  58059. var height = this.DEBUGCANVASSIZE.height * percent;
  58060. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  58061. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  58062. var hue = i / this.getFrequencyBinCount() * 360;
  58063. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  58064. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  58065. }
  58066. }
  58067. }
  58068. };
  58069. Analyser.prototype.stopDebugCanvas = function () {
  58070. if (this._debugCanvas) {
  58071. if (this._registerFunc) {
  58072. this._scene.unregisterBeforeRender(this._registerFunc);
  58073. this._registerFunc = null;
  58074. }
  58075. document.body.removeChild(this._debugCanvas);
  58076. this._debugCanvas = null;
  58077. this._debugCanvasContext = null;
  58078. }
  58079. };
  58080. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  58081. if (this._audioEngine.canUseWebAudio) {
  58082. inputAudioNode.connect(this._webAudioAnalyser);
  58083. this._webAudioAnalyser.connect(outputAudioNode);
  58084. }
  58085. };
  58086. Analyser.prototype.dispose = function () {
  58087. if (this._audioEngine.canUseWebAudio) {
  58088. this._webAudioAnalyser.disconnect();
  58089. }
  58090. };
  58091. return Analyser;
  58092. }());
  58093. BABYLON.Analyser = Analyser;
  58094. })(BABYLON || (BABYLON = {}));
  58095. //# sourceMappingURL=babylon.analyser.js.map
  58096. var BABYLON;
  58097. (function (BABYLON) {
  58098. var CubeTexture = /** @class */ (function (_super) {
  58099. __extends(CubeTexture, _super);
  58100. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension) {
  58101. if (extensions === void 0) { extensions = null; }
  58102. if (noMipmap === void 0) { noMipmap = false; }
  58103. if (files === void 0) { files = null; }
  58104. if (onLoad === void 0) { onLoad = null; }
  58105. if (onError === void 0) { onError = null; }
  58106. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  58107. if (prefiltered === void 0) { prefiltered = false; }
  58108. if (forcedExtension === void 0) { forcedExtension = null; }
  58109. var _this = _super.call(this, scene) || this;
  58110. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  58111. /**
  58112. * Gets or sets the center of the bounding box associated with the cube texture
  58113. * It must define where the camera used to render the texture was set
  58114. */
  58115. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  58116. _this.name = rootUrl;
  58117. _this.url = rootUrl;
  58118. _this._noMipmap = noMipmap;
  58119. _this.hasAlpha = false;
  58120. _this._format = format;
  58121. _this._prefiltered = prefiltered;
  58122. _this.isCube = true;
  58123. _this._textureMatrix = BABYLON.Matrix.Identity();
  58124. if (prefiltered) {
  58125. _this.gammaSpace = false;
  58126. }
  58127. if (!rootUrl && !files) {
  58128. return _this;
  58129. }
  58130. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  58131. var lastDot = rootUrl.lastIndexOf(".");
  58132. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  58133. var isDDS = (extension === ".dds");
  58134. if (!files) {
  58135. if (!isDDS && !extensions) {
  58136. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  58137. }
  58138. files = [];
  58139. if (extensions) {
  58140. for (var index = 0; index < extensions.length; index++) {
  58141. files.push(rootUrl + extensions[index]);
  58142. }
  58143. }
  58144. }
  58145. _this._files = files;
  58146. if (!_this._texture) {
  58147. if (!scene.useDelayedTextureLoading) {
  58148. if (prefiltered) {
  58149. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, _this.lodGenerationScale, _this.lodGenerationOffset, onLoad, onError, format, forcedExtension);
  58150. }
  58151. else {
  58152. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension);
  58153. }
  58154. }
  58155. else {
  58156. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  58157. }
  58158. }
  58159. else if (onLoad) {
  58160. if (_this._texture.isReady) {
  58161. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  58162. }
  58163. else {
  58164. _this._texture.onLoadedObservable.add(onLoad);
  58165. }
  58166. }
  58167. return _this;
  58168. }
  58169. Object.defineProperty(CubeTexture.prototype, "boundingBoxSize", {
  58170. get: function () {
  58171. return this._boundingBoxSize;
  58172. },
  58173. /**
  58174. * Gets or sets the size of the bounding box associated with the cube texture
  58175. * When defined, the cubemap will switch to local mode
  58176. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  58177. * @example https://www.babylonjs-playground.com/#RNASML
  58178. */
  58179. set: function (value) {
  58180. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  58181. return;
  58182. }
  58183. this._boundingBoxSize = value;
  58184. var scene = this.getScene();
  58185. if (scene) {
  58186. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  58187. }
  58188. },
  58189. enumerable: true,
  58190. configurable: true
  58191. });
  58192. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  58193. var rootUrlKey = "";
  58194. files.forEach(function (url) { return rootUrlKey += url; });
  58195. return new CubeTexture(rootUrlKey, scene, null, noMipmap, files);
  58196. };
  58197. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension) {
  58198. if (forcedExtension === void 0) { forcedExtension = null; }
  58199. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension);
  58200. };
  58201. // Methods
  58202. CubeTexture.prototype.delayLoad = function () {
  58203. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  58204. return;
  58205. }
  58206. var scene = this.getScene();
  58207. if (!scene) {
  58208. return;
  58209. }
  58210. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  58211. this._texture = this._getFromCache(this.url, this._noMipmap);
  58212. if (!this._texture) {
  58213. if (this._prefiltered) {
  58214. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format);
  58215. }
  58216. else {
  58217. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  58218. }
  58219. }
  58220. };
  58221. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  58222. return this._textureMatrix;
  58223. };
  58224. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  58225. this._textureMatrix = value;
  58226. };
  58227. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  58228. var texture = BABYLON.SerializationHelper.Parse(function () {
  58229. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  58230. }, parsedTexture, scene);
  58231. // Local Cubemaps
  58232. if (parsedTexture.boundingBoxPosition) {
  58233. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  58234. }
  58235. if (parsedTexture.boundingBoxSize) {
  58236. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  58237. }
  58238. // Animations
  58239. if (parsedTexture.animations) {
  58240. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  58241. var parsedAnimation = parsedTexture.animations[animationIndex];
  58242. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  58243. }
  58244. }
  58245. return texture;
  58246. };
  58247. CubeTexture.prototype.clone = function () {
  58248. var _this = this;
  58249. return BABYLON.SerializationHelper.Clone(function () {
  58250. var scene = _this.getScene();
  58251. if (!scene) {
  58252. return _this;
  58253. }
  58254. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  58255. }, this);
  58256. };
  58257. return CubeTexture;
  58258. }(BABYLON.BaseTexture));
  58259. BABYLON.CubeTexture = CubeTexture;
  58260. })(BABYLON || (BABYLON = {}));
  58261. //# sourceMappingURL=babylon.cubeTexture.js.map
  58262. var BABYLON;
  58263. (function (BABYLON) {
  58264. var RenderTargetTexture = /** @class */ (function (_super) {
  58265. __extends(RenderTargetTexture, _super);
  58266. /**
  58267. * Instantiate a render target texture. This is mainly to render of screen the scene to for instance apply post processse
  58268. * or used a shadow, depth texture...
  58269. * @param name The friendly name of the texture
  58270. * @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)
  58271. * @param scene The scene the RTT belongs to. The latest created scene will be used if not precised.
  58272. * @param generateMipMaps True if mip maps need to be generated after render.
  58273. * @param doNotChangeAspectRatio True to not change the aspect ratio of the scene in the RTT
  58274. * @param type The type of the buffer in the RTT (int, half float, float...)
  58275. * @param isCube True if a cube texture needs to be created
  58276. * @param samplingMode The sampling mode to be usedwith the render target (Linear, Nearest...)
  58277. * @param generateDepthBuffer True to generate a depth buffer
  58278. * @param generateStencilBuffer True to generate a stencil buffer
  58279. * @param isMulti True if multiple textures need to be created (Draw Buffers)
  58280. */
  58281. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  58282. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  58283. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  58284. if (isCube === void 0) { isCube = false; }
  58285. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  58286. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  58287. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  58288. if (isMulti === void 0) { isMulti = false; }
  58289. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  58290. _this.isCube = isCube;
  58291. /**
  58292. * Use this list to define the list of mesh you want to render.
  58293. */
  58294. _this.renderList = new Array();
  58295. _this.renderParticles = true;
  58296. _this.renderSprites = false;
  58297. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  58298. _this.ignoreCameraViewport = false;
  58299. // Events
  58300. /**
  58301. * An event triggered when the texture is unbind.
  58302. * @type {BABYLON.Observable}
  58303. */
  58304. _this.onBeforeBindObservable = new BABYLON.Observable();
  58305. /**
  58306. * An event triggered when the texture is unbind.
  58307. * @type {BABYLON.Observable}
  58308. */
  58309. _this.onAfterUnbindObservable = new BABYLON.Observable();
  58310. /**
  58311. * An event triggered before rendering the texture
  58312. * @type {BABYLON.Observable}
  58313. */
  58314. _this.onBeforeRenderObservable = new BABYLON.Observable();
  58315. /**
  58316. * An event triggered after rendering the texture
  58317. * @type {BABYLON.Observable}
  58318. */
  58319. _this.onAfterRenderObservable = new BABYLON.Observable();
  58320. /**
  58321. * An event triggered after the texture clear
  58322. * @type {BABYLON.Observable}
  58323. */
  58324. _this.onClearObservable = new BABYLON.Observable();
  58325. _this._currentRefreshId = -1;
  58326. _this._refreshRate = 1;
  58327. _this._samples = 1;
  58328. /**
  58329. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  58330. * It must define where the camera used to render the texture is set
  58331. */
  58332. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  58333. scene = _this.getScene();
  58334. if (!scene) {
  58335. return _this;
  58336. }
  58337. _this._engine = scene.getEngine();
  58338. _this.name = name;
  58339. _this.isRenderTarget = true;
  58340. _this._initialSizeParameter = size;
  58341. _this._processSizeParameter(size);
  58342. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  58343. });
  58344. _this._generateMipMaps = generateMipMaps ? true : false;
  58345. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  58346. // Rendering groups
  58347. _this._renderingManager = new BABYLON.RenderingManager(scene);
  58348. if (isMulti) {
  58349. return _this;
  58350. }
  58351. _this._renderTargetOptions = {
  58352. generateMipMaps: generateMipMaps,
  58353. type: type,
  58354. samplingMode: samplingMode,
  58355. generateDepthBuffer: generateDepthBuffer,
  58356. generateStencilBuffer: generateStencilBuffer
  58357. };
  58358. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  58359. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58360. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58361. }
  58362. if (isCube) {
  58363. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  58364. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  58365. _this._textureMatrix = BABYLON.Matrix.Identity();
  58366. }
  58367. else {
  58368. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  58369. }
  58370. return _this;
  58371. }
  58372. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  58373. get: function () {
  58374. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  58375. },
  58376. enumerable: true,
  58377. configurable: true
  58378. });
  58379. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  58380. get: function () {
  58381. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  58382. },
  58383. enumerable: true,
  58384. configurable: true
  58385. });
  58386. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  58387. get: function () {
  58388. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  58389. },
  58390. enumerable: true,
  58391. configurable: true
  58392. });
  58393. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  58394. set: function (callback) {
  58395. if (this._onAfterUnbindObserver) {
  58396. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  58397. }
  58398. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  58399. },
  58400. enumerable: true,
  58401. configurable: true
  58402. });
  58403. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  58404. set: function (callback) {
  58405. if (this._onBeforeRenderObserver) {
  58406. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  58407. }
  58408. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  58409. },
  58410. enumerable: true,
  58411. configurable: true
  58412. });
  58413. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  58414. set: function (callback) {
  58415. if (this._onAfterRenderObserver) {
  58416. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  58417. }
  58418. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  58419. },
  58420. enumerable: true,
  58421. configurable: true
  58422. });
  58423. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  58424. set: function (callback) {
  58425. if (this._onClearObserver) {
  58426. this.onClearObservable.remove(this._onClearObserver);
  58427. }
  58428. this._onClearObserver = this.onClearObservable.add(callback);
  58429. },
  58430. enumerable: true,
  58431. configurable: true
  58432. });
  58433. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  58434. get: function () {
  58435. return this._renderTargetOptions;
  58436. },
  58437. enumerable: true,
  58438. configurable: true
  58439. });
  58440. RenderTargetTexture.prototype._onRatioRescale = function () {
  58441. if (this._sizeRatio) {
  58442. this.resize(this._initialSizeParameter);
  58443. }
  58444. };
  58445. Object.defineProperty(RenderTargetTexture.prototype, "boundingBoxSize", {
  58446. get: function () {
  58447. return this._boundingBoxSize;
  58448. },
  58449. /**
  58450. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  58451. * When defined, the cubemap will switch to local mode
  58452. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  58453. * @example https://www.babylonjs-playground.com/#RNASML
  58454. */
  58455. set: function (value) {
  58456. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  58457. return;
  58458. }
  58459. this._boundingBoxSize = value;
  58460. var scene = this.getScene();
  58461. if (scene) {
  58462. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  58463. }
  58464. },
  58465. enumerable: true,
  58466. configurable: true
  58467. });
  58468. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  58469. if (size.ratio) {
  58470. this._sizeRatio = size.ratio;
  58471. this._size = {
  58472. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  58473. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  58474. };
  58475. }
  58476. else {
  58477. this._size = size;
  58478. }
  58479. };
  58480. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  58481. get: function () {
  58482. return this._samples;
  58483. },
  58484. set: function (value) {
  58485. if (this._samples === value) {
  58486. return;
  58487. }
  58488. var scene = this.getScene();
  58489. if (!scene) {
  58490. return;
  58491. }
  58492. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  58493. },
  58494. enumerable: true,
  58495. configurable: true
  58496. });
  58497. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  58498. this._currentRefreshId = -1;
  58499. };
  58500. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  58501. get: function () {
  58502. return this._refreshRate;
  58503. },
  58504. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  58505. set: function (value) {
  58506. this._refreshRate = value;
  58507. this.resetRefreshCounter();
  58508. },
  58509. enumerable: true,
  58510. configurable: true
  58511. });
  58512. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  58513. if (!this._postProcessManager) {
  58514. var scene = this.getScene();
  58515. if (!scene) {
  58516. return;
  58517. }
  58518. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  58519. this._postProcesses = new Array();
  58520. }
  58521. this._postProcesses.push(postProcess);
  58522. this._postProcesses[0].autoClear = false;
  58523. };
  58524. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  58525. if (!this._postProcesses) {
  58526. return;
  58527. }
  58528. if (dispose) {
  58529. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  58530. var postProcess = _a[_i];
  58531. postProcess.dispose();
  58532. }
  58533. }
  58534. this._postProcesses = [];
  58535. };
  58536. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  58537. if (!this._postProcesses) {
  58538. return;
  58539. }
  58540. var index = this._postProcesses.indexOf(postProcess);
  58541. if (index === -1) {
  58542. return;
  58543. }
  58544. this._postProcesses.splice(index, 1);
  58545. if (this._postProcesses.length > 0) {
  58546. this._postProcesses[0].autoClear = false;
  58547. }
  58548. };
  58549. RenderTargetTexture.prototype._shouldRender = function () {
  58550. if (this._currentRefreshId === -1) {
  58551. this._currentRefreshId = 1;
  58552. return true;
  58553. }
  58554. if (this.refreshRate === this._currentRefreshId) {
  58555. this._currentRefreshId = 1;
  58556. return true;
  58557. }
  58558. this._currentRefreshId++;
  58559. return false;
  58560. };
  58561. RenderTargetTexture.prototype.getRenderSize = function () {
  58562. if (this._size.width) {
  58563. return this._size.width;
  58564. }
  58565. return this._size;
  58566. };
  58567. RenderTargetTexture.prototype.getRenderWidth = function () {
  58568. if (this._size.width) {
  58569. return this._size.width;
  58570. }
  58571. return this._size;
  58572. };
  58573. RenderTargetTexture.prototype.getRenderHeight = function () {
  58574. if (this._size.width) {
  58575. return this._size.height;
  58576. }
  58577. return this._size;
  58578. };
  58579. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  58580. get: function () {
  58581. return true;
  58582. },
  58583. enumerable: true,
  58584. configurable: true
  58585. });
  58586. RenderTargetTexture.prototype.scale = function (ratio) {
  58587. var newSize = this.getRenderSize() * ratio;
  58588. this.resize(newSize);
  58589. };
  58590. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  58591. if (this.isCube) {
  58592. return this._textureMatrix;
  58593. }
  58594. return _super.prototype.getReflectionTextureMatrix.call(this);
  58595. };
  58596. RenderTargetTexture.prototype.resize = function (size) {
  58597. this.releaseInternalTexture();
  58598. var scene = this.getScene();
  58599. if (!scene) {
  58600. return;
  58601. }
  58602. this._processSizeParameter(size);
  58603. if (this.isCube) {
  58604. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  58605. }
  58606. else {
  58607. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  58608. }
  58609. };
  58610. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  58611. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  58612. if (dumpForDebug === void 0) { dumpForDebug = false; }
  58613. var scene = this.getScene();
  58614. if (!scene) {
  58615. return;
  58616. }
  58617. var engine = scene.getEngine();
  58618. if (this.useCameraPostProcesses !== undefined) {
  58619. useCameraPostProcess = this.useCameraPostProcesses;
  58620. }
  58621. if (this._waitingRenderList) {
  58622. this.renderList = [];
  58623. for (var index = 0; index < this._waitingRenderList.length; index++) {
  58624. var id = this._waitingRenderList[index];
  58625. var mesh_1 = scene.getMeshByID(id);
  58626. if (mesh_1) {
  58627. this.renderList.push(mesh_1);
  58628. }
  58629. }
  58630. delete this._waitingRenderList;
  58631. }
  58632. // Is predicate defined?
  58633. if (this.renderListPredicate) {
  58634. if (this.renderList) {
  58635. this.renderList.splice(0); // Clear previous renderList
  58636. }
  58637. else {
  58638. this.renderList = [];
  58639. }
  58640. var scene = this.getScene();
  58641. if (!scene) {
  58642. return;
  58643. }
  58644. var sceneMeshes = scene.meshes;
  58645. for (var index = 0; index < sceneMeshes.length; index++) {
  58646. var mesh = sceneMeshes[index];
  58647. if (this.renderListPredicate(mesh)) {
  58648. this.renderList.push(mesh);
  58649. }
  58650. }
  58651. }
  58652. this.onBeforeBindObservable.notifyObservers(this);
  58653. // Set custom projection.
  58654. // Needs to be before binding to prevent changing the aspect ratio.
  58655. var camera;
  58656. if (this.activeCamera) {
  58657. camera = this.activeCamera;
  58658. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  58659. if (this.activeCamera !== scene.activeCamera) {
  58660. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  58661. }
  58662. }
  58663. else {
  58664. camera = scene.activeCamera;
  58665. if (camera) {
  58666. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  58667. }
  58668. }
  58669. // Prepare renderingManager
  58670. this._renderingManager.reset();
  58671. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  58672. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  58673. var sceneRenderId = scene.getRenderId();
  58674. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  58675. var mesh = currentRenderList[meshIndex];
  58676. if (mesh) {
  58677. if (!mesh.isReady(this.refreshRate === 0)) {
  58678. this.resetRefreshCounter();
  58679. continue;
  58680. }
  58681. mesh._preActivateForIntermediateRendering(sceneRenderId);
  58682. var isMasked = void 0;
  58683. if (!this.renderList && camera) {
  58684. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  58685. }
  58686. else {
  58687. isMasked = false;
  58688. }
  58689. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  58690. mesh._activate(sceneRenderId);
  58691. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  58692. var subMesh = mesh.subMeshes[subIndex];
  58693. scene._activeIndices.addCount(subMesh.indexCount, false);
  58694. this._renderingManager.dispatch(subMesh, mesh);
  58695. }
  58696. }
  58697. }
  58698. }
  58699. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  58700. var particleSystem = scene.particleSystems[particleIndex];
  58701. var emitter = particleSystem.emitter;
  58702. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  58703. continue;
  58704. }
  58705. if (currentRenderList.indexOf(emitter) >= 0) {
  58706. this._renderingManager.dispatchParticles(particleSystem);
  58707. }
  58708. }
  58709. if (this.isCube) {
  58710. for (var face = 0; face < 6; face++) {
  58711. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  58712. scene.incrementRenderId();
  58713. scene.resetCachedMaterial();
  58714. }
  58715. }
  58716. else {
  58717. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  58718. }
  58719. this.onAfterUnbindObservable.notifyObservers(this);
  58720. if (scene.activeCamera) {
  58721. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  58722. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  58723. }
  58724. engine.setViewport(scene.activeCamera.viewport);
  58725. }
  58726. scene.resetCachedMaterial();
  58727. };
  58728. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  58729. var minimum = 128;
  58730. var x = renderDimension * scale;
  58731. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  58732. // Ensure we don't exceed the render dimension (while staying POT)
  58733. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  58734. };
  58735. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  58736. var _this = this;
  58737. if (!this._texture) {
  58738. return;
  58739. }
  58740. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  58741. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  58742. });
  58743. };
  58744. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  58745. var scene = this.getScene();
  58746. if (!scene) {
  58747. return;
  58748. }
  58749. var engine = scene.getEngine();
  58750. if (!this._texture) {
  58751. return;
  58752. }
  58753. // Bind
  58754. if (this._postProcessManager) {
  58755. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  58756. }
  58757. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  58758. if (this._texture) {
  58759. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport, this.depthStencilTexture ? this.depthStencilTexture : undefined);
  58760. }
  58761. }
  58762. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  58763. // Clear
  58764. if (this.onClearObservable.hasObservers()) {
  58765. this.onClearObservable.notifyObservers(engine);
  58766. }
  58767. else {
  58768. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  58769. }
  58770. if (!this._doNotChangeAspectRatio) {
  58771. scene.updateTransformMatrix(true);
  58772. }
  58773. // Render
  58774. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  58775. if (this._postProcessManager) {
  58776. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  58777. }
  58778. else if (useCameraPostProcess) {
  58779. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  58780. }
  58781. if (!this._doNotChangeAspectRatio) {
  58782. scene.updateTransformMatrix(true);
  58783. }
  58784. // Dump ?
  58785. if (dumpForDebug) {
  58786. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  58787. }
  58788. // Unbind
  58789. if (!this.isCube || faceIndex === 5) {
  58790. if (this.isCube) {
  58791. if (faceIndex === 5) {
  58792. engine.generateMipMapsForCubemap(this._texture);
  58793. }
  58794. }
  58795. this.unbindFrameBuffer(engine, faceIndex);
  58796. }
  58797. else {
  58798. this.onAfterRenderObservable.notifyObservers(faceIndex);
  58799. }
  58800. };
  58801. /**
  58802. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  58803. * This allowed control for front to back rendering or reversly depending of the special needs.
  58804. *
  58805. * @param renderingGroupId The rendering group id corresponding to its index
  58806. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  58807. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  58808. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  58809. */
  58810. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  58811. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  58812. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  58813. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  58814. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  58815. };
  58816. /**
  58817. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  58818. *
  58819. * @param renderingGroupId The rendering group id corresponding to its index
  58820. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  58821. */
  58822. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  58823. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  58824. };
  58825. RenderTargetTexture.prototype.clone = function () {
  58826. var textureSize = this.getSize();
  58827. 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);
  58828. // Base texture
  58829. newTexture.hasAlpha = this.hasAlpha;
  58830. newTexture.level = this.level;
  58831. // RenderTarget Texture
  58832. newTexture.coordinatesMode = this.coordinatesMode;
  58833. if (this.renderList) {
  58834. newTexture.renderList = this.renderList.slice(0);
  58835. }
  58836. return newTexture;
  58837. };
  58838. RenderTargetTexture.prototype.serialize = function () {
  58839. if (!this.name) {
  58840. return null;
  58841. }
  58842. var serializationObject = _super.prototype.serialize.call(this);
  58843. serializationObject.renderTargetSize = this.getRenderSize();
  58844. serializationObject.renderList = [];
  58845. if (this.renderList) {
  58846. for (var index = 0; index < this.renderList.length; index++) {
  58847. serializationObject.renderList.push(this.renderList[index].id);
  58848. }
  58849. }
  58850. return serializationObject;
  58851. };
  58852. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  58853. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  58854. var objBuffer = this.getInternalTexture();
  58855. var scene = this.getScene();
  58856. if (objBuffer && scene) {
  58857. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  58858. }
  58859. };
  58860. RenderTargetTexture.prototype.dispose = function () {
  58861. if (this._postProcessManager) {
  58862. this._postProcessManager.dispose();
  58863. this._postProcessManager = null;
  58864. }
  58865. this.clearPostProcesses(true);
  58866. if (this._resizeObserver) {
  58867. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  58868. this._resizeObserver = null;
  58869. }
  58870. this.renderList = null;
  58871. // Remove from custom render targets
  58872. var scene = this.getScene();
  58873. if (!scene) {
  58874. return;
  58875. }
  58876. var index = scene.customRenderTargets.indexOf(this);
  58877. if (index >= 0) {
  58878. scene.customRenderTargets.splice(index, 1);
  58879. }
  58880. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  58881. var camera = _a[_i];
  58882. index = camera.customRenderTargets.indexOf(this);
  58883. if (index >= 0) {
  58884. camera.customRenderTargets.splice(index, 1);
  58885. }
  58886. }
  58887. _super.prototype.dispose.call(this);
  58888. };
  58889. RenderTargetTexture.prototype._rebuild = function () {
  58890. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  58891. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  58892. }
  58893. if (this._postProcessManager) {
  58894. this._postProcessManager._rebuild();
  58895. }
  58896. };
  58897. /**
  58898. * Clear the info related to rendering groups preventing retention point in material dispose.
  58899. */
  58900. RenderTargetTexture.prototype.freeRenderingGroups = function () {
  58901. if (this._renderingManager) {
  58902. this._renderingManager.freeRenderingGroups();
  58903. }
  58904. };
  58905. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  58906. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  58907. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  58908. return RenderTargetTexture;
  58909. }(BABYLON.Texture));
  58910. BABYLON.RenderTargetTexture = RenderTargetTexture;
  58911. })(BABYLON || (BABYLON = {}));
  58912. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  58913. var BABYLON;
  58914. (function (BABYLON) {
  58915. ;
  58916. var MultiRenderTarget = /** @class */ (function (_super) {
  58917. __extends(MultiRenderTarget, _super);
  58918. function MultiRenderTarget(name, size, count, scene, options) {
  58919. var _this = this;
  58920. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  58921. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  58922. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  58923. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  58924. _this._engine = scene.getEngine();
  58925. if (!_this.isSupported) {
  58926. _this.dispose();
  58927. return;
  58928. }
  58929. var types = [];
  58930. var samplingModes = [];
  58931. for (var i = 0; i < count; i++) {
  58932. if (options && options.types && options.types[i] !== undefined) {
  58933. types.push(options.types[i]);
  58934. }
  58935. else {
  58936. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  58937. }
  58938. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  58939. samplingModes.push(options.samplingModes[i]);
  58940. }
  58941. else {
  58942. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  58943. }
  58944. }
  58945. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  58946. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  58947. _this._size = size;
  58948. _this._multiRenderTargetOptions = {
  58949. samplingModes: samplingModes,
  58950. generateMipMaps: generateMipMaps,
  58951. generateDepthBuffer: generateDepthBuffer,
  58952. generateStencilBuffer: generateStencilBuffer,
  58953. generateDepthTexture: generateDepthTexture,
  58954. types: types,
  58955. textureCount: count
  58956. };
  58957. _this._createInternalTextures();
  58958. _this._createTextures();
  58959. return _this;
  58960. }
  58961. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  58962. get: function () {
  58963. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  58964. },
  58965. enumerable: true,
  58966. configurable: true
  58967. });
  58968. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  58969. get: function () {
  58970. return this._textures;
  58971. },
  58972. enumerable: true,
  58973. configurable: true
  58974. });
  58975. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  58976. get: function () {
  58977. return this._textures[this._textures.length - 1];
  58978. },
  58979. enumerable: true,
  58980. configurable: true
  58981. });
  58982. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  58983. set: function (wrap) {
  58984. if (this._textures) {
  58985. for (var i = 0; i < this._textures.length; i++) {
  58986. this._textures[i].wrapU = wrap;
  58987. }
  58988. }
  58989. },
  58990. enumerable: true,
  58991. configurable: true
  58992. });
  58993. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  58994. set: function (wrap) {
  58995. if (this._textures) {
  58996. for (var i = 0; i < this._textures.length; i++) {
  58997. this._textures[i].wrapV = wrap;
  58998. }
  58999. }
  59000. },
  59001. enumerable: true,
  59002. configurable: true
  59003. });
  59004. MultiRenderTarget.prototype._rebuild = function () {
  59005. this.releaseInternalTextures();
  59006. this._createInternalTextures();
  59007. for (var i = 0; i < this._internalTextures.length; i++) {
  59008. var texture = this._textures[i];
  59009. texture._texture = this._internalTextures[i];
  59010. }
  59011. // Keeps references to frame buffer and stencil/depth buffer
  59012. this._texture = this._internalTextures[0];
  59013. };
  59014. MultiRenderTarget.prototype._createInternalTextures = function () {
  59015. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  59016. };
  59017. MultiRenderTarget.prototype._createTextures = function () {
  59018. this._textures = [];
  59019. for (var i = 0; i < this._internalTextures.length; i++) {
  59020. var texture = new BABYLON.Texture(null, this.getScene());
  59021. texture._texture = this._internalTextures[i];
  59022. this._textures.push(texture);
  59023. }
  59024. // Keeps references to frame buffer and stencil/depth buffer
  59025. this._texture = this._internalTextures[0];
  59026. };
  59027. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  59028. get: function () {
  59029. return this._samples;
  59030. },
  59031. set: function (value) {
  59032. if (this._samples === value) {
  59033. return;
  59034. }
  59035. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  59036. },
  59037. enumerable: true,
  59038. configurable: true
  59039. });
  59040. MultiRenderTarget.prototype.resize = function (size) {
  59041. this.releaseInternalTextures();
  59042. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  59043. this._createInternalTextures();
  59044. };
  59045. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  59046. var _this = this;
  59047. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  59048. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  59049. });
  59050. };
  59051. MultiRenderTarget.prototype.dispose = function () {
  59052. this.releaseInternalTextures();
  59053. _super.prototype.dispose.call(this);
  59054. };
  59055. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  59056. if (!this._internalTextures) {
  59057. return;
  59058. }
  59059. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  59060. if (this._internalTextures[i] !== undefined) {
  59061. this._internalTextures[i].dispose();
  59062. this._internalTextures.splice(i, 1);
  59063. }
  59064. }
  59065. };
  59066. return MultiRenderTarget;
  59067. }(BABYLON.RenderTargetTexture));
  59068. BABYLON.MultiRenderTarget = MultiRenderTarget;
  59069. })(BABYLON || (BABYLON = {}));
  59070. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  59071. var BABYLON;
  59072. (function (BABYLON) {
  59073. var MirrorTexture = /** @class */ (function (_super) {
  59074. __extends(MirrorTexture, _super);
  59075. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  59076. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  59077. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  59078. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  59079. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  59080. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  59081. _this._transformMatrix = BABYLON.Matrix.Zero();
  59082. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  59083. _this._adaptiveBlurKernel = 0;
  59084. _this._blurKernelX = 0;
  59085. _this._blurKernelY = 0;
  59086. _this._blurRatio = 1.0;
  59087. _this.ignoreCameraViewport = true;
  59088. _this.onBeforeRenderObservable.add(function () {
  59089. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  59090. _this._savedViewMatrix = scene.getViewMatrix();
  59091. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  59092. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  59093. scene.clipPlane = _this.mirrorPlane;
  59094. scene.getEngine().cullBackFaces = false;
  59095. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  59096. });
  59097. _this.onAfterRenderObservable.add(function () {
  59098. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  59099. scene.getEngine().cullBackFaces = true;
  59100. scene._mirroredCameraPosition = null;
  59101. delete scene.clipPlane;
  59102. });
  59103. return _this;
  59104. }
  59105. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  59106. get: function () {
  59107. return this._blurRatio;
  59108. },
  59109. set: function (value) {
  59110. if (this._blurRatio === value) {
  59111. return;
  59112. }
  59113. this._blurRatio = value;
  59114. this._preparePostProcesses();
  59115. },
  59116. enumerable: true,
  59117. configurable: true
  59118. });
  59119. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  59120. set: function (value) {
  59121. this._adaptiveBlurKernel = value;
  59122. this._autoComputeBlurKernel();
  59123. },
  59124. enumerable: true,
  59125. configurable: true
  59126. });
  59127. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  59128. set: function (value) {
  59129. this.blurKernelX = value;
  59130. this.blurKernelY = value;
  59131. },
  59132. enumerable: true,
  59133. configurable: true
  59134. });
  59135. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  59136. get: function () {
  59137. return this._blurKernelX;
  59138. },
  59139. set: function (value) {
  59140. if (this._blurKernelX === value) {
  59141. return;
  59142. }
  59143. this._blurKernelX = value;
  59144. this._preparePostProcesses();
  59145. },
  59146. enumerable: true,
  59147. configurable: true
  59148. });
  59149. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  59150. get: function () {
  59151. return this._blurKernelY;
  59152. },
  59153. set: function (value) {
  59154. if (this._blurKernelY === value) {
  59155. return;
  59156. }
  59157. this._blurKernelY = value;
  59158. this._preparePostProcesses();
  59159. },
  59160. enumerable: true,
  59161. configurable: true
  59162. });
  59163. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  59164. var engine = this.getScene().getEngine();
  59165. var dw = this.getRenderWidth() / engine.getRenderWidth();
  59166. var dh = this.getRenderHeight() / engine.getRenderHeight();
  59167. this.blurKernelX = this._adaptiveBlurKernel * dw;
  59168. this.blurKernelY = this._adaptiveBlurKernel * dh;
  59169. };
  59170. MirrorTexture.prototype._onRatioRescale = function () {
  59171. if (this._sizeRatio) {
  59172. this.resize(this._initialSizeParameter);
  59173. if (!this._adaptiveBlurKernel) {
  59174. this._preparePostProcesses();
  59175. }
  59176. }
  59177. if (this._adaptiveBlurKernel) {
  59178. this._autoComputeBlurKernel();
  59179. }
  59180. };
  59181. MirrorTexture.prototype._preparePostProcesses = function () {
  59182. this.clearPostProcesses(true);
  59183. if (this._blurKernelX && this._blurKernelY) {
  59184. var engine = this.getScene().getEngine();
  59185. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  59186. 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);
  59187. this._blurX.autoClear = false;
  59188. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  59189. this._blurX.inputTexture = this._texture;
  59190. }
  59191. else {
  59192. this._blurX.alwaysForcePOT = true;
  59193. }
  59194. 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);
  59195. this._blurY.autoClear = false;
  59196. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  59197. this.addPostProcess(this._blurX);
  59198. this.addPostProcess(this._blurY);
  59199. }
  59200. else {
  59201. if (this._blurY) {
  59202. this.removePostProcess(this._blurY);
  59203. this._blurY.dispose();
  59204. this._blurY = null;
  59205. }
  59206. if (this._blurX) {
  59207. this.removePostProcess(this._blurX);
  59208. this._blurX.dispose();
  59209. this._blurX = null;
  59210. }
  59211. }
  59212. };
  59213. MirrorTexture.prototype.clone = function () {
  59214. var scene = this.getScene();
  59215. if (!scene) {
  59216. return this;
  59217. }
  59218. var textureSize = this.getSize();
  59219. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  59220. // Base texture
  59221. newTexture.hasAlpha = this.hasAlpha;
  59222. newTexture.level = this.level;
  59223. // Mirror Texture
  59224. newTexture.mirrorPlane = this.mirrorPlane.clone();
  59225. if (this.renderList) {
  59226. newTexture.renderList = this.renderList.slice(0);
  59227. }
  59228. return newTexture;
  59229. };
  59230. MirrorTexture.prototype.serialize = function () {
  59231. if (!this.name) {
  59232. return null;
  59233. }
  59234. var serializationObject = _super.prototype.serialize.call(this);
  59235. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  59236. return serializationObject;
  59237. };
  59238. return MirrorTexture;
  59239. }(BABYLON.RenderTargetTexture));
  59240. BABYLON.MirrorTexture = MirrorTexture;
  59241. })(BABYLON || (BABYLON = {}));
  59242. //# sourceMappingURL=babylon.mirrorTexture.js.map
  59243. var BABYLON;
  59244. (function (BABYLON) {
  59245. /**
  59246. * Creates a refraction texture used by refraction channel of the standard material.
  59247. * @param name the texture name
  59248. * @param size size of the underlying texture
  59249. * @param scene root scene
  59250. */
  59251. var RefractionTexture = /** @class */ (function (_super) {
  59252. __extends(RefractionTexture, _super);
  59253. function RefractionTexture(name, size, scene, generateMipMaps) {
  59254. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  59255. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  59256. _this.depth = 2.0;
  59257. _this.onBeforeRenderObservable.add(function () {
  59258. scene.clipPlane = _this.refractionPlane;
  59259. });
  59260. _this.onAfterRenderObservable.add(function () {
  59261. delete scene.clipPlane;
  59262. });
  59263. return _this;
  59264. }
  59265. RefractionTexture.prototype.clone = function () {
  59266. var scene = this.getScene();
  59267. if (!scene) {
  59268. return this;
  59269. }
  59270. var textureSize = this.getSize();
  59271. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  59272. // Base texture
  59273. newTexture.hasAlpha = this.hasAlpha;
  59274. newTexture.level = this.level;
  59275. // Refraction Texture
  59276. newTexture.refractionPlane = this.refractionPlane.clone();
  59277. if (this.renderList) {
  59278. newTexture.renderList = this.renderList.slice(0);
  59279. }
  59280. newTexture.depth = this.depth;
  59281. return newTexture;
  59282. };
  59283. RefractionTexture.prototype.serialize = function () {
  59284. if (!this.name) {
  59285. return null;
  59286. }
  59287. var serializationObject = _super.prototype.serialize.call(this);
  59288. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  59289. serializationObject.depth = this.depth;
  59290. return serializationObject;
  59291. };
  59292. return RefractionTexture;
  59293. }(BABYLON.RenderTargetTexture));
  59294. BABYLON.RefractionTexture = RefractionTexture;
  59295. })(BABYLON || (BABYLON = {}));
  59296. //# sourceMappingURL=babylon.refractionTexture.js.map
  59297. var BABYLON;
  59298. (function (BABYLON) {
  59299. var DynamicTexture = /** @class */ (function (_super) {
  59300. __extends(DynamicTexture, _super);
  59301. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  59302. if (scene === void 0) { scene = null; }
  59303. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  59304. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  59305. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  59306. _this.name = name;
  59307. _this._engine = _this.getScene().getEngine();
  59308. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59309. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59310. _this._generateMipMaps = generateMipMaps;
  59311. if (options.getContext) {
  59312. _this._canvas = options;
  59313. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  59314. }
  59315. else {
  59316. _this._canvas = document.createElement("canvas");
  59317. if (options.width) {
  59318. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  59319. }
  59320. else {
  59321. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  59322. }
  59323. }
  59324. var textureSize = _this.getSize();
  59325. _this._canvas.width = textureSize.width;
  59326. _this._canvas.height = textureSize.height;
  59327. _this._context = _this._canvas.getContext("2d");
  59328. return _this;
  59329. }
  59330. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  59331. get: function () {
  59332. return true;
  59333. },
  59334. enumerable: true,
  59335. configurable: true
  59336. });
  59337. DynamicTexture.prototype._recreate = function (textureSize) {
  59338. this._canvas.width = textureSize.width;
  59339. this._canvas.height = textureSize.height;
  59340. this.releaseInternalTexture();
  59341. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  59342. };
  59343. DynamicTexture.prototype.scale = function (ratio) {
  59344. var textureSize = this.getSize();
  59345. textureSize.width *= ratio;
  59346. textureSize.height *= ratio;
  59347. this._recreate(textureSize);
  59348. };
  59349. DynamicTexture.prototype.scaleTo = function (width, height) {
  59350. var textureSize = this.getSize();
  59351. textureSize.width = width;
  59352. textureSize.height = height;
  59353. this._recreate(textureSize);
  59354. };
  59355. DynamicTexture.prototype.getContext = function () {
  59356. return this._context;
  59357. };
  59358. DynamicTexture.prototype.clear = function () {
  59359. var size = this.getSize();
  59360. this._context.fillRect(0, 0, size.width, size.height);
  59361. };
  59362. DynamicTexture.prototype.update = function (invertY) {
  59363. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format || undefined);
  59364. };
  59365. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  59366. if (update === void 0) { update = true; }
  59367. var size = this.getSize();
  59368. if (clearColor) {
  59369. this._context.fillStyle = clearColor;
  59370. this._context.fillRect(0, 0, size.width, size.height);
  59371. }
  59372. this._context.font = font;
  59373. if (x === null || x === undefined) {
  59374. var textSize = this._context.measureText(text);
  59375. x = (size.width - textSize.width) / 2;
  59376. }
  59377. if (y === null || y === undefined) {
  59378. var fontSize = parseInt((font.replace(/\D/g, '')));
  59379. ;
  59380. y = (size.height / 2) + (fontSize / 3.65);
  59381. }
  59382. this._context.fillStyle = color;
  59383. this._context.fillText(text, x, y);
  59384. if (update) {
  59385. this.update(invertY);
  59386. }
  59387. };
  59388. DynamicTexture.prototype.clone = function () {
  59389. var scene = this.getScene();
  59390. if (!scene) {
  59391. return this;
  59392. }
  59393. var textureSize = this.getSize();
  59394. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  59395. // Base texture
  59396. newTexture.hasAlpha = this.hasAlpha;
  59397. newTexture.level = this.level;
  59398. // Dynamic Texture
  59399. newTexture.wrapU = this.wrapU;
  59400. newTexture.wrapV = this.wrapV;
  59401. return newTexture;
  59402. };
  59403. DynamicTexture.prototype._rebuild = function () {
  59404. this.update();
  59405. };
  59406. return DynamicTexture;
  59407. }(BABYLON.Texture));
  59408. BABYLON.DynamicTexture = DynamicTexture;
  59409. })(BABYLON || (BABYLON = {}));
  59410. //# sourceMappingURL=babylon.dynamicTexture.js.map
  59411. var BABYLON;
  59412. (function (BABYLON) {
  59413. var VideoTexture = /** @class */ (function (_super) {
  59414. __extends(VideoTexture, _super);
  59415. /**
  59416. * Creates a video texture.
  59417. * Sample : https://doc.babylonjs.com/how_to/video_texture
  59418. * @param {string | null} name optional name, will detect from video source, if not defined
  59419. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  59420. * @param {BABYLON.Scene} scene is obviously the current scene.
  59421. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  59422. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  59423. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  59424. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  59425. */
  59426. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  59427. if (generateMipMaps === void 0) { generateMipMaps = false; }
  59428. if (invertY === void 0) { invertY = false; }
  59429. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  59430. if (settings === void 0) { settings = {
  59431. autoPlay: true,
  59432. loop: true,
  59433. autoUpdateTexture: true,
  59434. }; }
  59435. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  59436. _this._createInternalTexture = function () {
  59437. if (_this._texture != null) {
  59438. return;
  59439. }
  59440. if (!_this._engine.needPOTTextures ||
  59441. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  59442. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  59443. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  59444. }
  59445. else {
  59446. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59447. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59448. _this._generateMipMaps = false;
  59449. }
  59450. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  59451. _this._texture.isReady = true;
  59452. _this._updateInternalTexture();
  59453. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  59454. _this.onLoadObservable.notifyObservers(_this);
  59455. }
  59456. };
  59457. _this.reset = function () {
  59458. if (_this._texture == null) {
  59459. return;
  59460. }
  59461. _this._texture.dispose();
  59462. _this._texture = null;
  59463. };
  59464. _this._updateInternalTexture = function (e) {
  59465. if (_this._texture == null || !_this._texture.isReady) {
  59466. return;
  59467. }
  59468. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  59469. return;
  59470. }
  59471. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  59472. };
  59473. _this._engine = _this.getScene().getEngine();
  59474. _this._generateMipMaps = generateMipMaps;
  59475. _this._samplingMode = samplingMode;
  59476. _this.autoUpdateTexture = settings.autoUpdateTexture;
  59477. _this.name = name || _this._getName(src);
  59478. _this.video = _this._getVideo(src);
  59479. if (settings.autoPlay !== undefined) {
  59480. _this.video.autoplay = settings.autoPlay;
  59481. }
  59482. if (settings.loop !== undefined) {
  59483. _this.video.loop = settings.loop;
  59484. }
  59485. _this.video.addEventListener("canplay", _this._createInternalTexture);
  59486. _this.video.addEventListener("paused", _this._updateInternalTexture);
  59487. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  59488. _this.video.addEventListener("emptied", _this.reset);
  59489. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  59490. _this._createInternalTexture();
  59491. }
  59492. return _this;
  59493. }
  59494. VideoTexture.prototype._getName = function (src) {
  59495. if (src instanceof HTMLVideoElement) {
  59496. return src.currentSrc;
  59497. }
  59498. if (typeof src === "object") {
  59499. return src.toString();
  59500. }
  59501. return src;
  59502. };
  59503. ;
  59504. VideoTexture.prototype._getVideo = function (src) {
  59505. if (src instanceof HTMLVideoElement) {
  59506. BABYLON.Tools.SetCorsBehavior(src.currentSrc, src);
  59507. return src;
  59508. }
  59509. var video = document.createElement("video");
  59510. if (typeof src === "string") {
  59511. BABYLON.Tools.SetCorsBehavior(src, video);
  59512. video.src = src;
  59513. }
  59514. else {
  59515. BABYLON.Tools.SetCorsBehavior(src[0], video);
  59516. src.forEach(function (url) {
  59517. var source = document.createElement("source");
  59518. source.src = url;
  59519. video.appendChild(source);
  59520. });
  59521. }
  59522. return video;
  59523. };
  59524. ;
  59525. /**
  59526. * Internal method to initiate `update`.
  59527. */
  59528. VideoTexture.prototype._rebuild = function () {
  59529. this.update();
  59530. };
  59531. /**
  59532. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  59533. */
  59534. VideoTexture.prototype.update = function () {
  59535. if (!this.autoUpdateTexture) {
  59536. // Expecting user to call `updateTexture` manually
  59537. return;
  59538. }
  59539. this.updateTexture(true);
  59540. };
  59541. /**
  59542. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  59543. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  59544. */
  59545. VideoTexture.prototype.updateTexture = function (isVisible) {
  59546. if (!isVisible) {
  59547. return;
  59548. }
  59549. if (this.video.paused) {
  59550. return;
  59551. }
  59552. this._updateInternalTexture();
  59553. };
  59554. /**
  59555. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  59556. * @param url New url.
  59557. */
  59558. VideoTexture.prototype.updateURL = function (url) {
  59559. this.video.src = url;
  59560. };
  59561. VideoTexture.prototype.dispose = function () {
  59562. _super.prototype.dispose.call(this);
  59563. this.video.removeEventListener("canplay", this._createInternalTexture);
  59564. this.video.removeEventListener("paused", this._updateInternalTexture);
  59565. this.video.removeEventListener("seeked", this._updateInternalTexture);
  59566. this.video.removeEventListener("emptied", this.reset);
  59567. this.video.pause();
  59568. };
  59569. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  59570. var video = document.createElement("video");
  59571. var constraintsDeviceId;
  59572. if (constraints && constraints.deviceId) {
  59573. constraintsDeviceId = {
  59574. exact: constraints.deviceId,
  59575. };
  59576. }
  59577. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  59578. if (navigator.mediaDevices) {
  59579. navigator.mediaDevices.getUserMedia({ video: constraints })
  59580. .then(function (stream) {
  59581. if (video.mozSrcObject !== undefined) {
  59582. // hack for Firefox < 19
  59583. video.mozSrcObject = stream;
  59584. }
  59585. else {
  59586. video.srcObject = stream;
  59587. }
  59588. var onPlaying = function () {
  59589. if (onReady) {
  59590. onReady(new VideoTexture("video", video, scene, true, true));
  59591. }
  59592. video.removeEventListener("playing", onPlaying);
  59593. };
  59594. video.addEventListener("playing", onPlaying);
  59595. video.play();
  59596. })
  59597. .catch(function (err) {
  59598. BABYLON.Tools.Error(err.name);
  59599. });
  59600. }
  59601. else {
  59602. navigator.getUserMedia =
  59603. navigator.getUserMedia ||
  59604. navigator.webkitGetUserMedia ||
  59605. navigator.mozGetUserMedia ||
  59606. navigator.msGetUserMedia;
  59607. if (navigator.getUserMedia) {
  59608. navigator.getUserMedia({
  59609. video: {
  59610. deviceId: constraintsDeviceId,
  59611. width: {
  59612. min: (constraints && constraints.minWidth) || 256,
  59613. max: (constraints && constraints.maxWidth) || 640,
  59614. },
  59615. height: {
  59616. min: (constraints && constraints.minHeight) || 256,
  59617. max: (constraints && constraints.maxHeight) || 480,
  59618. },
  59619. },
  59620. }, function (stream) {
  59621. if (video.mozSrcObject !== undefined) {
  59622. // hack for Firefox < 19
  59623. video.mozSrcObject = stream;
  59624. }
  59625. else {
  59626. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  59627. }
  59628. video.play();
  59629. if (onReady) {
  59630. onReady(new VideoTexture("video", video, scene, true, true));
  59631. }
  59632. }, function (e) {
  59633. BABYLON.Tools.Error(e.name);
  59634. });
  59635. }
  59636. }
  59637. };
  59638. return VideoTexture;
  59639. }(BABYLON.Texture));
  59640. BABYLON.VideoTexture = VideoTexture;
  59641. })(BABYLON || (BABYLON = {}));
  59642. //# sourceMappingURL=babylon.videoTexture.js.map
  59643. var BABYLON;
  59644. (function (BABYLON) {
  59645. var RawTexture = /** @class */ (function (_super) {
  59646. __extends(RawTexture, _super);
  59647. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  59648. if (generateMipMaps === void 0) { generateMipMaps = true; }
  59649. if (invertY === void 0) { invertY = false; }
  59650. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  59651. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  59652. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  59653. _this.format = format;
  59654. _this._engine = scene.getEngine();
  59655. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  59656. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59657. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59658. return _this;
  59659. }
  59660. RawTexture.prototype.update = function (data) {
  59661. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  59662. };
  59663. // Statics
  59664. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  59665. if (generateMipMaps === void 0) { generateMipMaps = true; }
  59666. if (invertY === void 0) { invertY = false; }
  59667. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  59668. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  59669. };
  59670. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  59671. if (generateMipMaps === void 0) { generateMipMaps = true; }
  59672. if (invertY === void 0) { invertY = false; }
  59673. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  59674. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  59675. };
  59676. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  59677. if (generateMipMaps === void 0) { generateMipMaps = true; }
  59678. if (invertY === void 0) { invertY = false; }
  59679. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  59680. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  59681. };
  59682. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  59683. if (generateMipMaps === void 0) { generateMipMaps = true; }
  59684. if (invertY === void 0) { invertY = false; }
  59685. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  59686. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  59687. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  59688. };
  59689. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  59690. if (generateMipMaps === void 0) { generateMipMaps = true; }
  59691. if (invertY === void 0) { invertY = false; }
  59692. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  59693. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  59694. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  59695. };
  59696. return RawTexture;
  59697. }(BABYLON.Texture));
  59698. BABYLON.RawTexture = RawTexture;
  59699. })(BABYLON || (BABYLON = {}));
  59700. //# sourceMappingURL=babylon.rawTexture.js.map
  59701. var BABYLON;
  59702. (function (BABYLON) {
  59703. /**
  59704. * PostProcess can be used to apply a shader to a texture after it has been rendered
  59705. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  59706. */
  59707. var PostProcess = /** @class */ (function () {
  59708. /**
  59709. * Creates a new instance of @see PostProcess
  59710. * @param name The name of the PostProcess.
  59711. * @param fragmentUrl The url of the fragment shader to be used.
  59712. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  59713. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  59714. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  59715. * @param camera The camera to apply the render pass to.
  59716. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  59717. * @param engine The engine which the post process will be applied. (default: current engine)
  59718. * @param reusable If the post process can be reused on the same frame. (default: false)
  59719. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  59720. * @param textureType Type of textures used when performing the post process. (default: 0)
  59721. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  59722. * @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
  59723. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  59724. */
  59725. function PostProcess(/** Name of the PostProcess. */ name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  59726. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  59727. if (defines === void 0) { defines = null; }
  59728. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  59729. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  59730. if (blockCompilation === void 0) { blockCompilation = false; }
  59731. this.name = name;
  59732. /**
  59733. * Width of the texture to apply the post process on
  59734. */
  59735. this.width = -1;
  59736. /**
  59737. * Height of the texture to apply the post process on
  59738. */
  59739. this.height = -1;
  59740. /**
  59741. * If the buffer needs to be cleared before applying the post process. (default: true)
  59742. * Should be set to false if shader will overwrite all previous pixels.
  59743. */
  59744. this.autoClear = true;
  59745. /**
  59746. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  59747. */
  59748. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  59749. /**
  59750. * Animations to be used for the post processing
  59751. */
  59752. this.animations = new Array();
  59753. /**
  59754. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  59755. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  59756. */
  59757. this.enablePixelPerfectMode = false;
  59758. /**
  59759. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  59760. */
  59761. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  59762. /**
  59763. * Force textures to be a power of two (default: false)
  59764. */
  59765. this.alwaysForcePOT = false;
  59766. /**
  59767. * Number of sample textures (default: 1)
  59768. */
  59769. this.samples = 1;
  59770. /**
  59771. * Modify the scale of the post process to be the same as the viewport (default: false)
  59772. */
  59773. this.adaptScaleToCurrentViewport = false;
  59774. this._reusable = false;
  59775. /**
  59776. * Smart array of input and output textures for the post process.
  59777. */
  59778. this._textures = new BABYLON.SmartArray(2);
  59779. /**
  59780. * The index in _textures that corresponds to the output texture.
  59781. */
  59782. this._currentRenderTextureInd = 0;
  59783. this._scaleRatio = new BABYLON.Vector2(1, 1);
  59784. this._texelSize = BABYLON.Vector2.Zero();
  59785. // Events
  59786. /**
  59787. * An event triggered when the postprocess is activated.
  59788. * @type {BABYLON.Observable}
  59789. */
  59790. this.onActivateObservable = new BABYLON.Observable();
  59791. /**
  59792. * An event triggered when the postprocess changes its size.
  59793. * @type {BABYLON.Observable}
  59794. */
  59795. this.onSizeChangedObservable = new BABYLON.Observable();
  59796. /**
  59797. * An event triggered when the postprocess applies its effect.
  59798. * @type {BABYLON.Observable}
  59799. */
  59800. this.onApplyObservable = new BABYLON.Observable();
  59801. /**
  59802. * An event triggered before rendering the postprocess
  59803. * @type {BABYLON.Observable}
  59804. */
  59805. this.onBeforeRenderObservable = new BABYLON.Observable();
  59806. /**
  59807. * An event triggered after rendering the postprocess
  59808. * @type {BABYLON.Observable}
  59809. */
  59810. this.onAfterRenderObservable = new BABYLON.Observable();
  59811. if (camera != null) {
  59812. this._camera = camera;
  59813. this._scene = camera.getScene();
  59814. camera.attachPostProcess(this);
  59815. this._engine = this._scene.getEngine();
  59816. this._scene.postProcesses.push(this);
  59817. }
  59818. else if (engine) {
  59819. this._engine = engine;
  59820. this._engine.postProcesses.push(this);
  59821. }
  59822. this._options = options;
  59823. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  59824. this._reusable = reusable || false;
  59825. this._textureType = textureType;
  59826. this._samplers = samplers || [];
  59827. this._samplers.push("textureSampler");
  59828. this._fragmentUrl = fragmentUrl;
  59829. this._vertexUrl = vertexUrl;
  59830. this._parameters = parameters || [];
  59831. this._parameters.push("scale");
  59832. this._indexParameters = indexParameters;
  59833. if (!blockCompilation) {
  59834. this.updateEffect(defines);
  59835. }
  59836. }
  59837. Object.defineProperty(PostProcess.prototype, "onActivate", {
  59838. /**
  59839. * A function that is added to the onActivateObservable
  59840. */
  59841. set: function (callback) {
  59842. if (this._onActivateObserver) {
  59843. this.onActivateObservable.remove(this._onActivateObserver);
  59844. }
  59845. if (callback) {
  59846. this._onActivateObserver = this.onActivateObservable.add(callback);
  59847. }
  59848. },
  59849. enumerable: true,
  59850. configurable: true
  59851. });
  59852. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  59853. /**
  59854. * A function that is added to the onSizeChangedObservable
  59855. */
  59856. set: function (callback) {
  59857. if (this._onSizeChangedObserver) {
  59858. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  59859. }
  59860. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  59861. },
  59862. enumerable: true,
  59863. configurable: true
  59864. });
  59865. Object.defineProperty(PostProcess.prototype, "onApply", {
  59866. /**
  59867. * A function that is added to the onApplyObservable
  59868. */
  59869. set: function (callback) {
  59870. if (this._onApplyObserver) {
  59871. this.onApplyObservable.remove(this._onApplyObserver);
  59872. }
  59873. this._onApplyObserver = this.onApplyObservable.add(callback);
  59874. },
  59875. enumerable: true,
  59876. configurable: true
  59877. });
  59878. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  59879. /**
  59880. * A function that is added to the onBeforeRenderObservable
  59881. */
  59882. set: function (callback) {
  59883. if (this._onBeforeRenderObserver) {
  59884. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  59885. }
  59886. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  59887. },
  59888. enumerable: true,
  59889. configurable: true
  59890. });
  59891. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  59892. /**
  59893. * A function that is added to the onAfterRenderObservable
  59894. */
  59895. set: function (callback) {
  59896. if (this._onAfterRenderObserver) {
  59897. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  59898. }
  59899. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  59900. },
  59901. enumerable: true,
  59902. configurable: true
  59903. });
  59904. Object.defineProperty(PostProcess.prototype, "inputTexture", {
  59905. /**
  59906. * 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
  59907. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  59908. */
  59909. get: function () {
  59910. return this._textures.data[this._currentRenderTextureInd];
  59911. },
  59912. set: function (value) {
  59913. this._forcedOutputTexture = value;
  59914. },
  59915. enumerable: true,
  59916. configurable: true
  59917. });
  59918. /**
  59919. * Gets the camera which post process is applied to.
  59920. * @returns The camera the post process is applied to.
  59921. */
  59922. PostProcess.prototype.getCamera = function () {
  59923. return this._camera;
  59924. };
  59925. Object.defineProperty(PostProcess.prototype, "texelSize", {
  59926. /**
  59927. * Gets the texel size of the postprocess.
  59928. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  59929. */
  59930. get: function () {
  59931. if (this._shareOutputWithPostProcess) {
  59932. return this._shareOutputWithPostProcess.texelSize;
  59933. }
  59934. if (this._forcedOutputTexture) {
  59935. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  59936. }
  59937. return this._texelSize;
  59938. },
  59939. enumerable: true,
  59940. configurable: true
  59941. });
  59942. /**
  59943. * Gets the engine which this post process belongs to.
  59944. * @returns The engine the post process was enabled with.
  59945. */
  59946. PostProcess.prototype.getEngine = function () {
  59947. return this._engine;
  59948. };
  59949. /**
  59950. * The effect that is created when initializing the post process.
  59951. * @returns The created effect corrisponding the the postprocess.
  59952. */
  59953. PostProcess.prototype.getEffect = function () {
  59954. return this._effect;
  59955. };
  59956. /**
  59957. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  59958. * @param postProcess The post process to share the output with.
  59959. * @returns This post process.
  59960. */
  59961. PostProcess.prototype.shareOutputWith = function (postProcess) {
  59962. this._disposeTextures();
  59963. this._shareOutputWithPostProcess = postProcess;
  59964. return this;
  59965. };
  59966. /**
  59967. * Reverses the effect of calling shareOutputWith and returns the post process back to its original state.
  59968. * This should be called if the post process that shares output with this post process is disabled/disposed.
  59969. */
  59970. PostProcess.prototype.useOwnOutput = function () {
  59971. if (this._textures.length == 0) {
  59972. this._textures = new BABYLON.SmartArray(2);
  59973. }
  59974. this._shareOutputWithPostProcess = null;
  59975. };
  59976. /**
  59977. * Updates the effect with the current post process compile time values and recompiles the shader.
  59978. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  59979. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  59980. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  59981. * @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
  59982. * @param onCompiled Called when the shader has been compiled.
  59983. * @param onError Called if there is an error when compiling a shader.
  59984. */
  59985. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  59986. if (defines === void 0) { defines = null; }
  59987. if (uniforms === void 0) { uniforms = null; }
  59988. if (samplers === void 0) { samplers = null; }
  59989. 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);
  59990. };
  59991. /**
  59992. * The post process is reusable if it can be used multiple times within one frame.
  59993. * @returns If the post process is reusable
  59994. */
  59995. PostProcess.prototype.isReusable = function () {
  59996. return this._reusable;
  59997. };
  59998. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  59999. PostProcess.prototype.markTextureDirty = function () {
  60000. this.width = -1;
  60001. };
  60002. /**
  60003. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  60004. * 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.
  60005. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  60006. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  60007. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  60008. */
  60009. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  60010. var _this = this;
  60011. if (sourceTexture === void 0) { sourceTexture = null; }
  60012. camera = camera || this._camera;
  60013. var scene = camera.getScene();
  60014. var engine = scene.getEngine();
  60015. var maxSize = engine.getCaps().maxTextureSize;
  60016. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  60017. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  60018. // 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
  60019. var webVRCamera = camera.parent;
  60020. if (webVRCamera && (webVRCamera.leftCamera == camera || webVRCamera.rightCamera == camera)) {
  60021. requiredWidth /= 2;
  60022. }
  60023. var desiredWidth = (this._options.width || requiredWidth);
  60024. var desiredHeight = this._options.height || requiredHeight;
  60025. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  60026. if (this.adaptScaleToCurrentViewport) {
  60027. var currentViewport = engine.currentViewport;
  60028. if (currentViewport) {
  60029. desiredWidth *= currentViewport.width;
  60030. desiredHeight *= currentViewport.height;
  60031. }
  60032. }
  60033. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  60034. if (!this._options.width) {
  60035. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  60036. }
  60037. if (!this._options.height) {
  60038. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  60039. }
  60040. }
  60041. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  60042. if (this._textures.length > 0) {
  60043. for (var i = 0; i < this._textures.length; i++) {
  60044. this._engine._releaseTexture(this._textures.data[i]);
  60045. }
  60046. this._textures.reset();
  60047. }
  60048. this.width = desiredWidth;
  60049. this.height = desiredHeight;
  60050. var textureSize = { width: this.width, height: this.height };
  60051. var textureOptions = {
  60052. generateMipMaps: false,
  60053. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  60054. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  60055. samplingMode: this.renderTargetSamplingMode,
  60056. type: this._textureType
  60057. };
  60058. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  60059. if (this._reusable) {
  60060. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  60061. }
  60062. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  60063. this.onSizeChangedObservable.notifyObservers(this);
  60064. }
  60065. this._textures.forEach(function (texture) {
  60066. if (texture.samples !== _this.samples) {
  60067. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  60068. }
  60069. });
  60070. }
  60071. var target;
  60072. if (this._shareOutputWithPostProcess) {
  60073. target = this._shareOutputWithPostProcess.inputTexture;
  60074. }
  60075. else if (this._forcedOutputTexture) {
  60076. target = this._forcedOutputTexture;
  60077. this.width = this._forcedOutputTexture.width;
  60078. this.height = this._forcedOutputTexture.height;
  60079. }
  60080. else {
  60081. target = this.inputTexture;
  60082. }
  60083. // Bind the input of this post process to be used as the output of the previous post process.
  60084. if (this.enablePixelPerfectMode) {
  60085. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  60086. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, true);
  60087. }
  60088. else {
  60089. this._scaleRatio.copyFromFloats(1, 1);
  60090. this._engine.bindFramebuffer(target, 0, undefined, undefined, true);
  60091. }
  60092. this.onActivateObservable.notifyObservers(camera);
  60093. // Clear
  60094. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  60095. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  60096. }
  60097. if (this._reusable) {
  60098. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  60099. }
  60100. };
  60101. Object.defineProperty(PostProcess.prototype, "isSupported", {
  60102. /**
  60103. * If the post process is supported.
  60104. */
  60105. get: function () {
  60106. return this._effect.isSupported;
  60107. },
  60108. enumerable: true,
  60109. configurable: true
  60110. });
  60111. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  60112. /**
  60113. * The aspect ratio of the output texture.
  60114. */
  60115. get: function () {
  60116. if (this._shareOutputWithPostProcess) {
  60117. return this._shareOutputWithPostProcess.aspectRatio;
  60118. }
  60119. if (this._forcedOutputTexture) {
  60120. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  60121. }
  60122. return this.width / this.height;
  60123. },
  60124. enumerable: true,
  60125. configurable: true
  60126. });
  60127. /**
  60128. * Get a value indicating if the post-process is ready to be used
  60129. * @returns true if the post-process is ready (shader is compiled)
  60130. */
  60131. PostProcess.prototype.isReady = function () {
  60132. return this._effect && this._effect.isReady();
  60133. };
  60134. /**
  60135. * Binds all textures and uniforms to the shader, this will be run on every pass.
  60136. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  60137. */
  60138. PostProcess.prototype.apply = function () {
  60139. // Check
  60140. if (!this._effect || !this._effect.isReady())
  60141. return null;
  60142. // States
  60143. this._engine.enableEffect(this._effect);
  60144. this._engine.setState(false);
  60145. this._engine.setDepthBuffer(false);
  60146. this._engine.setDepthWrite(false);
  60147. // Alpha
  60148. this._engine.setAlphaMode(this.alphaMode);
  60149. if (this.alphaConstants) {
  60150. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  60151. }
  60152. // Bind the output texture of the preivous post process as the input to this post process.
  60153. var source;
  60154. if (this._shareOutputWithPostProcess) {
  60155. source = this._shareOutputWithPostProcess.inputTexture;
  60156. }
  60157. else if (this._forcedOutputTexture) {
  60158. source = this._forcedOutputTexture;
  60159. }
  60160. else {
  60161. source = this.inputTexture;
  60162. }
  60163. this._effect._bindTexture("textureSampler", source);
  60164. // Parameters
  60165. this._effect.setVector2("scale", this._scaleRatio);
  60166. this.onApplyObservable.notifyObservers(this._effect);
  60167. return this._effect;
  60168. };
  60169. PostProcess.prototype._disposeTextures = function () {
  60170. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  60171. return;
  60172. }
  60173. if (this._textures.length > 0) {
  60174. for (var i = 0; i < this._textures.length; i++) {
  60175. this._engine._releaseTexture(this._textures.data[i]);
  60176. }
  60177. }
  60178. this._textures.dispose();
  60179. };
  60180. /**
  60181. * Disposes the post process.
  60182. * @param camera The camera to dispose the post process on.
  60183. */
  60184. PostProcess.prototype.dispose = function (camera) {
  60185. camera = camera || this._camera;
  60186. this._disposeTextures();
  60187. if (this._scene) {
  60188. var index_1 = this._scene.postProcesses.indexOf(this);
  60189. if (index_1 !== -1) {
  60190. this._scene.postProcesses.splice(index_1, 1);
  60191. }
  60192. }
  60193. else {
  60194. var index_2 = this._engine.postProcesses.indexOf(this);
  60195. if (index_2 !== -1) {
  60196. this._engine.postProcesses.splice(index_2, 1);
  60197. }
  60198. }
  60199. if (!camera) {
  60200. return;
  60201. }
  60202. camera.detachPostProcess(this);
  60203. var index = camera._postProcesses.indexOf(this);
  60204. if (index === 0 && camera._postProcesses.length > 0) {
  60205. var firstPostProcess = this._camera._getFirstPostProcess();
  60206. if (firstPostProcess) {
  60207. firstPostProcess.markTextureDirty();
  60208. }
  60209. }
  60210. this.onActivateObservable.clear();
  60211. this.onAfterRenderObservable.clear();
  60212. this.onApplyObservable.clear();
  60213. this.onBeforeRenderObservable.clear();
  60214. this.onSizeChangedObservable.clear();
  60215. };
  60216. return PostProcess;
  60217. }());
  60218. BABYLON.PostProcess = PostProcess;
  60219. })(BABYLON || (BABYLON = {}));
  60220. //# sourceMappingURL=babylon.postProcess.js.map
  60221. var BABYLON;
  60222. (function (BABYLON) {
  60223. var PassPostProcess = /** @class */ (function (_super) {
  60224. __extends(PassPostProcess, _super);
  60225. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  60226. if (camera === void 0) { camera = null; }
  60227. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  60228. if (blockCompilation === void 0) { blockCompilation = false; }
  60229. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType, undefined, null, blockCompilation) || this;
  60230. }
  60231. return PassPostProcess;
  60232. }(BABYLON.PostProcess));
  60233. BABYLON.PassPostProcess = PassPostProcess;
  60234. })(BABYLON || (BABYLON = {}));
  60235. //# sourceMappingURL=babylon.passPostProcess.js.map
  60236. var __assign = (this && this.__assign) || Object.assign || function(t) {
  60237. for (var s, i = 1, n = arguments.length; i < n; i++) {
  60238. s = arguments[i];
  60239. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  60240. t[p] = s[p];
  60241. }
  60242. return t;
  60243. };
  60244. var BABYLON;
  60245. (function (BABYLON) {
  60246. /**
  60247. * Default implementation of @see IShadowGenerator.
  60248. * This is the main object responsible of generating shadows in the framework.
  60249. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  60250. */
  60251. var ShadowGenerator = /** @class */ (function () {
  60252. /**
  60253. * Creates a ShadowGenerator object.
  60254. * A ShadowGenerator is the required tool to use the shadows.
  60255. * Each light casting shadows needs to use its own ShadowGenerator.
  60256. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  60257. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  60258. * @param light The light object generating the shadows.
  60259. * @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.
  60260. */
  60261. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  60262. this._bias = 0.00005;
  60263. this._blurBoxOffset = 1;
  60264. this._blurScale = 2;
  60265. this._blurKernel = 1;
  60266. this._useKernelBlur = false;
  60267. this._filter = ShadowGenerator.FILTER_NONE;
  60268. this._darkness = 0;
  60269. this._transparencyShadow = false;
  60270. /**
  60271. * Controls the extent to which the shadows fade out at the edge of the frustum
  60272. * Used only by directionals and spots
  60273. */
  60274. this.frustumEdgeFalloff = 0;
  60275. /**
  60276. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  60277. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  60278. * It might on the other hand introduce peter panning.
  60279. */
  60280. this.forceBackFacesOnly = false;
  60281. this._lightDirection = BABYLON.Vector3.Zero();
  60282. this._viewMatrix = BABYLON.Matrix.Zero();
  60283. this._projectionMatrix = BABYLON.Matrix.Zero();
  60284. this._transformMatrix = BABYLON.Matrix.Zero();
  60285. this._cachedPosition = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  60286. this._cachedDirection = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  60287. this._currentFaceIndex = 0;
  60288. this._currentFaceIndexCache = 0;
  60289. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  60290. this._mapSize = mapSize;
  60291. this._light = light;
  60292. this._scene = light.getScene();
  60293. light._shadowGenerator = this;
  60294. // Texture type fallback from float to int if not supported.
  60295. var caps = this._scene.getEngine().getCaps();
  60296. if (!useFullFloatFirst) {
  60297. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  60298. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  60299. }
  60300. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  60301. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  60302. }
  60303. else {
  60304. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  60305. }
  60306. }
  60307. else {
  60308. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  60309. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  60310. }
  60311. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  60312. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  60313. }
  60314. else {
  60315. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  60316. }
  60317. }
  60318. this._initializeGenerator();
  60319. }
  60320. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  60321. /**
  60322. * Shadow generator mode None: no filtering applied.
  60323. */
  60324. get: function () {
  60325. return ShadowGenerator._FILTER_NONE;
  60326. },
  60327. enumerable: true,
  60328. configurable: true
  60329. });
  60330. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  60331. /**
  60332. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  60333. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  60334. */
  60335. get: function () {
  60336. return ShadowGenerator._FILTER_POISSONSAMPLING;
  60337. },
  60338. enumerable: true,
  60339. configurable: true
  60340. });
  60341. Object.defineProperty(ShadowGenerator, "FILTER_EXPONENTIALSHADOWMAP", {
  60342. /**
  60343. * Shadow generator mode ESM: Exponential Shadow Mapping.
  60344. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  60345. */
  60346. get: function () {
  60347. return ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP;
  60348. },
  60349. enumerable: true,
  60350. configurable: true
  60351. });
  60352. Object.defineProperty(ShadowGenerator, "FILTER_BLUREXPONENTIALSHADOWMAP", {
  60353. /**
  60354. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  60355. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  60356. */
  60357. get: function () {
  60358. return ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP;
  60359. },
  60360. enumerable: true,
  60361. configurable: true
  60362. });
  60363. Object.defineProperty(ShadowGenerator, "FILTER_CLOSEEXPONENTIALSHADOWMAP", {
  60364. /**
  60365. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  60366. * edge artifacts on steep falloff.
  60367. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  60368. */
  60369. get: function () {
  60370. return ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP;
  60371. },
  60372. enumerable: true,
  60373. configurable: true
  60374. });
  60375. Object.defineProperty(ShadowGenerator, "FILTER_BLURCLOSEEXPONENTIALSHADOWMAP", {
  60376. /**
  60377. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  60378. * edge artifacts on steep falloff.
  60379. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  60380. */
  60381. get: function () {
  60382. return ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  60383. },
  60384. enumerable: true,
  60385. configurable: true
  60386. });
  60387. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  60388. /**
  60389. * Gets the bias: offset applied on the depth preventing acnea.
  60390. */
  60391. get: function () {
  60392. return this._bias;
  60393. },
  60394. /**
  60395. * Sets the bias: offset applied on the depth preventing acnea.
  60396. */
  60397. set: function (bias) {
  60398. this._bias = bias;
  60399. },
  60400. enumerable: true,
  60401. configurable: true
  60402. });
  60403. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  60404. /**
  60405. * Gets the blur box offset: offset applied during the blur pass.
  60406. * Only usefull if useKernelBlur = false
  60407. */
  60408. get: function () {
  60409. return this._blurBoxOffset;
  60410. },
  60411. /**
  60412. * Sets the blur box offset: offset applied during the blur pass.
  60413. * Only usefull if useKernelBlur = false
  60414. */
  60415. set: function (value) {
  60416. if (this._blurBoxOffset === value) {
  60417. return;
  60418. }
  60419. this._blurBoxOffset = value;
  60420. this._disposeBlurPostProcesses();
  60421. },
  60422. enumerable: true,
  60423. configurable: true
  60424. });
  60425. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  60426. /**
  60427. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  60428. * 2 means half of the size.
  60429. */
  60430. get: function () {
  60431. return this._blurScale;
  60432. },
  60433. /**
  60434. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  60435. * 2 means half of the size.
  60436. */
  60437. set: function (value) {
  60438. if (this._blurScale === value) {
  60439. return;
  60440. }
  60441. this._blurScale = value;
  60442. this._disposeBlurPostProcesses();
  60443. },
  60444. enumerable: true,
  60445. configurable: true
  60446. });
  60447. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  60448. /**
  60449. * Gets the blur kernel: kernel size of the blur pass.
  60450. * Only usefull if useKernelBlur = true
  60451. */
  60452. get: function () {
  60453. return this._blurKernel;
  60454. },
  60455. /**
  60456. * Sets the blur kernel: kernel size of the blur pass.
  60457. * Only usefull if useKernelBlur = true
  60458. */
  60459. set: function (value) {
  60460. if (this._blurKernel === value) {
  60461. return;
  60462. }
  60463. this._blurKernel = value;
  60464. this._disposeBlurPostProcesses();
  60465. },
  60466. enumerable: true,
  60467. configurable: true
  60468. });
  60469. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  60470. /**
  60471. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  60472. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  60473. */
  60474. get: function () {
  60475. return this._useKernelBlur;
  60476. },
  60477. /**
  60478. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  60479. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  60480. */
  60481. set: function (value) {
  60482. if (this._useKernelBlur === value) {
  60483. return;
  60484. }
  60485. this._useKernelBlur = value;
  60486. this._disposeBlurPostProcesses();
  60487. },
  60488. enumerable: true,
  60489. configurable: true
  60490. });
  60491. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  60492. /**
  60493. * Gets the depth scale used in ESM mode.
  60494. */
  60495. get: function () {
  60496. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  60497. },
  60498. /**
  60499. * Sets the depth scale used in ESM mode.
  60500. * This can override the scale stored on the light.
  60501. */
  60502. set: function (value) {
  60503. this._depthScale = value;
  60504. },
  60505. enumerable: true,
  60506. configurable: true
  60507. });
  60508. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  60509. /**
  60510. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  60511. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  60512. */
  60513. get: function () {
  60514. return this._filter;
  60515. },
  60516. /**
  60517. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  60518. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  60519. */
  60520. set: function (value) {
  60521. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  60522. if (this._light.needCube()) {
  60523. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  60524. this.useExponentialShadowMap = true;
  60525. return;
  60526. }
  60527. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  60528. this.useCloseExponentialShadowMap = true;
  60529. return;
  60530. }
  60531. }
  60532. if (this._filter === value) {
  60533. return;
  60534. }
  60535. this._filter = value;
  60536. this._disposeBlurPostProcesses();
  60537. this._applyFilterValues();
  60538. this._light._markMeshesAsLightDirty();
  60539. },
  60540. enumerable: true,
  60541. configurable: true
  60542. });
  60543. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  60544. /**
  60545. * Gets if the current filter is set to Poisson Sampling aka PCF.
  60546. */
  60547. get: function () {
  60548. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  60549. },
  60550. /**
  60551. * Sets the current filter to Poisson Sampling aka PCF.
  60552. */
  60553. set: function (value) {
  60554. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  60555. return;
  60556. }
  60557. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  60558. },
  60559. enumerable: true,
  60560. configurable: true
  60561. });
  60562. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  60563. /**
  60564. * Gets if the current filter is set to VSM.
  60565. * DEPRECATED. Should use useExponentialShadowMap instead.
  60566. */
  60567. get: function () {
  60568. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  60569. return this.useExponentialShadowMap;
  60570. },
  60571. /**
  60572. * Sets the current filter is to VSM.
  60573. * DEPRECATED. Should use useExponentialShadowMap instead.
  60574. */
  60575. set: function (value) {
  60576. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  60577. this.useExponentialShadowMap = value;
  60578. },
  60579. enumerable: true,
  60580. configurable: true
  60581. });
  60582. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  60583. /**
  60584. * Gets if the current filter is set to blurred VSM.
  60585. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  60586. */
  60587. get: function () {
  60588. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  60589. return this.useBlurExponentialShadowMap;
  60590. },
  60591. /**
  60592. * Sets the current filter is to blurred VSM.
  60593. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  60594. */
  60595. set: function (value) {
  60596. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  60597. this.useBlurExponentialShadowMap = value;
  60598. },
  60599. enumerable: true,
  60600. configurable: true
  60601. });
  60602. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  60603. /**
  60604. * Gets if the current filter is set to ESM.
  60605. */
  60606. get: function () {
  60607. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  60608. },
  60609. /**
  60610. * Sets the current filter is to ESM.
  60611. */
  60612. set: function (value) {
  60613. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  60614. return;
  60615. }
  60616. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  60617. },
  60618. enumerable: true,
  60619. configurable: true
  60620. });
  60621. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  60622. /**
  60623. * Gets if the current filter is set to filtered ESM.
  60624. */
  60625. get: function () {
  60626. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  60627. },
  60628. /**
  60629. * Gets if the current filter is set to filtered ESM.
  60630. */
  60631. set: function (value) {
  60632. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  60633. return;
  60634. }
  60635. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  60636. },
  60637. enumerable: true,
  60638. configurable: true
  60639. });
  60640. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  60641. /**
  60642. * Gets if the current filter is set to "close ESM" (using the inverse of the
  60643. * exponential to prevent steep falloff artifacts).
  60644. */
  60645. get: function () {
  60646. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  60647. },
  60648. /**
  60649. * Sets the current filter to "close ESM" (using the inverse of the
  60650. * exponential to prevent steep falloff artifacts).
  60651. */
  60652. set: function (value) {
  60653. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  60654. return;
  60655. }
  60656. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  60657. },
  60658. enumerable: true,
  60659. configurable: true
  60660. });
  60661. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  60662. /**
  60663. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  60664. * exponential to prevent steep falloff artifacts).
  60665. */
  60666. get: function () {
  60667. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  60668. },
  60669. /**
  60670. * Sets the current filter to fileterd "close ESM" (using the inverse of the
  60671. * exponential to prevent steep falloff artifacts).
  60672. */
  60673. set: function (value) {
  60674. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  60675. return;
  60676. }
  60677. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  60678. },
  60679. enumerable: true,
  60680. configurable: true
  60681. });
  60682. /**
  60683. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  60684. * 0 means strongest and 1 would means no shadow.
  60685. * @returns the darkness.
  60686. */
  60687. ShadowGenerator.prototype.getDarkness = function () {
  60688. return this._darkness;
  60689. };
  60690. /**
  60691. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  60692. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  60693. * @returns the shadow generator allowing fluent coding.
  60694. */
  60695. ShadowGenerator.prototype.setDarkness = function (darkness) {
  60696. if (darkness >= 1.0)
  60697. this._darkness = 1.0;
  60698. else if (darkness <= 0.0)
  60699. this._darkness = 0.0;
  60700. else
  60701. this._darkness = darkness;
  60702. return this;
  60703. };
  60704. /**
  60705. * Sets the ability to have transparent shadow (boolean).
  60706. * @param transparent True if transparent else False
  60707. * @returns the shadow generator allowing fluent coding
  60708. */
  60709. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  60710. this._transparencyShadow = transparent;
  60711. return this;
  60712. };
  60713. /**
  60714. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  60715. * @returns The render target texture if present otherwise, null
  60716. */
  60717. ShadowGenerator.prototype.getShadowMap = function () {
  60718. return this._shadowMap;
  60719. };
  60720. /**
  60721. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  60722. * @returns The render target texture if the shadow map is present otherwise, null
  60723. */
  60724. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  60725. if (this._shadowMap2) {
  60726. return this._shadowMap2;
  60727. }
  60728. return this._shadowMap;
  60729. };
  60730. /**
  60731. * Helper function to add a mesh and its descendants to the list of shadow casters.
  60732. * @param mesh Mesh to add
  60733. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  60734. * @returns the Shadow Generator itself
  60735. */
  60736. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  60737. if (includeDescendants === void 0) { includeDescendants = true; }
  60738. if (!this._shadowMap) {
  60739. return this;
  60740. }
  60741. if (!this._shadowMap.renderList) {
  60742. this._shadowMap.renderList = [];
  60743. }
  60744. this._shadowMap.renderList.push(mesh);
  60745. if (includeDescendants) {
  60746. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  60747. }
  60748. return this;
  60749. var _a;
  60750. };
  60751. /**
  60752. * Helper function to remove a mesh and its descendants from the list of shadow casters
  60753. * @param mesh Mesh to remove
  60754. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  60755. * @returns the Shadow Generator itself
  60756. */
  60757. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  60758. if (includeDescendants === void 0) { includeDescendants = true; }
  60759. if (!this._shadowMap || !this._shadowMap.renderList) {
  60760. return this;
  60761. }
  60762. var index = this._shadowMap.renderList.indexOf(mesh);
  60763. if (index !== -1) {
  60764. this._shadowMap.renderList.splice(index, 1);
  60765. }
  60766. if (includeDescendants) {
  60767. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  60768. var child = _a[_i];
  60769. this.removeShadowCaster(child);
  60770. }
  60771. }
  60772. return this;
  60773. };
  60774. /**
  60775. * Returns the associated light object.
  60776. * @returns the light generating the shadow
  60777. */
  60778. ShadowGenerator.prototype.getLight = function () {
  60779. return this._light;
  60780. };
  60781. ShadowGenerator.prototype._initializeGenerator = function () {
  60782. this._light._markMeshesAsLightDirty();
  60783. this._initializeShadowMap();
  60784. };
  60785. ShadowGenerator.prototype._initializeShadowMap = function () {
  60786. var _this = this;
  60787. // Render target
  60788. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  60789. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60790. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60791. this._shadowMap.anisotropicFilteringLevel = 1;
  60792. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  60793. this._shadowMap.renderParticles = false;
  60794. this._shadowMap.ignoreCameraViewport = true;
  60795. // Record Face Index before render.
  60796. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  60797. _this._currentFaceIndex = faceIndex;
  60798. });
  60799. // Custom render function.
  60800. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  60801. // Blur if required afer render.
  60802. this._shadowMap.onAfterUnbindObservable.add(function () {
  60803. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  60804. return;
  60805. }
  60806. var shadowMap = _this.getShadowMapForRendering();
  60807. if (shadowMap) {
  60808. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  60809. }
  60810. });
  60811. // Clear according to the chosen filter.
  60812. var zero = new BABYLON.Color4(0, 0, 0, 0);
  60813. var one = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  60814. this._shadowMap.onClearObservable.add(function (engine) {
  60815. if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  60816. engine.clear(zero, true, true, true);
  60817. }
  60818. else {
  60819. engine.clear(one, true, true, true);
  60820. }
  60821. });
  60822. };
  60823. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  60824. var _this = this;
  60825. var engine = this._scene.getEngine();
  60826. var targetSize = this._mapSize / this.blurScale;
  60827. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  60828. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  60829. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60830. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60831. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  60832. }
  60833. if (this.useKernelBlur) {
  60834. 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);
  60835. this._kernelBlurXPostprocess.width = targetSize;
  60836. this._kernelBlurXPostprocess.height = targetSize;
  60837. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  60838. effect.setTexture("textureSampler", _this._shadowMap);
  60839. });
  60840. 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);
  60841. this._kernelBlurXPostprocess.autoClear = false;
  60842. this._kernelBlurYPostprocess.autoClear = false;
  60843. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  60844. this._kernelBlurXPostprocess.packedFloat = true;
  60845. this._kernelBlurYPostprocess.packedFloat = true;
  60846. }
  60847. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  60848. }
  60849. else {
  60850. 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);
  60851. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  60852. effect.setFloat2("screenSize", targetSize, targetSize);
  60853. effect.setTexture("textureSampler", _this._shadowMap);
  60854. });
  60855. this._boxBlurPostprocess.autoClear = false;
  60856. this._blurPostProcesses = [this._boxBlurPostprocess];
  60857. }
  60858. };
  60859. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  60860. var index;
  60861. var engine = this._scene.getEngine();
  60862. if (depthOnlySubMeshes.length) {
  60863. engine.setColorWrite(false);
  60864. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  60865. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  60866. }
  60867. engine.setColorWrite(true);
  60868. }
  60869. for (index = 0; index < opaqueSubMeshes.length; index++) {
  60870. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  60871. }
  60872. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  60873. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  60874. }
  60875. if (this._transparencyShadow) {
  60876. for (index = 0; index < transparentSubMeshes.length; index++) {
  60877. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  60878. }
  60879. }
  60880. };
  60881. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  60882. var _this = this;
  60883. var mesh = subMesh.getRenderingMesh();
  60884. var scene = this._scene;
  60885. var engine = scene.getEngine();
  60886. var material = subMesh.getMaterial();
  60887. if (!material) {
  60888. return;
  60889. }
  60890. // Culling
  60891. engine.setState(material.backFaceCulling);
  60892. // Managing instances
  60893. var batch = mesh._getInstancesRenderList(subMesh._id);
  60894. if (batch.mustReturn) {
  60895. return;
  60896. }
  60897. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  60898. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  60899. engine.enableEffect(this._effect);
  60900. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  60901. this._effect.setFloat2("biasAndScale", this.bias, this.depthScale);
  60902. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  60903. this._effect.setVector3("lightPosition", this.getLight().position);
  60904. if (scene.activeCamera) {
  60905. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  60906. }
  60907. // Alpha test
  60908. if (material && material.needAlphaTesting()) {
  60909. var alphaTexture = material.getAlphaTestTexture();
  60910. if (alphaTexture) {
  60911. this._effect.setTexture("diffuseSampler", alphaTexture);
  60912. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  60913. }
  60914. }
  60915. // Bones
  60916. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  60917. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  60918. }
  60919. if (this.forceBackFacesOnly) {
  60920. engine.setState(true, 0, false, true);
  60921. }
  60922. // Draw
  60923. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  60924. if (this.forceBackFacesOnly) {
  60925. engine.setState(true, 0, false, false);
  60926. }
  60927. }
  60928. else {
  60929. // Need to reset refresh rate of the shadowMap
  60930. if (this._shadowMap) {
  60931. this._shadowMap.resetRefreshCounter();
  60932. }
  60933. }
  60934. };
  60935. ShadowGenerator.prototype._applyFilterValues = function () {
  60936. if (!this._shadowMap) {
  60937. return;
  60938. }
  60939. if (this.filter === ShadowGenerator.FILTER_NONE) {
  60940. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  60941. }
  60942. else {
  60943. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  60944. }
  60945. };
  60946. /**
  60947. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  60948. * @param onCompiled Callback triggered at the and of the effects compilation
  60949. * @param options Sets of optional options forcing the compilation with different modes
  60950. */
  60951. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  60952. var _this = this;
  60953. var localOptions = __assign({ useInstances: false }, options);
  60954. var shadowMap = this.getShadowMap();
  60955. if (!shadowMap) {
  60956. if (onCompiled) {
  60957. onCompiled(this);
  60958. }
  60959. return;
  60960. }
  60961. var renderList = shadowMap.renderList;
  60962. if (!renderList) {
  60963. if (onCompiled) {
  60964. onCompiled(this);
  60965. }
  60966. return;
  60967. }
  60968. var subMeshes = new Array();
  60969. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  60970. var mesh = renderList_1[_i];
  60971. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  60972. }
  60973. if (subMeshes.length === 0) {
  60974. if (onCompiled) {
  60975. onCompiled(this);
  60976. }
  60977. return;
  60978. }
  60979. var currentIndex = 0;
  60980. var checkReady = function () {
  60981. if (!_this._scene || !_this._scene.getEngine()) {
  60982. return;
  60983. }
  60984. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  60985. currentIndex++;
  60986. if (currentIndex >= subMeshes.length) {
  60987. if (onCompiled) {
  60988. onCompiled(_this);
  60989. }
  60990. return;
  60991. }
  60992. }
  60993. setTimeout(checkReady, 16);
  60994. };
  60995. checkReady();
  60996. };
  60997. /**
  60998. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  60999. * @param options Sets of optional options forcing the compilation with different modes
  61000. * @returns A promise that resolves when the compilation completes
  61001. */
  61002. ShadowGenerator.prototype.forceCompilationAsync = function (options) {
  61003. var _this = this;
  61004. return new Promise(function (resolve) {
  61005. _this.forceCompilation(function () {
  61006. resolve();
  61007. }, options);
  61008. });
  61009. };
  61010. /**
  61011. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  61012. * @param subMesh The submesh we want to render in the shadow map
  61013. * @param useInstances Defines wether will draw in the map using instances
  61014. * @returns true if ready otherwise, false
  61015. */
  61016. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  61017. var defines = [];
  61018. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  61019. defines.push("#define FLOAT");
  61020. }
  61021. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  61022. defines.push("#define ESM");
  61023. }
  61024. var attribs = [BABYLON.VertexBuffer.PositionKind];
  61025. var mesh = subMesh.getMesh();
  61026. var material = subMesh.getMaterial();
  61027. // Alpha test
  61028. if (material && material.needAlphaTesting()) {
  61029. var alphaTexture = material.getAlphaTestTexture();
  61030. if (alphaTexture) {
  61031. defines.push("#define ALPHATEST");
  61032. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  61033. attribs.push(BABYLON.VertexBuffer.UVKind);
  61034. defines.push("#define UV1");
  61035. }
  61036. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  61037. if (alphaTexture.coordinatesIndex === 1) {
  61038. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  61039. defines.push("#define UV2");
  61040. }
  61041. }
  61042. }
  61043. }
  61044. // Bones
  61045. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  61046. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  61047. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  61048. if (mesh.numBoneInfluencers > 4) {
  61049. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  61050. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  61051. }
  61052. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  61053. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  61054. }
  61055. else {
  61056. defines.push("#define NUM_BONE_INFLUENCERS 0");
  61057. }
  61058. // Instances
  61059. if (useInstances) {
  61060. defines.push("#define INSTANCES");
  61061. attribs.push("world0");
  61062. attribs.push("world1");
  61063. attribs.push("world2");
  61064. attribs.push("world3");
  61065. }
  61066. // Get correct effect
  61067. var join = defines.join("\n");
  61068. if (this._cachedDefines !== join) {
  61069. this._cachedDefines = join;
  61070. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues", "biasAndScale"], ["diffuseSampler"], join);
  61071. }
  61072. if (!this._effect.isReady()) {
  61073. return false;
  61074. }
  61075. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  61076. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  61077. this._initializeBlurRTTAndPostProcesses();
  61078. }
  61079. }
  61080. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  61081. return false;
  61082. }
  61083. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  61084. return false;
  61085. }
  61086. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  61087. return false;
  61088. }
  61089. return true;
  61090. };
  61091. /**
  61092. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  61093. * @param defines Defines of the material we want to update
  61094. * @param lightIndex Index of the light in the enabled light list of the material
  61095. */
  61096. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  61097. var scene = this._scene;
  61098. var light = this._light;
  61099. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  61100. return;
  61101. }
  61102. defines["SHADOW" + lightIndex] = true;
  61103. if (this.usePoissonSampling) {
  61104. defines["SHADOWPCF" + lightIndex] = true;
  61105. }
  61106. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  61107. defines["SHADOWESM" + lightIndex] = true;
  61108. }
  61109. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  61110. defines["SHADOWCLOSEESM" + lightIndex] = true;
  61111. }
  61112. if (light.needCube()) {
  61113. defines["SHADOWCUBE" + lightIndex] = true;
  61114. }
  61115. };
  61116. /**
  61117. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  61118. * defined in the generator but impacting the effect).
  61119. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  61120. * @param effect The effect we are binfing the information for
  61121. */
  61122. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  61123. var light = this._light;
  61124. var scene = this._scene;
  61125. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  61126. return;
  61127. }
  61128. var camera = scene.activeCamera;
  61129. if (!camera) {
  61130. return;
  61131. }
  61132. var shadowMap = this.getShadowMap();
  61133. if (!shadowMap) {
  61134. return;
  61135. }
  61136. if (!light.needCube()) {
  61137. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  61138. }
  61139. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  61140. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  61141. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  61142. };
  61143. /**
  61144. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  61145. * (eq to shadow prjection matrix * light transform matrix)
  61146. * @returns The transform matrix used to create the shadow map
  61147. */
  61148. ShadowGenerator.prototype.getTransformMatrix = function () {
  61149. var scene = this._scene;
  61150. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  61151. return this._transformMatrix;
  61152. }
  61153. this._currentRenderID = scene.getRenderId();
  61154. this._currentFaceIndexCache = this._currentFaceIndex;
  61155. var lightPosition = this._light.position;
  61156. if (this._light.computeTransformedInformation()) {
  61157. lightPosition = this._light.transformedPosition;
  61158. }
  61159. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  61160. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  61161. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  61162. }
  61163. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  61164. this._cachedPosition.copyFrom(lightPosition);
  61165. this._cachedDirection.copyFrom(this._lightDirection);
  61166. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  61167. var shadowMap = this.getShadowMap();
  61168. if (shadowMap) {
  61169. var renderList = shadowMap.renderList;
  61170. if (renderList) {
  61171. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  61172. }
  61173. }
  61174. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  61175. }
  61176. return this._transformMatrix;
  61177. };
  61178. /**
  61179. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  61180. * Cube and 2D textures for instance.
  61181. */
  61182. ShadowGenerator.prototype.recreateShadowMap = function () {
  61183. var shadowMap = this._shadowMap;
  61184. if (!shadowMap) {
  61185. return;
  61186. }
  61187. // Track render list.
  61188. var renderList = shadowMap.renderList;
  61189. // Clean up existing data.
  61190. this._disposeRTTandPostProcesses();
  61191. // Reinitializes.
  61192. this._initializeGenerator();
  61193. // Reaffect the filter to ensure a correct fallback if necessary.
  61194. this.filter = this.filter;
  61195. // Reaffect the filter.
  61196. this._applyFilterValues();
  61197. // Reaffect Render List.
  61198. this._shadowMap.renderList = renderList;
  61199. };
  61200. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  61201. if (this._shadowMap2) {
  61202. this._shadowMap2.dispose();
  61203. this._shadowMap2 = null;
  61204. }
  61205. if (this._boxBlurPostprocess) {
  61206. this._boxBlurPostprocess.dispose();
  61207. this._boxBlurPostprocess = null;
  61208. }
  61209. if (this._kernelBlurXPostprocess) {
  61210. this._kernelBlurXPostprocess.dispose();
  61211. this._kernelBlurXPostprocess = null;
  61212. }
  61213. if (this._kernelBlurYPostprocess) {
  61214. this._kernelBlurYPostprocess.dispose();
  61215. this._kernelBlurYPostprocess = null;
  61216. }
  61217. this._blurPostProcesses = [];
  61218. };
  61219. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  61220. if (this._shadowMap) {
  61221. this._shadowMap.dispose();
  61222. this._shadowMap = null;
  61223. }
  61224. this._disposeBlurPostProcesses();
  61225. };
  61226. /**
  61227. * Disposes the ShadowGenerator.
  61228. * Returns nothing.
  61229. */
  61230. ShadowGenerator.prototype.dispose = function () {
  61231. this._disposeRTTandPostProcesses();
  61232. if (this._light) {
  61233. this._light._shadowGenerator = null;
  61234. this._light._markMeshesAsLightDirty();
  61235. }
  61236. };
  61237. /**
  61238. * Serializes the shadow generator setup to a json object.
  61239. * @returns The serialized JSON object
  61240. */
  61241. ShadowGenerator.prototype.serialize = function () {
  61242. var serializationObject = {};
  61243. var shadowMap = this.getShadowMap();
  61244. if (!shadowMap) {
  61245. return serializationObject;
  61246. }
  61247. serializationObject.lightId = this._light.id;
  61248. serializationObject.mapSize = shadowMap.getRenderSize();
  61249. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  61250. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  61251. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  61252. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  61253. serializationObject.usePoissonSampling = this.usePoissonSampling;
  61254. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  61255. serializationObject.depthScale = this.depthScale;
  61256. serializationObject.darkness = this.getDarkness();
  61257. serializationObject.blurBoxOffset = this.blurBoxOffset;
  61258. serializationObject.blurKernel = this.blurKernel;
  61259. serializationObject.blurScale = this.blurScale;
  61260. serializationObject.useKernelBlur = this.useKernelBlur;
  61261. serializationObject.transparencyShadow = this._transparencyShadow;
  61262. serializationObject.renderList = [];
  61263. if (shadowMap.renderList) {
  61264. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  61265. var mesh = shadowMap.renderList[meshIndex];
  61266. serializationObject.renderList.push(mesh.id);
  61267. }
  61268. }
  61269. return serializationObject;
  61270. };
  61271. /**
  61272. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  61273. * @param parsedShadowGenerator The JSON object to parse
  61274. * @param scene The scene to create the shadow map for
  61275. * @returns The parsed shadow generator
  61276. */
  61277. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  61278. //casting to point light, as light is missing the position attr and typescript complains.
  61279. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  61280. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  61281. var shadowMap = shadowGenerator.getShadowMap();
  61282. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  61283. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  61284. meshes.forEach(function (mesh) {
  61285. if (!shadowMap) {
  61286. return;
  61287. }
  61288. if (!shadowMap.renderList) {
  61289. shadowMap.renderList = [];
  61290. }
  61291. shadowMap.renderList.push(mesh);
  61292. });
  61293. }
  61294. if (parsedShadowGenerator.usePoissonSampling) {
  61295. shadowGenerator.usePoissonSampling = true;
  61296. }
  61297. else if (parsedShadowGenerator.useExponentialShadowMap) {
  61298. shadowGenerator.useExponentialShadowMap = true;
  61299. }
  61300. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  61301. shadowGenerator.useBlurExponentialShadowMap = true;
  61302. }
  61303. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  61304. shadowGenerator.useCloseExponentialShadowMap = true;
  61305. }
  61306. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  61307. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  61308. }
  61309. else if (parsedShadowGenerator.useVarianceShadowMap) {
  61310. shadowGenerator.useExponentialShadowMap = true;
  61311. }
  61312. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  61313. shadowGenerator.useBlurExponentialShadowMap = true;
  61314. }
  61315. if (parsedShadowGenerator.depthScale) {
  61316. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  61317. }
  61318. if (parsedShadowGenerator.blurScale) {
  61319. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  61320. }
  61321. if (parsedShadowGenerator.blurBoxOffset) {
  61322. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  61323. }
  61324. if (parsedShadowGenerator.useKernelBlur) {
  61325. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  61326. }
  61327. if (parsedShadowGenerator.blurKernel) {
  61328. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  61329. }
  61330. if (parsedShadowGenerator.bias !== undefined) {
  61331. shadowGenerator.bias = parsedShadowGenerator.bias;
  61332. }
  61333. if (parsedShadowGenerator.darkness) {
  61334. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  61335. }
  61336. if (parsedShadowGenerator.transparencyShadow) {
  61337. shadowGenerator.setTransparencyShadow(true);
  61338. }
  61339. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  61340. return shadowGenerator;
  61341. };
  61342. ShadowGenerator._FILTER_NONE = 0;
  61343. ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP = 1;
  61344. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  61345. ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  61346. ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  61347. ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  61348. return ShadowGenerator;
  61349. }());
  61350. BABYLON.ShadowGenerator = ShadowGenerator;
  61351. })(BABYLON || (BABYLON = {}));
  61352. //# sourceMappingURL=babylon.shadowGenerator.js.map
  61353. var BABYLON;
  61354. (function (BABYLON) {
  61355. var DefaultLoadingScreen = /** @class */ (function () {
  61356. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  61357. if (_loadingText === void 0) { _loadingText = ""; }
  61358. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  61359. var _this = this;
  61360. this._renderingCanvas = _renderingCanvas;
  61361. this._loadingText = _loadingText;
  61362. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  61363. // Resize
  61364. this._resizeLoadingUI = function () {
  61365. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  61366. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  61367. if (!_this._loadingDiv) {
  61368. return;
  61369. }
  61370. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  61371. _this._loadingDiv.style.left = canvasRect.left + "px";
  61372. _this._loadingDiv.style.top = canvasRect.top + "px";
  61373. _this._loadingDiv.style.width = canvasRect.width + "px";
  61374. _this._loadingDiv.style.height = canvasRect.height + "px";
  61375. };
  61376. }
  61377. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  61378. if (this._loadingDiv) {
  61379. // Do not add a loading screen if there is already one
  61380. return;
  61381. }
  61382. this._loadingDiv = document.createElement("div");
  61383. this._loadingDiv.id = "babylonjsLoadingDiv";
  61384. this._loadingDiv.style.opacity = "0";
  61385. this._loadingDiv.style.transition = "opacity 1.5s ease";
  61386. this._loadingDiv.style.pointerEvents = "none";
  61387. // Loading text
  61388. this._loadingTextDiv = document.createElement("div");
  61389. this._loadingTextDiv.style.position = "absolute";
  61390. this._loadingTextDiv.style.left = "0";
  61391. this._loadingTextDiv.style.top = "50%";
  61392. this._loadingTextDiv.style.marginTop = "80px";
  61393. this._loadingTextDiv.style.width = "100%";
  61394. this._loadingTextDiv.style.height = "20px";
  61395. this._loadingTextDiv.style.fontFamily = "Arial";
  61396. this._loadingTextDiv.style.fontSize = "14px";
  61397. this._loadingTextDiv.style.color = "white";
  61398. this._loadingTextDiv.style.textAlign = "center";
  61399. this._loadingTextDiv.innerHTML = "Loading";
  61400. this._loadingDiv.appendChild(this._loadingTextDiv);
  61401. //set the predefined text
  61402. this._loadingTextDiv.innerHTML = this._loadingText;
  61403. // Generating keyframes
  61404. var style = document.createElement('style');
  61405. style.type = 'text/css';
  61406. 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 }";
  61407. style.innerHTML = keyFrames;
  61408. document.getElementsByTagName('head')[0].appendChild(style);
  61409. // Loading img
  61410. var imgBack = new Image();
  61411. 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";
  61412. imgBack.style.position = "absolute";
  61413. imgBack.style.left = "50%";
  61414. imgBack.style.top = "50%";
  61415. imgBack.style.marginLeft = "-60px";
  61416. imgBack.style.marginTop = "-60px";
  61417. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  61418. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  61419. imgBack.style.transformOrigin = "50% 50%";
  61420. imgBack.style.webkitTransformOrigin = "50% 50%";
  61421. this._loadingDiv.appendChild(imgBack);
  61422. this._resizeLoadingUI();
  61423. window.addEventListener("resize", this._resizeLoadingUI);
  61424. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  61425. document.body.appendChild(this._loadingDiv);
  61426. this._loadingDiv.style.opacity = "1";
  61427. };
  61428. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  61429. var _this = this;
  61430. if (!this._loadingDiv) {
  61431. return;
  61432. }
  61433. var onTransitionEnd = function () {
  61434. if (!_this._loadingDiv) {
  61435. return;
  61436. }
  61437. document.body.removeChild(_this._loadingDiv);
  61438. window.removeEventListener("resize", _this._resizeLoadingUI);
  61439. _this._loadingDiv = null;
  61440. };
  61441. this._loadingDiv.style.opacity = "0";
  61442. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  61443. };
  61444. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  61445. set: function (text) {
  61446. this._loadingText = text;
  61447. if (this._loadingTextDiv) {
  61448. this._loadingTextDiv.innerHTML = this._loadingText;
  61449. }
  61450. },
  61451. enumerable: true,
  61452. configurable: true
  61453. });
  61454. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  61455. get: function () {
  61456. return this._loadingDivBackgroundColor;
  61457. },
  61458. set: function (color) {
  61459. this._loadingDivBackgroundColor = color;
  61460. if (!this._loadingDiv) {
  61461. return;
  61462. }
  61463. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  61464. },
  61465. enumerable: true,
  61466. configurable: true
  61467. });
  61468. return DefaultLoadingScreen;
  61469. }());
  61470. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  61471. })(BABYLON || (BABYLON = {}));
  61472. //# sourceMappingURL=babylon.loadingScreen.js.map
  61473. var BABYLON;
  61474. (function (BABYLON) {
  61475. var SceneLoaderProgressEvent = /** @class */ (function () {
  61476. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  61477. this.lengthComputable = lengthComputable;
  61478. this.loaded = loaded;
  61479. this.total = total;
  61480. }
  61481. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  61482. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  61483. };
  61484. return SceneLoaderProgressEvent;
  61485. }());
  61486. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  61487. var SceneLoader = /** @class */ (function () {
  61488. function SceneLoader() {
  61489. }
  61490. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  61491. get: function () {
  61492. return 0;
  61493. },
  61494. enumerable: true,
  61495. configurable: true
  61496. });
  61497. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  61498. get: function () {
  61499. return 1;
  61500. },
  61501. enumerable: true,
  61502. configurable: true
  61503. });
  61504. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  61505. get: function () {
  61506. return 2;
  61507. },
  61508. enumerable: true,
  61509. configurable: true
  61510. });
  61511. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  61512. get: function () {
  61513. return 3;
  61514. },
  61515. enumerable: true,
  61516. configurable: true
  61517. });
  61518. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  61519. get: function () {
  61520. return SceneLoader._ForceFullSceneLoadingForIncremental;
  61521. },
  61522. set: function (value) {
  61523. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  61524. },
  61525. enumerable: true,
  61526. configurable: true
  61527. });
  61528. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  61529. get: function () {
  61530. return SceneLoader._ShowLoadingScreen;
  61531. },
  61532. set: function (value) {
  61533. SceneLoader._ShowLoadingScreen = value;
  61534. },
  61535. enumerable: true,
  61536. configurable: true
  61537. });
  61538. Object.defineProperty(SceneLoader, "loggingLevel", {
  61539. get: function () {
  61540. return SceneLoader._loggingLevel;
  61541. },
  61542. set: function (value) {
  61543. SceneLoader._loggingLevel = value;
  61544. },
  61545. enumerable: true,
  61546. configurable: true
  61547. });
  61548. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  61549. get: function () {
  61550. return SceneLoader._CleanBoneMatrixWeights;
  61551. },
  61552. set: function (value) {
  61553. SceneLoader._CleanBoneMatrixWeights = value;
  61554. },
  61555. enumerable: true,
  61556. configurable: true
  61557. });
  61558. SceneLoader._getDefaultPlugin = function () {
  61559. return SceneLoader._registeredPlugins[".babylon"];
  61560. };
  61561. SceneLoader._getPluginForExtension = function (extension) {
  61562. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  61563. if (registeredPlugin) {
  61564. return registeredPlugin;
  61565. }
  61566. BABYLON.Tools.Warn("Unable to find a plugin to load " + extension + " files. Trying to use .babylon default plugin.");
  61567. return SceneLoader._getDefaultPlugin();
  61568. };
  61569. SceneLoader._getPluginForDirectLoad = function (data) {
  61570. for (var extension in SceneLoader._registeredPlugins) {
  61571. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  61572. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  61573. return SceneLoader._registeredPlugins[extension];
  61574. }
  61575. }
  61576. return SceneLoader._getDefaultPlugin();
  61577. };
  61578. SceneLoader._getPluginForFilename = function (sceneFilename) {
  61579. if (sceneFilename.name) {
  61580. sceneFilename = sceneFilename.name;
  61581. }
  61582. var queryStringPosition = sceneFilename.indexOf("?");
  61583. if (queryStringPosition !== -1) {
  61584. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  61585. }
  61586. var dotPosition = sceneFilename.lastIndexOf(".");
  61587. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  61588. return SceneLoader._getPluginForExtension(extension);
  61589. };
  61590. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  61591. SceneLoader._getDirectLoad = function (sceneFilename) {
  61592. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  61593. return sceneFilename.substr(5);
  61594. }
  61595. return null;
  61596. };
  61597. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  61598. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  61599. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  61600. var plugin;
  61601. if (registeredPlugin.plugin.createPlugin) {
  61602. plugin = registeredPlugin.plugin.createPlugin();
  61603. }
  61604. else {
  61605. plugin = registeredPlugin.plugin;
  61606. }
  61607. var useArrayBuffer = registeredPlugin.isBinary;
  61608. var database;
  61609. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  61610. var dataCallback = function (data, responseURL) {
  61611. if (scene.isDisposed) {
  61612. onError("Scene has been disposed");
  61613. return;
  61614. }
  61615. scene.database = database;
  61616. onSuccess(plugin, data, responseURL);
  61617. };
  61618. var request = null;
  61619. var pluginDisposed = false;
  61620. var onDisposeObservable = plugin.onDisposeObservable;
  61621. if (onDisposeObservable) {
  61622. onDisposeObservable.add(function () {
  61623. pluginDisposed = true;
  61624. if (request) {
  61625. request.abort();
  61626. request = null;
  61627. }
  61628. onDispose();
  61629. });
  61630. }
  61631. var manifestChecked = function () {
  61632. if (pluginDisposed) {
  61633. return;
  61634. }
  61635. var url = rootUrl + sceneFilename;
  61636. request = BABYLON.Tools.LoadFile(url, dataCallback, onProgress ? function (event) {
  61637. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  61638. } : undefined, database, useArrayBuffer, function (request, exception) {
  61639. onError("Failed to load scene." + (exception ? "" : " " + exception.message), exception);
  61640. });
  61641. };
  61642. if (directLoad) {
  61643. dataCallback(directLoad);
  61644. return plugin;
  61645. }
  61646. if (rootUrl.indexOf("file:") === -1) {
  61647. if (scene.getEngine().enableOfflineSupport) {
  61648. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  61649. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  61650. }
  61651. else {
  61652. manifestChecked();
  61653. }
  61654. }
  61655. else {
  61656. var fileOrString = sceneFilename;
  61657. if (fileOrString.name) {
  61658. request = BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  61659. }
  61660. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  61661. request = BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  61662. }
  61663. else {
  61664. onError("Unable to find file named " + sceneFilename);
  61665. }
  61666. }
  61667. return plugin;
  61668. };
  61669. // Public functions
  61670. SceneLoader.GetPluginForExtension = function (extension) {
  61671. return SceneLoader._getPluginForExtension(extension).plugin;
  61672. };
  61673. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  61674. return !!SceneLoader._registeredPlugins[extension];
  61675. };
  61676. SceneLoader.RegisterPlugin = function (plugin) {
  61677. if (typeof plugin.extensions === "string") {
  61678. var extension = plugin.extensions;
  61679. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  61680. plugin: plugin,
  61681. isBinary: false
  61682. };
  61683. }
  61684. else {
  61685. var extensions = plugin.extensions;
  61686. Object.keys(extensions).forEach(function (extension) {
  61687. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  61688. plugin: plugin,
  61689. isBinary: extensions[extension].isBinary
  61690. };
  61691. });
  61692. }
  61693. };
  61694. /**
  61695. * Import meshes into a scene
  61696. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  61697. * @param rootUrl a string that defines the root url for scene and resources
  61698. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  61699. * @param scene the instance of BABYLON.Scene to append to
  61700. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  61701. * @param onProgress a callback with a progress event for each file being loaded
  61702. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  61703. * @param pluginExtension the extension used to determine the plugin
  61704. * @returns The loaded plugin
  61705. */
  61706. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  61707. if (onSuccess === void 0) { onSuccess = null; }
  61708. if (onProgress === void 0) { onProgress = null; }
  61709. if (onError === void 0) { onError = null; }
  61710. if (pluginExtension === void 0) { pluginExtension = null; }
  61711. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  61712. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  61713. return null;
  61714. }
  61715. var loadingToken = {};
  61716. scene._addPendingData(loadingToken);
  61717. var disposeHandler = function () {
  61718. scene._removePendingData(loadingToken);
  61719. };
  61720. var errorHandler = function (message, exception) {
  61721. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + ": " + message;
  61722. if (onError) {
  61723. onError(scene, errorMessage, exception);
  61724. }
  61725. else {
  61726. BABYLON.Tools.Error(errorMessage);
  61727. // should the exception be thrown?
  61728. }
  61729. disposeHandler();
  61730. };
  61731. var progressHandler = onProgress ? function (event) {
  61732. try {
  61733. onProgress(event);
  61734. }
  61735. catch (e) {
  61736. errorHandler("Error in onProgress callback", e);
  61737. }
  61738. } : undefined;
  61739. var successHandler = function (meshes, particleSystems, skeletons) {
  61740. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  61741. if (onSuccess) {
  61742. try {
  61743. onSuccess(meshes, particleSystems, skeletons);
  61744. }
  61745. catch (e) {
  61746. errorHandler("Error in onSuccess callback", e);
  61747. }
  61748. }
  61749. scene._removePendingData(loadingToken);
  61750. };
  61751. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  61752. if (plugin.rewriteRootURL) {
  61753. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  61754. }
  61755. if (sceneFilename === "") {
  61756. if (sceneFilename === "") {
  61757. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  61758. }
  61759. }
  61760. if (plugin.importMesh) {
  61761. var syncedPlugin = plugin;
  61762. var meshes = new Array();
  61763. var particleSystems = new Array();
  61764. var skeletons = new Array();
  61765. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  61766. return;
  61767. }
  61768. scene.loadingPluginName = plugin.name;
  61769. successHandler(meshes, particleSystems, skeletons);
  61770. }
  61771. else {
  61772. var asyncedPlugin = plugin;
  61773. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, progressHandler).then(function (result) {
  61774. scene.loadingPluginName = plugin.name;
  61775. successHandler(result.meshes, result.particleSystems, result.skeletons);
  61776. }).catch(function (error) {
  61777. errorHandler(error.message, error);
  61778. });
  61779. }
  61780. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  61781. };
  61782. /**
  61783. * Import meshes into a scene
  61784. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  61785. * @param rootUrl a string that defines the root url for scene and resources
  61786. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  61787. * @param scene the instance of BABYLON.Scene to append to
  61788. * @param onProgress a callback with a progress event for each file being loaded
  61789. * @param pluginExtension the extension used to determine the plugin
  61790. * @returns The loaded list of imported meshes, particleSystems, and skeletons
  61791. */
  61792. SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  61793. if (onProgress === void 0) { onProgress = null; }
  61794. if (pluginExtension === void 0) { pluginExtension = null; }
  61795. return new Promise(function (resolve, reject) {
  61796. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  61797. resolve({
  61798. meshes: meshes,
  61799. particleSystems: particleSystems,
  61800. skeletons: skeletons
  61801. });
  61802. }, onProgress, function (scene, message, exception) {
  61803. reject(exception || new Error(message));
  61804. });
  61805. });
  61806. };
  61807. /**
  61808. * Load a scene
  61809. * @param rootUrl a string that defines the root url for scene and resources
  61810. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  61811. * @param engine is the instance of BABYLON.Engine to use to create the scene
  61812. * @param onSuccess a callback with the scene when import succeeds
  61813. * @param onProgress a callback with a progress event for each file being loaded
  61814. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  61815. * @param pluginExtension the extension used to determine the plugin
  61816. * @returns The loaded plugin
  61817. */
  61818. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  61819. if (onSuccess === void 0) { onSuccess = null; }
  61820. if (onProgress === void 0) { onProgress = null; }
  61821. if (onError === void 0) { onError = null; }
  61822. if (pluginExtension === void 0) { pluginExtension = null; }
  61823. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  61824. };
  61825. /**
  61826. * Load a scene
  61827. * @param rootUrl a string that defines the root url for scene and resources
  61828. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  61829. * @param engine is the instance of BABYLON.Engine to use to create the scene
  61830. * @param onProgress a callback with a progress event for each file being loaded
  61831. * @param pluginExtension the extension used to determine the plugin
  61832. * @returns The loaded scene
  61833. */
  61834. SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {
  61835. if (onProgress === void 0) { onProgress = null; }
  61836. if (pluginExtension === void 0) { pluginExtension = null; }
  61837. return new Promise(function (resolve, reject) {
  61838. SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {
  61839. resolve(scene);
  61840. }, onProgress, function (scene, message, exception) {
  61841. reject(exception || new Error(message));
  61842. }, pluginExtension);
  61843. });
  61844. };
  61845. /**
  61846. * Append a scene
  61847. * @param rootUrl a string that defines the root url for scene and resources
  61848. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  61849. * @param scene is the instance of BABYLON.Scene to append to
  61850. * @param onSuccess a callback with the scene when import succeeds
  61851. * @param onProgress a callback with a progress event for each file being loaded
  61852. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  61853. * @param pluginExtension the extension used to determine the plugin
  61854. * @returns The loaded plugin
  61855. */
  61856. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  61857. if (onSuccess === void 0) { onSuccess = null; }
  61858. if (onProgress === void 0) { onProgress = null; }
  61859. if (onError === void 0) { onError = null; }
  61860. if (pluginExtension === void 0) { pluginExtension = null; }
  61861. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  61862. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  61863. return null;
  61864. }
  61865. if (SceneLoader.ShowLoadingScreen) {
  61866. scene.getEngine().displayLoadingUI();
  61867. }
  61868. var loadingToken = {};
  61869. scene._addPendingData(loadingToken);
  61870. var disposeHandler = function () {
  61871. scene._removePendingData(loadingToken);
  61872. scene.getEngine().hideLoadingUI();
  61873. };
  61874. var errorHandler = function (message, exception) {
  61875. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  61876. if (onError) {
  61877. onError(scene, errorMessage, exception);
  61878. }
  61879. else {
  61880. BABYLON.Tools.Error(errorMessage);
  61881. // should the exception be thrown?
  61882. }
  61883. disposeHandler();
  61884. };
  61885. var progressHandler = onProgress ? function (event) {
  61886. try {
  61887. onProgress(event);
  61888. }
  61889. catch (e) {
  61890. errorHandler("Error in onProgress callback", e);
  61891. }
  61892. } : undefined;
  61893. var successHandler = function () {
  61894. if (onSuccess) {
  61895. try {
  61896. onSuccess(scene);
  61897. }
  61898. catch (e) {
  61899. errorHandler("Error in onSuccess callback", e);
  61900. }
  61901. }
  61902. scene._removePendingData(loadingToken);
  61903. };
  61904. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  61905. if (sceneFilename === "") {
  61906. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  61907. }
  61908. if (plugin.load) {
  61909. var syncedPlugin = plugin;
  61910. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  61911. return;
  61912. }
  61913. scene.loadingPluginName = plugin.name;
  61914. successHandler();
  61915. }
  61916. else {
  61917. var asyncedPlugin = plugin;
  61918. asyncedPlugin.loadAsync(scene, data, rootUrl, progressHandler).then(function () {
  61919. scene.loadingPluginName = plugin.name;
  61920. successHandler();
  61921. }).catch(function (error) {
  61922. errorHandler(error.message, error);
  61923. });
  61924. }
  61925. if (SceneLoader.ShowLoadingScreen) {
  61926. scene.executeWhenReady(function () {
  61927. scene.getEngine().hideLoadingUI();
  61928. });
  61929. }
  61930. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  61931. };
  61932. /**
  61933. * Append a scene
  61934. * @param rootUrl a string that defines the root url for scene and resources
  61935. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  61936. * @param scene is the instance of BABYLON.Scene to append to
  61937. * @param onProgress a callback with a progress event for each file being loaded
  61938. * @param pluginExtension the extension used to determine the plugin
  61939. * @returns The given scene
  61940. */
  61941. SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  61942. if (onProgress === void 0) { onProgress = null; }
  61943. if (pluginExtension === void 0) { pluginExtension = null; }
  61944. return new Promise(function (resolve, reject) {
  61945. SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {
  61946. resolve(scene);
  61947. }, onProgress, function (scene, message, exception) {
  61948. reject(exception || new Error(message));
  61949. }, pluginExtension);
  61950. });
  61951. };
  61952. /**
  61953. * Load a scene into an asset container
  61954. * @param rootUrl a string that defines the root url for scene and resources
  61955. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  61956. * @param scene is the instance of BABYLON.Scene to append to
  61957. * @param onSuccess a callback with the scene when import succeeds
  61958. * @param onProgress a callback with a progress event for each file being loaded
  61959. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  61960. * @param pluginExtension the extension used to determine the plugin
  61961. * @returns The loaded plugin
  61962. */
  61963. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  61964. if (onSuccess === void 0) { onSuccess = null; }
  61965. if (onProgress === void 0) { onProgress = null; }
  61966. if (onError === void 0) { onError = null; }
  61967. if (pluginExtension === void 0) { pluginExtension = null; }
  61968. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  61969. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  61970. return null;
  61971. }
  61972. var loadingToken = {};
  61973. scene._addPendingData(loadingToken);
  61974. var disposeHandler = function () {
  61975. scene._removePendingData(loadingToken);
  61976. };
  61977. var errorHandler = function (message, exception) {
  61978. var errorMessage = "Unable to load assets from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  61979. if (onError) {
  61980. onError(scene, errorMessage, exception);
  61981. }
  61982. else {
  61983. BABYLON.Tools.Error(errorMessage);
  61984. // should the exception be thrown?
  61985. }
  61986. disposeHandler();
  61987. };
  61988. var progressHandler = onProgress ? function (event) {
  61989. try {
  61990. onProgress(event);
  61991. }
  61992. catch (e) {
  61993. errorHandler("Error in onProgress callback", e);
  61994. }
  61995. } : undefined;
  61996. var successHandler = function (assets) {
  61997. if (onSuccess) {
  61998. try {
  61999. onSuccess(assets);
  62000. }
  62001. catch (e) {
  62002. errorHandler("Error in onSuccess callback", e);
  62003. }
  62004. }
  62005. scene._removePendingData(loadingToken);
  62006. };
  62007. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  62008. if (plugin.loadAssetContainer) {
  62009. var syncedPlugin = plugin;
  62010. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, rootUrl, errorHandler);
  62011. if (!assetContainer) {
  62012. return;
  62013. }
  62014. scene.loadingPluginName = plugin.name;
  62015. successHandler(assetContainer);
  62016. }
  62017. else if (plugin.loadAssetContainerAsync) {
  62018. var asyncedPlugin = plugin;
  62019. asyncedPlugin.loadAssetContainerAsync(scene, data, rootUrl, progressHandler).then(function (assetContainer) {
  62020. scene.loadingPluginName = plugin.name;
  62021. successHandler(assetContainer);
  62022. }).catch(function (error) {
  62023. errorHandler(error.message, error);
  62024. });
  62025. }
  62026. else {
  62027. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
  62028. }
  62029. if (SceneLoader.ShowLoadingScreen) {
  62030. scene.executeWhenReady(function () {
  62031. scene.getEngine().hideLoadingUI();
  62032. });
  62033. }
  62034. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  62035. };
  62036. /**
  62037. * Load a scene into an asset container
  62038. * @param rootUrl a string that defines the root url for scene and resources
  62039. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  62040. * @param scene is the instance of BABYLON.Scene to append to
  62041. * @param onProgress a callback with a progress event for each file being loaded
  62042. * @param pluginExtension the extension used to determine the plugin
  62043. * @returns The loaded asset container
  62044. */
  62045. SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  62046. if (onProgress === void 0) { onProgress = null; }
  62047. if (pluginExtension === void 0) { pluginExtension = null; }
  62048. return new Promise(function (resolve, reject) {
  62049. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {
  62050. resolve(assetContainer);
  62051. }, onProgress, function (scene, message, exception) {
  62052. reject(exception || new Error(message));
  62053. }, pluginExtension);
  62054. });
  62055. };
  62056. // Flags
  62057. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  62058. SceneLoader._ShowLoadingScreen = true;
  62059. SceneLoader._CleanBoneMatrixWeights = false;
  62060. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  62061. // Members
  62062. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  62063. SceneLoader._registeredPlugins = {};
  62064. return SceneLoader;
  62065. }());
  62066. BABYLON.SceneLoader = SceneLoader;
  62067. ;
  62068. })(BABYLON || (BABYLON = {}));
  62069. //# sourceMappingURL=babylon.sceneLoader.js.map
  62070. var BABYLON;
  62071. (function (BABYLON) {
  62072. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  62073. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  62074. var parsedMaterial = parsedData.materials[index];
  62075. if (parsedMaterial.id === id) {
  62076. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  62077. }
  62078. }
  62079. return null;
  62080. };
  62081. var isDescendantOf = function (mesh, names, hierarchyIds) {
  62082. for (var i in names) {
  62083. if (mesh.name === names[i]) {
  62084. hierarchyIds.push(mesh.id);
  62085. return true;
  62086. }
  62087. }
  62088. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  62089. hierarchyIds.push(mesh.id);
  62090. return true;
  62091. }
  62092. return false;
  62093. };
  62094. var logOperation = function (operation, producer) {
  62095. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  62096. };
  62097. var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {
  62098. if (addToScene === void 0) { addToScene = false; }
  62099. var container = new BABYLON.AssetContainer(scene);
  62100. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  62101. // when SceneLoader.debugLogging = true (default), or exception encountered.
  62102. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  62103. // and avoid problems with multiple concurrent .babylon loads.
  62104. var log = "importScene has failed JSON parse";
  62105. try {
  62106. var parsedData = JSON.parse(data);
  62107. log = "";
  62108. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  62109. var index;
  62110. var cache;
  62111. // Lights
  62112. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  62113. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  62114. var parsedLight = parsedData.lights[index];
  62115. var light = BABYLON.Light.Parse(parsedLight, scene);
  62116. if (light) {
  62117. container.lights.push(light);
  62118. log += (index === 0 ? "\n\tLights:" : "");
  62119. log += "\n\t\t" + light.toString(fullDetails);
  62120. }
  62121. }
  62122. }
  62123. // Animations
  62124. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  62125. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  62126. var parsedAnimation = parsedData.animations[index];
  62127. var animation = BABYLON.Animation.Parse(parsedAnimation);
  62128. scene.animations.push(animation);
  62129. container.animations.push(animation);
  62130. log += (index === 0 ? "\n\tAnimations:" : "");
  62131. log += "\n\t\t" + animation.toString(fullDetails);
  62132. }
  62133. }
  62134. // Materials
  62135. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  62136. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  62137. var parsedMaterial = parsedData.materials[index];
  62138. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  62139. container.materials.push(mat);
  62140. log += (index === 0 ? "\n\tMaterials:" : "");
  62141. log += "\n\t\t" + mat.toString(fullDetails);
  62142. }
  62143. }
  62144. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  62145. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  62146. var parsedMultiMaterial = parsedData.multiMaterials[index];
  62147. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  62148. container.multiMaterials.push(mmat);
  62149. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  62150. log += "\n\t\t" + mmat.toString(fullDetails);
  62151. }
  62152. }
  62153. // Morph targets
  62154. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  62155. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  62156. var managerData = _a[_i];
  62157. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  62158. }
  62159. }
  62160. // Skeletons
  62161. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  62162. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  62163. var parsedSkeleton = parsedData.skeletons[index];
  62164. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  62165. container.skeletons.push(skeleton);
  62166. log += (index === 0 ? "\n\tSkeletons:" : "");
  62167. log += "\n\t\t" + skeleton.toString(fullDetails);
  62168. }
  62169. }
  62170. // Geometries
  62171. var geometries = parsedData.geometries;
  62172. if (geometries !== undefined && geometries !== null) {
  62173. var addedGeometry = new Array();
  62174. // Boxes
  62175. var boxes = geometries.boxes;
  62176. if (boxes !== undefined && boxes !== null) {
  62177. for (index = 0, cache = boxes.length; index < cache; index++) {
  62178. var parsedBox = boxes[index];
  62179. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  62180. }
  62181. }
  62182. // Spheres
  62183. var spheres = geometries.spheres;
  62184. if (spheres !== undefined && spheres !== null) {
  62185. for (index = 0, cache = spheres.length; index < cache; index++) {
  62186. var parsedSphere = spheres[index];
  62187. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  62188. }
  62189. }
  62190. // Cylinders
  62191. var cylinders = geometries.cylinders;
  62192. if (cylinders !== undefined && cylinders !== null) {
  62193. for (index = 0, cache = cylinders.length; index < cache; index++) {
  62194. var parsedCylinder = cylinders[index];
  62195. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  62196. }
  62197. }
  62198. // Toruses
  62199. var toruses = geometries.toruses;
  62200. if (toruses !== undefined && toruses !== null) {
  62201. for (index = 0, cache = toruses.length; index < cache; index++) {
  62202. var parsedTorus = toruses[index];
  62203. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  62204. }
  62205. }
  62206. // Grounds
  62207. var grounds = geometries.grounds;
  62208. if (grounds !== undefined && grounds !== null) {
  62209. for (index = 0, cache = grounds.length; index < cache; index++) {
  62210. var parsedGround = grounds[index];
  62211. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  62212. }
  62213. }
  62214. // Planes
  62215. var planes = geometries.planes;
  62216. if (planes !== undefined && planes !== null) {
  62217. for (index = 0, cache = planes.length; index < cache; index++) {
  62218. var parsedPlane = planes[index];
  62219. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  62220. }
  62221. }
  62222. // TorusKnots
  62223. var torusKnots = geometries.torusKnots;
  62224. if (torusKnots !== undefined && torusKnots !== null) {
  62225. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  62226. var parsedTorusKnot = torusKnots[index];
  62227. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  62228. }
  62229. }
  62230. // VertexData
  62231. var vertexData = geometries.vertexData;
  62232. if (vertexData !== undefined && vertexData !== null) {
  62233. for (index = 0, cache = vertexData.length; index < cache; index++) {
  62234. var parsedVertexData = vertexData[index];
  62235. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  62236. }
  62237. }
  62238. addedGeometry.forEach(function (g) {
  62239. if (g) {
  62240. container.geometries.push(g);
  62241. }
  62242. });
  62243. }
  62244. // Transform nodes
  62245. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  62246. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  62247. var parsedTransformNode = parsedData.transformNodes[index];
  62248. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  62249. container.transformNodes.push(node);
  62250. }
  62251. }
  62252. // Meshes
  62253. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  62254. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  62255. var parsedMesh = parsedData.meshes[index];
  62256. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  62257. container.meshes.push(mesh);
  62258. log += (index === 0 ? "\n\tMeshes:" : "");
  62259. log += "\n\t\t" + mesh.toString(fullDetails);
  62260. }
  62261. }
  62262. // Cameras
  62263. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  62264. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  62265. var parsedCamera = parsedData.cameras[index];
  62266. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  62267. container.cameras.push(camera);
  62268. log += (index === 0 ? "\n\tCameras:" : "");
  62269. log += "\n\t\t" + camera.toString(fullDetails);
  62270. }
  62271. }
  62272. // Browsing all the graph to connect the dots
  62273. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  62274. var camera = scene.cameras[index];
  62275. if (camera._waitingParentId) {
  62276. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  62277. camera._waitingParentId = null;
  62278. }
  62279. }
  62280. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  62281. var light_1 = scene.lights[index];
  62282. if (light_1 && light_1._waitingParentId) {
  62283. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  62284. light_1._waitingParentId = null;
  62285. }
  62286. }
  62287. // Sounds
  62288. // TODO: add sound
  62289. var loadedSounds = [];
  62290. var loadedSound;
  62291. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  62292. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  62293. var parsedSound = parsedData.sounds[index];
  62294. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62295. if (!parsedSound.url)
  62296. parsedSound.url = parsedSound.name;
  62297. if (!loadedSounds[parsedSound.url]) {
  62298. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  62299. loadedSounds[parsedSound.url] = loadedSound;
  62300. container.sounds.push(loadedSound);
  62301. }
  62302. else {
  62303. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  62304. }
  62305. }
  62306. else {
  62307. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  62308. }
  62309. }
  62310. }
  62311. loadedSounds = [];
  62312. // Connect parents & children and parse actions
  62313. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  62314. var transformNode = scene.transformNodes[index];
  62315. if (transformNode._waitingParentId) {
  62316. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  62317. transformNode._waitingParentId = null;
  62318. }
  62319. }
  62320. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  62321. var mesh = scene.meshes[index];
  62322. if (mesh._waitingParentId) {
  62323. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  62324. mesh._waitingParentId = null;
  62325. }
  62326. if (mesh._waitingActions) {
  62327. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  62328. mesh._waitingActions = null;
  62329. }
  62330. }
  62331. // freeze world matrix application
  62332. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  62333. var currentMesh = scene.meshes[index];
  62334. if (currentMesh._waitingFreezeWorldMatrix) {
  62335. currentMesh.freezeWorldMatrix();
  62336. currentMesh._waitingFreezeWorldMatrix = null;
  62337. }
  62338. else {
  62339. currentMesh.computeWorldMatrix(true);
  62340. }
  62341. }
  62342. // Particles Systems
  62343. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  62344. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  62345. var parsedParticleSystem = parsedData.particleSystems[index];
  62346. if (parsedParticleSystem.activeParticleCount) {
  62347. var ps = BABYLON.GPUParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  62348. container.particleSystems.push(ps);
  62349. }
  62350. else {
  62351. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  62352. container.particleSystems.push(ps);
  62353. }
  62354. }
  62355. }
  62356. // Lens flares
  62357. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  62358. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  62359. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  62360. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  62361. container.lensFlareSystems.push(lf);
  62362. }
  62363. }
  62364. // Shadows
  62365. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  62366. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  62367. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  62368. var sg = BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  62369. container.shadowGenerators.push(sg);
  62370. }
  62371. }
  62372. // Lights exclusions / inclusions
  62373. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  62374. var light_2 = scene.lights[index];
  62375. // Excluded check
  62376. if (light_2._excludedMeshesIds.length > 0) {
  62377. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  62378. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  62379. if (excludedMesh) {
  62380. light_2.excludedMeshes.push(excludedMesh);
  62381. }
  62382. }
  62383. light_2._excludedMeshesIds = [];
  62384. }
  62385. // Included check
  62386. if (light_2._includedOnlyMeshesIds.length > 0) {
  62387. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  62388. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  62389. if (includedOnlyMesh) {
  62390. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  62391. }
  62392. }
  62393. light_2._includedOnlyMeshesIds = [];
  62394. }
  62395. }
  62396. // Actions (scene)
  62397. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  62398. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  62399. }
  62400. if (!addToScene) {
  62401. container.removeAllFromScene();
  62402. }
  62403. }
  62404. catch (err) {
  62405. var msg = logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + log;
  62406. if (onError) {
  62407. onError(msg, err);
  62408. }
  62409. else {
  62410. BABYLON.Tools.Log(msg);
  62411. throw err;
  62412. }
  62413. }
  62414. finally {
  62415. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  62416. BABYLON.Tools.Log(logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  62417. }
  62418. }
  62419. return container;
  62420. };
  62421. BABYLON.SceneLoader.RegisterPlugin({
  62422. name: "babylon.js",
  62423. extensions: ".babylon",
  62424. canDirectLoad: function (data) {
  62425. if (data.indexOf("babylon") !== -1) {
  62426. return true;
  62427. }
  62428. return false;
  62429. },
  62430. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  62431. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  62432. // when SceneLoader.debugLogging = true (default), or exception encountered.
  62433. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  62434. // and avoid problems with multiple concurrent .babylon loads.
  62435. var log = "importMesh has failed JSON parse";
  62436. try {
  62437. var parsedData = JSON.parse(data);
  62438. log = "";
  62439. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  62440. if (!meshesNames) {
  62441. meshesNames = null;
  62442. }
  62443. else if (!Array.isArray(meshesNames)) {
  62444. meshesNames = [meshesNames];
  62445. }
  62446. var hierarchyIds = new Array();
  62447. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  62448. var loadedSkeletonsIds = [];
  62449. var loadedMaterialsIds = [];
  62450. var index;
  62451. var cache;
  62452. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  62453. var parsedMesh = parsedData.meshes[index];
  62454. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  62455. if (meshesNames !== null) {
  62456. // Remove found mesh name from list.
  62457. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  62458. }
  62459. //Geometry?
  62460. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  62461. //does the file contain geometries?
  62462. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  62463. //find the correct geometry and add it to the scene
  62464. var found = false;
  62465. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  62466. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  62467. return;
  62468. }
  62469. else {
  62470. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  62471. if (parsedGeometryData.id === parsedMesh.geometryId) {
  62472. switch (geometryType) {
  62473. case "boxes":
  62474. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  62475. break;
  62476. case "spheres":
  62477. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  62478. break;
  62479. case "cylinders":
  62480. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  62481. break;
  62482. case "toruses":
  62483. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  62484. break;
  62485. case "grounds":
  62486. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  62487. break;
  62488. case "planes":
  62489. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  62490. break;
  62491. case "torusKnots":
  62492. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  62493. break;
  62494. case "vertexData":
  62495. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  62496. break;
  62497. }
  62498. found = true;
  62499. }
  62500. });
  62501. }
  62502. });
  62503. if (found === false) {
  62504. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  62505. }
  62506. }
  62507. }
  62508. // Material ?
  62509. if (parsedMesh.materialId) {
  62510. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  62511. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  62512. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  62513. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  62514. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  62515. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  62516. var subMatId = parsedMultiMaterial.materials[matIndex];
  62517. loadedMaterialsIds.push(subMatId);
  62518. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  62519. if (mat) {
  62520. log += "\n\tMaterial " + mat.toString(fullDetails);
  62521. }
  62522. }
  62523. loadedMaterialsIds.push(parsedMultiMaterial.id);
  62524. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  62525. if (mmat) {
  62526. materialFound = true;
  62527. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  62528. }
  62529. break;
  62530. }
  62531. }
  62532. }
  62533. if (materialFound === false) {
  62534. loadedMaterialsIds.push(parsedMesh.materialId);
  62535. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  62536. if (!mat) {
  62537. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  62538. }
  62539. else {
  62540. log += "\n\tMaterial " + mat.toString(fullDetails);
  62541. }
  62542. }
  62543. }
  62544. // Skeleton ?
  62545. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  62546. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  62547. if (skeletonAlreadyLoaded === false) {
  62548. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  62549. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  62550. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  62551. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  62552. skeletons.push(skeleton);
  62553. loadedSkeletonsIds.push(parsedSkeleton.id);
  62554. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  62555. }
  62556. }
  62557. }
  62558. }
  62559. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  62560. meshes.push(mesh);
  62561. log += "\n\tMesh " + mesh.toString(fullDetails);
  62562. }
  62563. }
  62564. // Connecting parents
  62565. var currentMesh;
  62566. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  62567. currentMesh = scene.meshes[index];
  62568. if (currentMesh._waitingParentId) {
  62569. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  62570. currentMesh._waitingParentId = null;
  62571. }
  62572. }
  62573. // freeze and compute world matrix application
  62574. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  62575. currentMesh = scene.meshes[index];
  62576. if (currentMesh._waitingFreezeWorldMatrix) {
  62577. currentMesh.freezeWorldMatrix();
  62578. currentMesh._waitingFreezeWorldMatrix = null;
  62579. }
  62580. else {
  62581. currentMesh.computeWorldMatrix(true);
  62582. }
  62583. }
  62584. }
  62585. // Particles
  62586. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  62587. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  62588. var parsedParticleSystem = parsedData.particleSystems[index];
  62589. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  62590. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  62591. }
  62592. }
  62593. }
  62594. return true;
  62595. }
  62596. catch (err) {
  62597. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  62598. if (onError) {
  62599. onError(msg, err);
  62600. }
  62601. else {
  62602. BABYLON.Tools.Log(msg);
  62603. throw err;
  62604. }
  62605. }
  62606. finally {
  62607. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  62608. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  62609. }
  62610. }
  62611. return false;
  62612. },
  62613. load: function (scene, data, rootUrl, onError) {
  62614. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  62615. // when SceneLoader.debugLogging = true (default), or exception encountered.
  62616. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  62617. // and avoid problems with multiple concurrent .babylon loads.
  62618. var log = "importScene has failed JSON parse";
  62619. try {
  62620. var parsedData = JSON.parse(data);
  62621. log = "";
  62622. // Scene
  62623. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  62624. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  62625. }
  62626. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  62627. scene.autoClear = parsedData.autoClear;
  62628. }
  62629. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  62630. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  62631. }
  62632. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  62633. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  62634. }
  62635. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  62636. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  62637. }
  62638. // Fog
  62639. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  62640. scene.fogMode = parsedData.fogMode;
  62641. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  62642. scene.fogStart = parsedData.fogStart;
  62643. scene.fogEnd = parsedData.fogEnd;
  62644. scene.fogDensity = parsedData.fogDensity;
  62645. log += "\tFog mode for scene: ";
  62646. switch (scene.fogMode) {
  62647. // getters not compiling, so using hardcoded
  62648. case 1:
  62649. log += "exp\n";
  62650. break;
  62651. case 2:
  62652. log += "exp2\n";
  62653. break;
  62654. case 3:
  62655. log += "linear\n";
  62656. break;
  62657. }
  62658. }
  62659. //Physics
  62660. if (parsedData.physicsEnabled) {
  62661. var physicsPlugin;
  62662. if (parsedData.physicsEngine === "cannon") {
  62663. physicsPlugin = new BABYLON.CannonJSPlugin();
  62664. }
  62665. else if (parsedData.physicsEngine === "oimo") {
  62666. physicsPlugin = new BABYLON.OimoJSPlugin();
  62667. }
  62668. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  62669. //else - default engine, which is currently oimo
  62670. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  62671. scene.enablePhysics(physicsGravity, physicsPlugin);
  62672. }
  62673. // Metadata
  62674. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  62675. scene.metadata = parsedData.metadata;
  62676. }
  62677. //collisions, if defined. otherwise, default is true
  62678. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  62679. scene.collisionsEnabled = parsedData.collisionsEnabled;
  62680. }
  62681. scene.workerCollisions = !!parsedData.workerCollisions;
  62682. var container = loadAssetContainer(scene, data, rootUrl, onError, true);
  62683. if (!container) {
  62684. return false;
  62685. }
  62686. if (parsedData.autoAnimate) {
  62687. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  62688. }
  62689. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  62690. scene.setActiveCameraByID(parsedData.activeCameraID);
  62691. }
  62692. // Environment texture
  62693. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  62694. scene.environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  62695. if (parsedData.createDefaultSkybox === true) {
  62696. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  62697. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  62698. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  62699. }
  62700. }
  62701. // Finish
  62702. return true;
  62703. }
  62704. catch (err) {
  62705. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  62706. if (onError) {
  62707. onError(msg, err);
  62708. }
  62709. else {
  62710. BABYLON.Tools.Log(msg);
  62711. throw err;
  62712. }
  62713. }
  62714. finally {
  62715. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  62716. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  62717. }
  62718. }
  62719. return false;
  62720. },
  62721. loadAssetContainer: function (scene, data, rootUrl, onError) {
  62722. var container = loadAssetContainer(scene, data, rootUrl, onError);
  62723. return container;
  62724. }
  62725. });
  62726. })(BABYLON || (BABYLON = {}));
  62727. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  62728. var BABYLON;
  62729. (function (BABYLON) {
  62730. var FilesInput = /** @class */ (function () {
  62731. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  62732. this.onProcessFileCallback = function () { return true; };
  62733. this._engine = engine;
  62734. this._currentScene = scene;
  62735. this._sceneLoadedCallback = sceneLoadedCallback;
  62736. this._progressCallback = progressCallback;
  62737. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  62738. this._textureLoadingCallback = textureLoadingCallback;
  62739. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  62740. this._onReloadCallback = onReloadCallback;
  62741. this._errorCallback = errorCallback;
  62742. }
  62743. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  62744. var _this = this;
  62745. if (elementToMonitor) {
  62746. this._elementToMonitor = elementToMonitor;
  62747. this._dragEnterHandler = function (e) { _this.drag(e); };
  62748. this._dragOverHandler = function (e) { _this.drag(e); };
  62749. this._dropHandler = function (e) { _this.drop(e); };
  62750. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  62751. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  62752. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  62753. }
  62754. };
  62755. FilesInput.prototype.dispose = function () {
  62756. if (!this._elementToMonitor) {
  62757. return;
  62758. }
  62759. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  62760. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  62761. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  62762. };
  62763. FilesInput.prototype.renderFunction = function () {
  62764. if (this._additionalRenderLoopLogicCallback) {
  62765. this._additionalRenderLoopLogicCallback();
  62766. }
  62767. if (this._currentScene) {
  62768. if (this._textureLoadingCallback) {
  62769. var remaining = this._currentScene.getWaitingItemsCount();
  62770. if (remaining > 0) {
  62771. this._textureLoadingCallback(remaining);
  62772. }
  62773. }
  62774. this._currentScene.render();
  62775. }
  62776. };
  62777. FilesInput.prototype.drag = function (e) {
  62778. e.stopPropagation();
  62779. e.preventDefault();
  62780. };
  62781. FilesInput.prototype.drop = function (eventDrop) {
  62782. eventDrop.stopPropagation();
  62783. eventDrop.preventDefault();
  62784. this.loadFiles(eventDrop);
  62785. };
  62786. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  62787. var _this = this;
  62788. var reader = folder.createReader();
  62789. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  62790. reader.readEntries(function (entries) {
  62791. remaining.count += entries.length;
  62792. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  62793. var entry = entries_1[_i];
  62794. if (entry.isFile) {
  62795. entry.file(function (file) {
  62796. file.correctName = relativePath + file.name;
  62797. files.push(file);
  62798. if (--remaining.count === 0) {
  62799. callback();
  62800. }
  62801. });
  62802. }
  62803. else if (entry.isDirectory) {
  62804. _this._traverseFolder(entry, files, remaining, callback);
  62805. }
  62806. }
  62807. if (--remaining.count) {
  62808. callback();
  62809. }
  62810. });
  62811. };
  62812. FilesInput.prototype._processFiles = function (files) {
  62813. for (var i = 0; i < files.length; i++) {
  62814. var name = files[i].correctName.toLowerCase();
  62815. var extension = name.split('.').pop();
  62816. if (!this.onProcessFileCallback(files[i], name, extension)) {
  62817. continue;
  62818. }
  62819. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  62820. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  62821. this._sceneFileToLoad = files[i];
  62822. }
  62823. else {
  62824. FilesInput.FilesToLoad[name] = files[i];
  62825. }
  62826. }
  62827. };
  62828. FilesInput.prototype.loadFiles = function (event) {
  62829. var _this = this;
  62830. if (this._startingProcessingFilesCallback)
  62831. this._startingProcessingFilesCallback();
  62832. // Handling data transfer via drag'n'drop
  62833. if (event && event.dataTransfer && event.dataTransfer.files) {
  62834. this._filesToLoad = event.dataTransfer.files;
  62835. }
  62836. // Handling files from input files
  62837. if (event && event.target && event.target.files) {
  62838. this._filesToLoad = event.target.files;
  62839. }
  62840. if (this._filesToLoad && this._filesToLoad.length > 0) {
  62841. var files_1 = new Array();
  62842. var folders = [];
  62843. var items = event.dataTransfer ? event.dataTransfer.items : null;
  62844. for (var i = 0; i < this._filesToLoad.length; i++) {
  62845. var fileToLoad = this._filesToLoad[i];
  62846. var name_1 = fileToLoad.name.toLowerCase();
  62847. var entry = void 0;
  62848. fileToLoad.correctName = name_1;
  62849. if (items) {
  62850. var item = items[i];
  62851. if (item.getAsEntry) {
  62852. entry = item.getAsEntry();
  62853. }
  62854. else if (item.webkitGetAsEntry) {
  62855. entry = item.webkitGetAsEntry();
  62856. }
  62857. }
  62858. if (!entry) {
  62859. files_1.push(fileToLoad);
  62860. }
  62861. else {
  62862. if (entry.isDirectory) {
  62863. folders.push(entry);
  62864. }
  62865. else {
  62866. files_1.push(fileToLoad);
  62867. }
  62868. }
  62869. }
  62870. if (folders.length === 0) {
  62871. this._processFiles(files_1);
  62872. this._processReload();
  62873. }
  62874. else {
  62875. var remaining = { count: folders.length };
  62876. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  62877. var folder = folders_1[_i];
  62878. this._traverseFolder(folder, files_1, remaining, function () {
  62879. _this._processFiles(files_1);
  62880. if (remaining.count === 0) {
  62881. _this._processReload();
  62882. }
  62883. });
  62884. }
  62885. }
  62886. }
  62887. };
  62888. FilesInput.prototype._processReload = function () {
  62889. if (this._onReloadCallback) {
  62890. this._onReloadCallback(this._sceneFileToLoad);
  62891. }
  62892. else {
  62893. this.reload();
  62894. }
  62895. };
  62896. FilesInput.prototype.reload = function () {
  62897. var _this = this;
  62898. // If a scene file has been provided
  62899. if (this._sceneFileToLoad) {
  62900. if (this._currentScene) {
  62901. if (BABYLON.Tools.errorsCount > 0) {
  62902. BABYLON.Tools.ClearLogCache();
  62903. }
  62904. this._engine.stopRenderLoop();
  62905. this._currentScene.dispose();
  62906. }
  62907. BABYLON.SceneLoader.LoadAsync("file:", this._sceneFileToLoad, this._engine, function (progress) {
  62908. if (_this._progressCallback) {
  62909. _this._progressCallback(progress);
  62910. }
  62911. }).then(function (scene) {
  62912. _this._currentScene = scene;
  62913. if (_this._sceneLoadedCallback) {
  62914. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  62915. }
  62916. // Wait for textures and shaders to be ready
  62917. _this._currentScene.executeWhenReady(function () {
  62918. _this._engine.runRenderLoop(function () {
  62919. _this.renderFunction();
  62920. });
  62921. });
  62922. }).catch(function (error) {
  62923. if (_this._errorCallback) {
  62924. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);
  62925. }
  62926. });
  62927. }
  62928. else {
  62929. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  62930. }
  62931. };
  62932. FilesInput.FilesToLoad = {};
  62933. return FilesInput;
  62934. }());
  62935. BABYLON.FilesInput = FilesInput;
  62936. })(BABYLON || (BABYLON = {}));
  62937. //# sourceMappingURL=babylon.filesInput.js.map
  62938. var BABYLON;
  62939. (function (BABYLON) {
  62940. /**
  62941. * This class implement a typical dictionary using a string as key and the generic type T as value.
  62942. * The underlying implementation relies on an associative array to ensure the best performances.
  62943. * The value can be anything including 'null' but except 'undefined'
  62944. */
  62945. var StringDictionary = /** @class */ (function () {
  62946. function StringDictionary() {
  62947. this._count = 0;
  62948. this._data = {};
  62949. }
  62950. /**
  62951. * This will clear this dictionary and copy the content from the 'source' one.
  62952. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  62953. * @param source the dictionary to take the content from and copy to this dictionary
  62954. */
  62955. StringDictionary.prototype.copyFrom = function (source) {
  62956. var _this = this;
  62957. this.clear();
  62958. source.forEach(function (t, v) { return _this.add(t, v); });
  62959. };
  62960. /**
  62961. * Get a value based from its key
  62962. * @param key the given key to get the matching value from
  62963. * @return the value if found, otherwise undefined is returned
  62964. */
  62965. StringDictionary.prototype.get = function (key) {
  62966. var val = this._data[key];
  62967. if (val !== undefined) {
  62968. return val;
  62969. }
  62970. return undefined;
  62971. };
  62972. /**
  62973. * Get a value from its key or add it if it doesn't exist.
  62974. * This method will ensure you that a given key/data will be present in the dictionary.
  62975. * @param key the given key to get the matching value from
  62976. * @param factory the factory that will create the value if the key is not present in the dictionary.
  62977. * The factory will only be invoked if there's no data for the given key.
  62978. * @return the value corresponding to the key.
  62979. */
  62980. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  62981. var val = this.get(key);
  62982. if (val !== undefined) {
  62983. return val;
  62984. }
  62985. val = factory(key);
  62986. if (val) {
  62987. this.add(key, val);
  62988. }
  62989. return val;
  62990. };
  62991. /**
  62992. * Get a value from its key if present in the dictionary otherwise add it
  62993. * @param key the key to get the value from
  62994. * @param val if there's no such key/value pair in the dictionary add it with this value
  62995. * @return the value corresponding to the key
  62996. */
  62997. StringDictionary.prototype.getOrAdd = function (key, val) {
  62998. var curVal = this.get(key);
  62999. if (curVal !== undefined) {
  63000. return curVal;
  63001. }
  63002. this.add(key, val);
  63003. return val;
  63004. };
  63005. /**
  63006. * Check if there's a given key in the dictionary
  63007. * @param key the key to check for
  63008. * @return true if the key is present, false otherwise
  63009. */
  63010. StringDictionary.prototype.contains = function (key) {
  63011. return this._data[key] !== undefined;
  63012. };
  63013. /**
  63014. * Add a new key and its corresponding value
  63015. * @param key the key to add
  63016. * @param value the value corresponding to the key
  63017. * @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
  63018. */
  63019. StringDictionary.prototype.add = function (key, value) {
  63020. if (this._data[key] !== undefined) {
  63021. return false;
  63022. }
  63023. this._data[key] = value;
  63024. ++this._count;
  63025. return true;
  63026. };
  63027. StringDictionary.prototype.set = function (key, value) {
  63028. if (this._data[key] === undefined) {
  63029. return false;
  63030. }
  63031. this._data[key] = value;
  63032. return true;
  63033. };
  63034. /**
  63035. * Get the element of the given key and remove it from the dictionary
  63036. * @param key
  63037. */
  63038. StringDictionary.prototype.getAndRemove = function (key) {
  63039. var val = this.get(key);
  63040. if (val !== undefined) {
  63041. delete this._data[key];
  63042. --this._count;
  63043. return val;
  63044. }
  63045. return null;
  63046. };
  63047. /**
  63048. * Remove a key/value from the dictionary.
  63049. * @param key the key to remove
  63050. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  63051. */
  63052. StringDictionary.prototype.remove = function (key) {
  63053. if (this.contains(key)) {
  63054. delete this._data[key];
  63055. --this._count;
  63056. return true;
  63057. }
  63058. return false;
  63059. };
  63060. /**
  63061. * Clear the whole content of the dictionary
  63062. */
  63063. StringDictionary.prototype.clear = function () {
  63064. this._data = {};
  63065. this._count = 0;
  63066. };
  63067. Object.defineProperty(StringDictionary.prototype, "count", {
  63068. get: function () {
  63069. return this._count;
  63070. },
  63071. enumerable: true,
  63072. configurable: true
  63073. });
  63074. /**
  63075. * Execute a callback on each key/val of the dictionary.
  63076. * Note that you can remove any element in this dictionary in the callback implementation
  63077. * @param callback the callback to execute on a given key/value pair
  63078. */
  63079. StringDictionary.prototype.forEach = function (callback) {
  63080. for (var cur in this._data) {
  63081. var val = this._data[cur];
  63082. callback(cur, val);
  63083. }
  63084. };
  63085. /**
  63086. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  63087. * If the callback returns null or undefined the method will iterate to the next key/value pair
  63088. * Note that you can remove any element in this dictionary in the callback implementation
  63089. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  63090. */
  63091. StringDictionary.prototype.first = function (callback) {
  63092. for (var cur in this._data) {
  63093. var val = this._data[cur];
  63094. var res = callback(cur, val);
  63095. if (res) {
  63096. return res;
  63097. }
  63098. }
  63099. return null;
  63100. };
  63101. return StringDictionary;
  63102. }());
  63103. BABYLON.StringDictionary = StringDictionary;
  63104. })(BABYLON || (BABYLON = {}));
  63105. //# sourceMappingURL=babylon.stringDictionary.js.map
  63106. var BABYLON;
  63107. (function (BABYLON) {
  63108. var Tags = /** @class */ (function () {
  63109. function Tags() {
  63110. }
  63111. Tags.EnableFor = function (obj) {
  63112. obj._tags = obj._tags || {};
  63113. obj.hasTags = function () {
  63114. return Tags.HasTags(obj);
  63115. };
  63116. obj.addTags = function (tagsString) {
  63117. return Tags.AddTagsTo(obj, tagsString);
  63118. };
  63119. obj.removeTags = function (tagsString) {
  63120. return Tags.RemoveTagsFrom(obj, tagsString);
  63121. };
  63122. obj.matchesTagsQuery = function (tagsQuery) {
  63123. return Tags.MatchesQuery(obj, tagsQuery);
  63124. };
  63125. };
  63126. Tags.DisableFor = function (obj) {
  63127. delete obj._tags;
  63128. delete obj.hasTags;
  63129. delete obj.addTags;
  63130. delete obj.removeTags;
  63131. delete obj.matchesTagsQuery;
  63132. };
  63133. Tags.HasTags = function (obj) {
  63134. if (!obj._tags) {
  63135. return false;
  63136. }
  63137. return !BABYLON.Tools.IsEmpty(obj._tags);
  63138. };
  63139. Tags.GetTags = function (obj, asString) {
  63140. if (asString === void 0) { asString = true; }
  63141. if (!obj._tags) {
  63142. return null;
  63143. }
  63144. if (asString) {
  63145. var tagsArray = [];
  63146. for (var tag in obj._tags) {
  63147. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  63148. tagsArray.push(tag);
  63149. }
  63150. }
  63151. return tagsArray.join(" ");
  63152. }
  63153. else {
  63154. return obj._tags;
  63155. }
  63156. };
  63157. // the tags 'true' and 'false' are reserved and cannot be used as tags
  63158. // a tag cannot start with '||', '&&', and '!'
  63159. // it cannot contain whitespaces
  63160. Tags.AddTagsTo = function (obj, tagsString) {
  63161. if (!tagsString) {
  63162. return;
  63163. }
  63164. if (typeof tagsString !== "string") {
  63165. return;
  63166. }
  63167. var tags = tagsString.split(" ");
  63168. tags.forEach(function (tag, index, array) {
  63169. Tags._AddTagTo(obj, tag);
  63170. });
  63171. };
  63172. Tags._AddTagTo = function (obj, tag) {
  63173. tag = tag.trim();
  63174. if (tag === "" || tag === "true" || tag === "false") {
  63175. return;
  63176. }
  63177. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  63178. return;
  63179. }
  63180. Tags.EnableFor(obj);
  63181. obj._tags[tag] = true;
  63182. };
  63183. Tags.RemoveTagsFrom = function (obj, tagsString) {
  63184. if (!Tags.HasTags(obj)) {
  63185. return;
  63186. }
  63187. var tags = tagsString.split(" ");
  63188. for (var t in tags) {
  63189. Tags._RemoveTagFrom(obj, tags[t]);
  63190. }
  63191. };
  63192. Tags._RemoveTagFrom = function (obj, tag) {
  63193. delete obj._tags[tag];
  63194. };
  63195. Tags.MatchesQuery = function (obj, tagsQuery) {
  63196. if (tagsQuery === undefined) {
  63197. return true;
  63198. }
  63199. if (tagsQuery === "") {
  63200. return Tags.HasTags(obj);
  63201. }
  63202. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  63203. };
  63204. return Tags;
  63205. }());
  63206. BABYLON.Tags = Tags;
  63207. })(BABYLON || (BABYLON = {}));
  63208. //# sourceMappingURL=babylon.tags.js.map
  63209. var BABYLON;
  63210. (function (BABYLON) {
  63211. var AndOrNotEvaluator = /** @class */ (function () {
  63212. function AndOrNotEvaluator() {
  63213. }
  63214. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  63215. if (!query.match(/\([^\(\)]*\)/g)) {
  63216. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  63217. }
  63218. else {
  63219. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  63220. // remove parenthesis
  63221. r = r.slice(1, r.length - 1);
  63222. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  63223. });
  63224. }
  63225. if (query === "true") {
  63226. return true;
  63227. }
  63228. if (query === "false") {
  63229. return false;
  63230. }
  63231. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  63232. };
  63233. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  63234. evaluateCallback = evaluateCallback || (function (r) {
  63235. return r === "true" ? true : false;
  63236. });
  63237. var result;
  63238. var or = parenthesisContent.split("||");
  63239. for (var i in or) {
  63240. if (or.hasOwnProperty(i)) {
  63241. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  63242. var and = ori.split("&&");
  63243. if (and.length > 1) {
  63244. for (var j = 0; j < and.length; ++j) {
  63245. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  63246. if (andj !== "true" && andj !== "false") {
  63247. if (andj[0] === "!") {
  63248. result = !evaluateCallback(andj.substring(1));
  63249. }
  63250. else {
  63251. result = evaluateCallback(andj);
  63252. }
  63253. }
  63254. else {
  63255. result = andj === "true" ? true : false;
  63256. }
  63257. if (!result) {
  63258. ori = "false";
  63259. break;
  63260. }
  63261. }
  63262. }
  63263. if (result || ori === "true") {
  63264. result = true;
  63265. break;
  63266. }
  63267. // result equals false (or undefined)
  63268. if (ori !== "true" && ori !== "false") {
  63269. if (ori[0] === "!") {
  63270. result = !evaluateCallback(ori.substring(1));
  63271. }
  63272. else {
  63273. result = evaluateCallback(ori);
  63274. }
  63275. }
  63276. else {
  63277. result = ori === "true" ? true : false;
  63278. }
  63279. }
  63280. }
  63281. // the whole parenthesis scope is replaced by 'true' or 'false'
  63282. return result ? "true" : "false";
  63283. };
  63284. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  63285. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  63286. // remove whitespaces
  63287. r = r.replace(/[\s]/g, function () { return ""; });
  63288. return r.length % 2 ? "!" : "";
  63289. });
  63290. booleanString = booleanString.trim();
  63291. if (booleanString === "!true") {
  63292. booleanString = "false";
  63293. }
  63294. else if (booleanString === "!false") {
  63295. booleanString = "true";
  63296. }
  63297. return booleanString;
  63298. };
  63299. return AndOrNotEvaluator;
  63300. }());
  63301. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  63302. })(BABYLON || (BABYLON = {}));
  63303. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  63304. var BABYLON;
  63305. (function (BABYLON) {
  63306. var Database = /** @class */ (function () {
  63307. function Database(urlToScene, callbackManifestChecked) {
  63308. // Handling various flavors of prefixed version of IndexedDB
  63309. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  63310. this.callbackManifestChecked = callbackManifestChecked;
  63311. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  63312. this.db = null;
  63313. this._enableSceneOffline = false;
  63314. this._enableTexturesOffline = false;
  63315. this.manifestVersionFound = 0;
  63316. this.mustUpdateRessources = false;
  63317. this.hasReachedQuota = false;
  63318. if (!Database.IDBStorageEnabled) {
  63319. this.callbackManifestChecked(true);
  63320. }
  63321. else {
  63322. this.checkManifestFile();
  63323. }
  63324. }
  63325. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  63326. get: function () {
  63327. return this._enableSceneOffline;
  63328. },
  63329. enumerable: true,
  63330. configurable: true
  63331. });
  63332. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  63333. get: function () {
  63334. return this._enableTexturesOffline;
  63335. },
  63336. enumerable: true,
  63337. configurable: true
  63338. });
  63339. Database.prototype.checkManifestFile = function () {
  63340. var _this = this;
  63341. var noManifestFile = function () {
  63342. _this._enableSceneOffline = false;
  63343. _this._enableTexturesOffline = false;
  63344. _this.callbackManifestChecked(false);
  63345. };
  63346. var timeStampUsed = false;
  63347. var manifestURL = this.currentSceneUrl + ".manifest";
  63348. var xhr = new XMLHttpRequest();
  63349. if (navigator.onLine) {
  63350. // Adding a timestamp to by-pass browsers' cache
  63351. timeStampUsed = true;
  63352. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  63353. }
  63354. xhr.open("GET", manifestURL, true);
  63355. xhr.addEventListener("load", function () {
  63356. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  63357. try {
  63358. var manifestFile = JSON.parse(xhr.response);
  63359. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  63360. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  63361. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  63362. _this.manifestVersionFound = manifestFile.version;
  63363. }
  63364. if (_this.callbackManifestChecked) {
  63365. _this.callbackManifestChecked(true);
  63366. }
  63367. }
  63368. catch (ex) {
  63369. noManifestFile();
  63370. }
  63371. }
  63372. else {
  63373. noManifestFile();
  63374. }
  63375. }, false);
  63376. xhr.addEventListener("error", function (event) {
  63377. if (timeStampUsed) {
  63378. timeStampUsed = false;
  63379. // Let's retry without the timeStamp
  63380. // It could fail when coupled with HTML5 Offline API
  63381. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  63382. xhr.open("GET", retryManifestURL, true);
  63383. xhr.send();
  63384. }
  63385. else {
  63386. noManifestFile();
  63387. }
  63388. }, false);
  63389. try {
  63390. xhr.send();
  63391. }
  63392. catch (ex) {
  63393. BABYLON.Tools.Error("Error on XHR send request.");
  63394. this.callbackManifestChecked(false);
  63395. }
  63396. };
  63397. Database.prototype.openAsync = function (successCallback, errorCallback) {
  63398. var _this = this;
  63399. var handleError = function () {
  63400. _this.isSupported = false;
  63401. if (errorCallback)
  63402. errorCallback();
  63403. };
  63404. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  63405. // Your browser doesn't support IndexedDB
  63406. this.isSupported = false;
  63407. if (errorCallback)
  63408. errorCallback();
  63409. }
  63410. else {
  63411. // If the DB hasn't been opened or created yet
  63412. if (!this.db) {
  63413. this.hasReachedQuota = false;
  63414. this.isSupported = true;
  63415. var request = this.idbFactory.open("babylonjs", 1);
  63416. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  63417. request.onerror = function (event) {
  63418. handleError();
  63419. };
  63420. // executes when a version change transaction cannot complete due to other active transactions
  63421. request.onblocked = function (event) {
  63422. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  63423. handleError();
  63424. };
  63425. // DB has been opened successfully
  63426. request.onsuccess = function (event) {
  63427. _this.db = request.result;
  63428. successCallback();
  63429. };
  63430. // Initialization of the DB. Creating Scenes & Textures stores
  63431. request.onupgradeneeded = function (event) {
  63432. _this.db = (event.target).result;
  63433. if (_this.db) {
  63434. try {
  63435. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  63436. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  63437. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  63438. }
  63439. catch (ex) {
  63440. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  63441. handleError();
  63442. }
  63443. }
  63444. };
  63445. }
  63446. else {
  63447. if (successCallback)
  63448. successCallback();
  63449. }
  63450. }
  63451. };
  63452. Database.prototype.loadImageFromDB = function (url, image) {
  63453. var _this = this;
  63454. var completeURL = Database.ReturnFullUrlLocation(url);
  63455. var saveAndLoadImage = function () {
  63456. if (!_this.hasReachedQuota && _this.db !== null) {
  63457. // the texture is not yet in the DB, let's try to save it
  63458. _this._saveImageIntoDBAsync(completeURL, image);
  63459. }
  63460. else {
  63461. image.src = url;
  63462. }
  63463. };
  63464. if (!this.mustUpdateRessources) {
  63465. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  63466. }
  63467. else {
  63468. saveAndLoadImage();
  63469. }
  63470. };
  63471. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  63472. if (this.isSupported && this.db !== null) {
  63473. var texture;
  63474. var transaction = this.db.transaction(["textures"]);
  63475. transaction.onabort = function (event) {
  63476. image.src = url;
  63477. };
  63478. transaction.oncomplete = function (event) {
  63479. var blobTextureURL;
  63480. if (texture) {
  63481. var URL = window.URL || window.webkitURL;
  63482. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  63483. image.onerror = function () {
  63484. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  63485. image.src = url;
  63486. };
  63487. image.src = blobTextureURL;
  63488. }
  63489. else {
  63490. notInDBCallback();
  63491. }
  63492. };
  63493. var getRequest = transaction.objectStore("textures").get(url);
  63494. getRequest.onsuccess = function (event) {
  63495. texture = (event.target).result;
  63496. };
  63497. getRequest.onerror = function (event) {
  63498. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  63499. image.src = url;
  63500. };
  63501. }
  63502. else {
  63503. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  63504. image.src = url;
  63505. }
  63506. };
  63507. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  63508. var _this = this;
  63509. if (this.isSupported) {
  63510. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  63511. var generateBlobUrl = function () {
  63512. var blobTextureURL;
  63513. if (blob) {
  63514. var URL = window.URL || window.webkitURL;
  63515. try {
  63516. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  63517. }
  63518. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  63519. catch (ex) {
  63520. blobTextureURL = URL.createObjectURL(blob);
  63521. }
  63522. }
  63523. if (blobTextureURL) {
  63524. image.src = blobTextureURL;
  63525. }
  63526. };
  63527. if (Database.IsUASupportingBlobStorage) {
  63528. var xhr = new XMLHttpRequest(), blob;
  63529. xhr.open("GET", url, true);
  63530. xhr.responseType = "blob";
  63531. xhr.addEventListener("load", function () {
  63532. if (xhr.status === 200 && _this.db) {
  63533. // Blob as response (XHR2)
  63534. blob = xhr.response;
  63535. var transaction = _this.db.transaction(["textures"], "readwrite");
  63536. // the transaction could abort because of a QuotaExceededError error
  63537. transaction.onabort = function (event) {
  63538. try {
  63539. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  63540. var srcElement = (event.srcElement || event.target);
  63541. var error = srcElement.error;
  63542. if (error && error.name === "QuotaExceededError") {
  63543. _this.hasReachedQuota = true;
  63544. }
  63545. }
  63546. catch (ex) { }
  63547. generateBlobUrl();
  63548. };
  63549. transaction.oncomplete = function (event) {
  63550. generateBlobUrl();
  63551. };
  63552. var newTexture = { textureUrl: url, data: blob };
  63553. try {
  63554. // Put the blob into the dabase
  63555. var addRequest = transaction.objectStore("textures").put(newTexture);
  63556. addRequest.onsuccess = function (event) {
  63557. };
  63558. addRequest.onerror = function (event) {
  63559. generateBlobUrl();
  63560. };
  63561. }
  63562. catch (ex) {
  63563. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  63564. if (ex.code === 25) {
  63565. Database.IsUASupportingBlobStorage = false;
  63566. }
  63567. image.src = url;
  63568. }
  63569. }
  63570. else {
  63571. image.src = url;
  63572. }
  63573. }, false);
  63574. xhr.addEventListener("error", function (event) {
  63575. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  63576. image.src = url;
  63577. }, false);
  63578. xhr.send();
  63579. }
  63580. else {
  63581. image.src = url;
  63582. }
  63583. }
  63584. else {
  63585. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  63586. image.src = url;
  63587. }
  63588. };
  63589. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  63590. var _this = this;
  63591. var updateVersion = function () {
  63592. // the version is not yet in the DB or we need to update it
  63593. _this._saveVersionIntoDBAsync(url, versionLoaded);
  63594. };
  63595. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  63596. };
  63597. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  63598. var _this = this;
  63599. if (this.isSupported && this.db) {
  63600. var version;
  63601. try {
  63602. var transaction = this.db.transaction(["versions"]);
  63603. transaction.oncomplete = function (event) {
  63604. if (version) {
  63605. // If the version in the JSON file is > than the version in DB
  63606. if (_this.manifestVersionFound > version.data) {
  63607. _this.mustUpdateRessources = true;
  63608. updateInDBCallback();
  63609. }
  63610. else {
  63611. callback(version.data);
  63612. }
  63613. }
  63614. else {
  63615. _this.mustUpdateRessources = true;
  63616. updateInDBCallback();
  63617. }
  63618. };
  63619. transaction.onabort = function (event) {
  63620. callback(-1);
  63621. };
  63622. var getRequest = transaction.objectStore("versions").get(url);
  63623. getRequest.onsuccess = function (event) {
  63624. version = (event.target).result;
  63625. };
  63626. getRequest.onerror = function (event) {
  63627. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  63628. callback(-1);
  63629. };
  63630. }
  63631. catch (ex) {
  63632. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  63633. callback(-1);
  63634. }
  63635. }
  63636. else {
  63637. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  63638. callback(-1);
  63639. }
  63640. };
  63641. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  63642. var _this = this;
  63643. if (this.isSupported && !this.hasReachedQuota && this.db) {
  63644. try {
  63645. // Open a transaction to the database
  63646. var transaction = this.db.transaction(["versions"], "readwrite");
  63647. // the transaction could abort because of a QuotaExceededError error
  63648. transaction.onabort = function (event) {
  63649. try {
  63650. var error = event.srcElement['error'];
  63651. if (error && error.name === "QuotaExceededError") {
  63652. _this.hasReachedQuota = true;
  63653. }
  63654. }
  63655. catch (ex) { }
  63656. callback(-1);
  63657. };
  63658. transaction.oncomplete = function (event) {
  63659. callback(_this.manifestVersionFound);
  63660. };
  63661. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  63662. // Put the scene into the database
  63663. var addRequest = transaction.objectStore("versions").put(newVersion);
  63664. addRequest.onsuccess = function (event) {
  63665. };
  63666. addRequest.onerror = function (event) {
  63667. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  63668. };
  63669. }
  63670. catch (ex) {
  63671. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  63672. callback(-1);
  63673. }
  63674. }
  63675. else {
  63676. callback(-1);
  63677. }
  63678. };
  63679. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  63680. var _this = this;
  63681. var completeUrl = Database.ReturnFullUrlLocation(url);
  63682. var saveAndLoadFile = function () {
  63683. // the scene is not yet in the DB, let's try to save it
  63684. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  63685. };
  63686. this._checkVersionFromDB(completeUrl, function (version) {
  63687. if (version !== -1) {
  63688. if (!_this.mustUpdateRessources) {
  63689. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  63690. }
  63691. else {
  63692. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  63693. }
  63694. }
  63695. else {
  63696. if (errorCallback) {
  63697. errorCallback();
  63698. }
  63699. }
  63700. });
  63701. };
  63702. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  63703. if (this.isSupported && this.db) {
  63704. var targetStore;
  63705. if (url.indexOf(".babylon") !== -1) {
  63706. targetStore = "scenes";
  63707. }
  63708. else {
  63709. targetStore = "textures";
  63710. }
  63711. var file;
  63712. var transaction = this.db.transaction([targetStore]);
  63713. transaction.oncomplete = function (event) {
  63714. if (file) {
  63715. callback(file.data);
  63716. }
  63717. else {
  63718. notInDBCallback();
  63719. }
  63720. };
  63721. transaction.onabort = function (event) {
  63722. notInDBCallback();
  63723. };
  63724. var getRequest = transaction.objectStore(targetStore).get(url);
  63725. getRequest.onsuccess = function (event) {
  63726. file = (event.target).result;
  63727. };
  63728. getRequest.onerror = function (event) {
  63729. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  63730. notInDBCallback();
  63731. };
  63732. }
  63733. else {
  63734. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  63735. callback();
  63736. }
  63737. };
  63738. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  63739. var _this = this;
  63740. if (this.isSupported) {
  63741. var targetStore;
  63742. if (url.indexOf(".babylon") !== -1) {
  63743. targetStore = "scenes";
  63744. }
  63745. else {
  63746. targetStore = "textures";
  63747. }
  63748. // Create XHR
  63749. var xhr = new XMLHttpRequest();
  63750. var fileData;
  63751. xhr.open("GET", url, true);
  63752. if (useArrayBuffer) {
  63753. xhr.responseType = "arraybuffer";
  63754. }
  63755. if (progressCallback) {
  63756. xhr.onprogress = progressCallback;
  63757. }
  63758. xhr.addEventListener("load", function () {
  63759. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  63760. // Blob as response (XHR2)
  63761. //fileData = xhr.responseText;
  63762. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  63763. if (!_this.hasReachedQuota && _this.db) {
  63764. // Open a transaction to the database
  63765. var transaction = _this.db.transaction([targetStore], "readwrite");
  63766. // the transaction could abort because of a QuotaExceededError error
  63767. transaction.onabort = function (event) {
  63768. try {
  63769. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  63770. var error = event.srcElement['error'];
  63771. if (error && error.name === "QuotaExceededError") {
  63772. _this.hasReachedQuota = true;
  63773. }
  63774. }
  63775. catch (ex) { }
  63776. callback(fileData);
  63777. };
  63778. transaction.oncomplete = function (event) {
  63779. callback(fileData);
  63780. };
  63781. var newFile;
  63782. if (targetStore === "scenes") {
  63783. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  63784. }
  63785. else {
  63786. newFile = { textureUrl: url, data: fileData };
  63787. }
  63788. try {
  63789. // Put the scene into the database
  63790. var addRequest = transaction.objectStore(targetStore).put(newFile);
  63791. addRequest.onsuccess = function (event) {
  63792. };
  63793. addRequest.onerror = function (event) {
  63794. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  63795. };
  63796. }
  63797. catch (ex) {
  63798. callback(fileData);
  63799. }
  63800. }
  63801. else {
  63802. callback(fileData);
  63803. }
  63804. }
  63805. else {
  63806. callback();
  63807. }
  63808. }, false);
  63809. xhr.addEventListener("error", function (event) {
  63810. BABYLON.Tools.Error("error on XHR request.");
  63811. callback();
  63812. }, false);
  63813. xhr.send();
  63814. }
  63815. else {
  63816. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  63817. callback();
  63818. }
  63819. };
  63820. Database.IsUASupportingBlobStorage = true;
  63821. Database.IDBStorageEnabled = true;
  63822. Database.parseURL = function (url) {
  63823. var a = document.createElement('a');
  63824. a.href = url;
  63825. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  63826. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  63827. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  63828. return absLocation;
  63829. };
  63830. Database.ReturnFullUrlLocation = function (url) {
  63831. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  63832. return (Database.parseURL(window.location.href) + url);
  63833. }
  63834. else {
  63835. return url;
  63836. }
  63837. };
  63838. return Database;
  63839. }());
  63840. BABYLON.Database = Database;
  63841. })(BABYLON || (BABYLON = {}));
  63842. //# sourceMappingURL=babylon.database.js.map
  63843. var BABYLON;
  63844. (function (BABYLON) {
  63845. var FresnelParameters = /** @class */ (function () {
  63846. function FresnelParameters() {
  63847. this._isEnabled = true;
  63848. this.leftColor = BABYLON.Color3.White();
  63849. this.rightColor = BABYLON.Color3.Black();
  63850. this.bias = 0;
  63851. this.power = 1;
  63852. }
  63853. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  63854. get: function () {
  63855. return this._isEnabled;
  63856. },
  63857. set: function (value) {
  63858. if (this._isEnabled === value) {
  63859. return;
  63860. }
  63861. this._isEnabled = value;
  63862. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  63863. },
  63864. enumerable: true,
  63865. configurable: true
  63866. });
  63867. FresnelParameters.prototype.clone = function () {
  63868. var newFresnelParameters = new FresnelParameters();
  63869. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  63870. return newFresnelParameters;
  63871. };
  63872. FresnelParameters.prototype.serialize = function () {
  63873. var serializationObject = {};
  63874. serializationObject.isEnabled = this.isEnabled;
  63875. serializationObject.leftColor = this.leftColor;
  63876. serializationObject.rightColor = this.rightColor;
  63877. serializationObject.bias = this.bias;
  63878. serializationObject.power = this.power;
  63879. return serializationObject;
  63880. };
  63881. FresnelParameters.Parse = function (parsedFresnelParameters) {
  63882. var fresnelParameters = new FresnelParameters();
  63883. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  63884. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  63885. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  63886. fresnelParameters.bias = parsedFresnelParameters.bias;
  63887. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  63888. return fresnelParameters;
  63889. };
  63890. return FresnelParameters;
  63891. }());
  63892. BABYLON.FresnelParameters = FresnelParameters;
  63893. })(BABYLON || (BABYLON = {}));
  63894. //# sourceMappingURL=babylon.fresnelParameters.js.map
  63895. var BABYLON;
  63896. (function (BABYLON) {
  63897. var MultiMaterial = /** @class */ (function (_super) {
  63898. __extends(MultiMaterial, _super);
  63899. function MultiMaterial(name, scene) {
  63900. var _this = _super.call(this, name, scene, true) || this;
  63901. scene.multiMaterials.push(_this);
  63902. _this.subMaterials = new Array();
  63903. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  63904. return _this;
  63905. }
  63906. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  63907. get: function () {
  63908. return this._subMaterials;
  63909. },
  63910. set: function (value) {
  63911. this._subMaterials = value;
  63912. this._hookArray(value);
  63913. },
  63914. enumerable: true,
  63915. configurable: true
  63916. });
  63917. MultiMaterial.prototype._hookArray = function (array) {
  63918. var _this = this;
  63919. var oldPush = array.push;
  63920. array.push = function () {
  63921. var items = [];
  63922. for (var _i = 0; _i < arguments.length; _i++) {
  63923. items[_i] = arguments[_i];
  63924. }
  63925. var result = oldPush.apply(array, items);
  63926. _this._markAllSubMeshesAsTexturesDirty();
  63927. return result;
  63928. };
  63929. var oldSplice = array.splice;
  63930. array.splice = function (index, deleteCount) {
  63931. var deleted = oldSplice.apply(array, [index, deleteCount]);
  63932. _this._markAllSubMeshesAsTexturesDirty();
  63933. return deleted;
  63934. };
  63935. };
  63936. // Properties
  63937. MultiMaterial.prototype.getSubMaterial = function (index) {
  63938. if (index < 0 || index >= this.subMaterials.length) {
  63939. return this.getScene().defaultMaterial;
  63940. }
  63941. return this.subMaterials[index];
  63942. };
  63943. MultiMaterial.prototype.getActiveTextures = function () {
  63944. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  63945. if (subMaterial) {
  63946. return subMaterial.getActiveTextures();
  63947. }
  63948. else {
  63949. return [];
  63950. }
  63951. }));
  63952. var _a;
  63953. };
  63954. // Methods
  63955. MultiMaterial.prototype.getClassName = function () {
  63956. return "MultiMaterial";
  63957. };
  63958. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  63959. for (var index = 0; index < this.subMaterials.length; index++) {
  63960. var subMaterial = this.subMaterials[index];
  63961. if (subMaterial) {
  63962. if (subMaterial.storeEffectOnSubMeshes) {
  63963. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  63964. return false;
  63965. }
  63966. continue;
  63967. }
  63968. if (!subMaterial.isReady(mesh)) {
  63969. return false;
  63970. }
  63971. }
  63972. }
  63973. return true;
  63974. };
  63975. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  63976. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  63977. for (var index = 0; index < this.subMaterials.length; index++) {
  63978. var subMaterial = null;
  63979. var current = this.subMaterials[index];
  63980. if (cloneChildren && current) {
  63981. subMaterial = current.clone(name + "-" + current.name);
  63982. }
  63983. else {
  63984. subMaterial = this.subMaterials[index];
  63985. }
  63986. newMultiMaterial.subMaterials.push(subMaterial);
  63987. }
  63988. return newMultiMaterial;
  63989. };
  63990. MultiMaterial.prototype.serialize = function () {
  63991. var serializationObject = {};
  63992. serializationObject.name = this.name;
  63993. serializationObject.id = this.id;
  63994. if (BABYLON.Tags) {
  63995. serializationObject.tags = BABYLON.Tags.GetTags(this);
  63996. }
  63997. serializationObject.materials = [];
  63998. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  63999. var subMat = this.subMaterials[matIndex];
  64000. if (subMat) {
  64001. serializationObject.materials.push(subMat.id);
  64002. }
  64003. else {
  64004. serializationObject.materials.push(null);
  64005. }
  64006. }
  64007. return serializationObject;
  64008. };
  64009. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  64010. var scene = this.getScene();
  64011. if (!scene) {
  64012. return;
  64013. }
  64014. var index = scene.multiMaterials.indexOf(this);
  64015. if (index >= 0) {
  64016. scene.multiMaterials.splice(index, 1);
  64017. }
  64018. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  64019. };
  64020. return MultiMaterial;
  64021. }(BABYLON.Material));
  64022. BABYLON.MultiMaterial = MultiMaterial;
  64023. })(BABYLON || (BABYLON = {}));
  64024. //# sourceMappingURL=babylon.multiMaterial.js.map
  64025. var BABYLON;
  64026. (function (BABYLON) {
  64027. var FreeCameraTouchInput = /** @class */ (function () {
  64028. function FreeCameraTouchInput() {
  64029. this._offsetX = null;
  64030. this._offsetY = null;
  64031. this._pointerPressed = new Array();
  64032. this.touchAngularSensibility = 200000.0;
  64033. this.touchMoveSensibility = 250.0;
  64034. }
  64035. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  64036. var _this = this;
  64037. var previousPosition = null;
  64038. if (this._pointerInput === undefined) {
  64039. this._onLostFocus = function (evt) {
  64040. _this._offsetX = null;
  64041. _this._offsetY = null;
  64042. };
  64043. this._pointerInput = function (p, s) {
  64044. var evt = p.event;
  64045. if (evt.pointerType === "mouse") {
  64046. return;
  64047. }
  64048. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  64049. if (!noPreventDefault) {
  64050. evt.preventDefault();
  64051. }
  64052. _this._pointerPressed.push(evt.pointerId);
  64053. if (_this._pointerPressed.length !== 1) {
  64054. return;
  64055. }
  64056. previousPosition = {
  64057. x: evt.clientX,
  64058. y: evt.clientY
  64059. };
  64060. }
  64061. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  64062. if (!noPreventDefault) {
  64063. evt.preventDefault();
  64064. }
  64065. var index = _this._pointerPressed.indexOf(evt.pointerId);
  64066. if (index === -1) {
  64067. return;
  64068. }
  64069. _this._pointerPressed.splice(index, 1);
  64070. if (index != 0) {
  64071. return;
  64072. }
  64073. previousPosition = null;
  64074. _this._offsetX = null;
  64075. _this._offsetY = null;
  64076. }
  64077. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  64078. if (!noPreventDefault) {
  64079. evt.preventDefault();
  64080. }
  64081. if (!previousPosition) {
  64082. return;
  64083. }
  64084. var index = _this._pointerPressed.indexOf(evt.pointerId);
  64085. if (index != 0) {
  64086. return;
  64087. }
  64088. _this._offsetX = evt.clientX - previousPosition.x;
  64089. _this._offsetY = -(evt.clientY - previousPosition.y);
  64090. }
  64091. };
  64092. }
  64093. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  64094. if (this._onLostFocus) {
  64095. element.addEventListener("blur", this._onLostFocus);
  64096. }
  64097. };
  64098. FreeCameraTouchInput.prototype.detachControl = function (element) {
  64099. if (this._pointerInput && element) {
  64100. if (this._observer) {
  64101. this.camera.getScene().onPointerObservable.remove(this._observer);
  64102. this._observer = null;
  64103. }
  64104. if (this._onLostFocus) {
  64105. element.removeEventListener("blur", this._onLostFocus);
  64106. this._onLostFocus = null;
  64107. }
  64108. this._pointerPressed = [];
  64109. this._offsetX = null;
  64110. this._offsetY = null;
  64111. }
  64112. };
  64113. FreeCameraTouchInput.prototype.checkInputs = function () {
  64114. if (this._offsetX && this._offsetY) {
  64115. var camera = this.camera;
  64116. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  64117. if (this._pointerPressed.length > 1) {
  64118. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  64119. }
  64120. else {
  64121. var speed = camera._computeLocalCameraSpeed();
  64122. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  64123. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  64124. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  64125. }
  64126. }
  64127. };
  64128. FreeCameraTouchInput.prototype.getClassName = function () {
  64129. return "FreeCameraTouchInput";
  64130. };
  64131. FreeCameraTouchInput.prototype.getSimpleName = function () {
  64132. return "touch";
  64133. };
  64134. __decorate([
  64135. BABYLON.serialize()
  64136. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  64137. __decorate([
  64138. BABYLON.serialize()
  64139. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  64140. return FreeCameraTouchInput;
  64141. }());
  64142. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  64143. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  64144. })(BABYLON || (BABYLON = {}));
  64145. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  64146. var BABYLON;
  64147. (function (BABYLON) {
  64148. // We're mainly based on the logic defined into the FreeCamera code
  64149. var TouchCamera = /** @class */ (function (_super) {
  64150. __extends(TouchCamera, _super);
  64151. //-- end properties for backward compatibility for inputs
  64152. function TouchCamera(name, position, scene) {
  64153. var _this = _super.call(this, name, position, scene) || this;
  64154. _this.inputs.addTouch();
  64155. _this._setupInputs();
  64156. return _this;
  64157. }
  64158. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  64159. //-- Begin properties for backward compatibility for inputs
  64160. get: function () {
  64161. var touch = this.inputs.attached["touch"];
  64162. if (touch)
  64163. return touch.touchAngularSensibility;
  64164. return 0;
  64165. },
  64166. set: function (value) {
  64167. var touch = this.inputs.attached["touch"];
  64168. if (touch)
  64169. touch.touchAngularSensibility = value;
  64170. },
  64171. enumerable: true,
  64172. configurable: true
  64173. });
  64174. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  64175. get: function () {
  64176. var touch = this.inputs.attached["touch"];
  64177. if (touch)
  64178. return touch.touchMoveSensibility;
  64179. return 0;
  64180. },
  64181. set: function (value) {
  64182. var touch = this.inputs.attached["touch"];
  64183. if (touch)
  64184. touch.touchMoveSensibility = value;
  64185. },
  64186. enumerable: true,
  64187. configurable: true
  64188. });
  64189. TouchCamera.prototype.getClassName = function () {
  64190. return "TouchCamera";
  64191. };
  64192. TouchCamera.prototype._setupInputs = function () {
  64193. var mouse = this.inputs.attached["mouse"];
  64194. if (mouse) {
  64195. mouse.touchEnabled = false;
  64196. }
  64197. };
  64198. return TouchCamera;
  64199. }(BABYLON.FreeCamera));
  64200. BABYLON.TouchCamera = TouchCamera;
  64201. })(BABYLON || (BABYLON = {}));
  64202. //# sourceMappingURL=babylon.touchCamera.js.map
  64203. var BABYLON;
  64204. (function (BABYLON) {
  64205. var ProceduralTexture = /** @class */ (function (_super) {
  64206. __extends(ProceduralTexture, _super);
  64207. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  64208. if (fallbackTexture === void 0) { fallbackTexture = null; }
  64209. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64210. if (isCube === void 0) { isCube = false; }
  64211. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  64212. _this.isCube = isCube;
  64213. _this.isEnabled = true;
  64214. _this._currentRefreshId = -1;
  64215. _this._refreshRate = 1;
  64216. _this._vertexBuffers = {};
  64217. _this._uniforms = new Array();
  64218. _this._samplers = new Array();
  64219. _this._textures = {};
  64220. _this._floats = {};
  64221. _this._floatsArrays = {};
  64222. _this._colors3 = {};
  64223. _this._colors4 = {};
  64224. _this._vectors2 = {};
  64225. _this._vectors3 = {};
  64226. _this._matrices = {};
  64227. _this._fallbackTextureUsed = false;
  64228. scene._proceduralTextures.push(_this);
  64229. _this._engine = scene.getEngine();
  64230. _this.name = name;
  64231. _this.isRenderTarget = true;
  64232. _this._size = size;
  64233. _this._generateMipMaps = generateMipMaps;
  64234. _this.setFragment(fragment);
  64235. _this._fallbackTexture = fallbackTexture;
  64236. if (isCube) {
  64237. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  64238. _this.setFloat("face", 0);
  64239. }
  64240. else {
  64241. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  64242. }
  64243. // VBO
  64244. var vertices = [];
  64245. vertices.push(1, 1);
  64246. vertices.push(-1, 1);
  64247. vertices.push(-1, -1);
  64248. vertices.push(1, -1);
  64249. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  64250. _this._createIndexBuffer();
  64251. return _this;
  64252. }
  64253. ProceduralTexture.prototype._createIndexBuffer = function () {
  64254. var engine = this._engine;
  64255. // Indices
  64256. var indices = [];
  64257. indices.push(0);
  64258. indices.push(1);
  64259. indices.push(2);
  64260. indices.push(0);
  64261. indices.push(2);
  64262. indices.push(3);
  64263. this._indexBuffer = engine.createIndexBuffer(indices);
  64264. };
  64265. ProceduralTexture.prototype._rebuild = function () {
  64266. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  64267. if (vb) {
  64268. vb._rebuild();
  64269. }
  64270. this._createIndexBuffer();
  64271. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  64272. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  64273. }
  64274. };
  64275. ProceduralTexture.prototype.reset = function () {
  64276. if (this._effect === undefined) {
  64277. return;
  64278. }
  64279. var engine = this._engine;
  64280. engine._releaseEffect(this._effect);
  64281. };
  64282. ProceduralTexture.prototype.isReady = function () {
  64283. var _this = this;
  64284. var engine = this._engine;
  64285. var shaders;
  64286. if (!this._fragment) {
  64287. return false;
  64288. }
  64289. if (this._fallbackTextureUsed) {
  64290. return true;
  64291. }
  64292. if (this._fragment.fragmentElement !== undefined) {
  64293. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  64294. }
  64295. else {
  64296. shaders = { vertex: "procedural", fragment: this._fragment };
  64297. }
  64298. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  64299. _this.releaseInternalTexture();
  64300. if (_this._fallbackTexture) {
  64301. _this._texture = _this._fallbackTexture._texture;
  64302. if (_this._texture) {
  64303. _this._texture.incrementReferences();
  64304. }
  64305. }
  64306. _this._fallbackTextureUsed = true;
  64307. });
  64308. return this._effect.isReady();
  64309. };
  64310. ProceduralTexture.prototype.resetRefreshCounter = function () {
  64311. this._currentRefreshId = -1;
  64312. };
  64313. ProceduralTexture.prototype.setFragment = function (fragment) {
  64314. this._fragment = fragment;
  64315. };
  64316. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  64317. get: function () {
  64318. return this._refreshRate;
  64319. },
  64320. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  64321. set: function (value) {
  64322. this._refreshRate = value;
  64323. this.resetRefreshCounter();
  64324. },
  64325. enumerable: true,
  64326. configurable: true
  64327. });
  64328. ProceduralTexture.prototype._shouldRender = function () {
  64329. if (!this.isEnabled || !this.isReady() || !this._texture) {
  64330. return false;
  64331. }
  64332. if (this._fallbackTextureUsed) {
  64333. return false;
  64334. }
  64335. if (this._currentRefreshId === -1) {
  64336. this._currentRefreshId = 1;
  64337. return true;
  64338. }
  64339. if (this.refreshRate === this._currentRefreshId) {
  64340. this._currentRefreshId = 1;
  64341. return true;
  64342. }
  64343. this._currentRefreshId++;
  64344. return false;
  64345. };
  64346. ProceduralTexture.prototype.getRenderSize = function () {
  64347. return this._size;
  64348. };
  64349. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  64350. if (this._fallbackTextureUsed) {
  64351. return;
  64352. }
  64353. this.releaseInternalTexture();
  64354. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  64355. };
  64356. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  64357. if (this._uniforms.indexOf(uniformName) === -1) {
  64358. this._uniforms.push(uniformName);
  64359. }
  64360. };
  64361. ProceduralTexture.prototype.setTexture = function (name, texture) {
  64362. if (this._samplers.indexOf(name) === -1) {
  64363. this._samplers.push(name);
  64364. }
  64365. this._textures[name] = texture;
  64366. return this;
  64367. };
  64368. ProceduralTexture.prototype.setFloat = function (name, value) {
  64369. this._checkUniform(name);
  64370. this._floats[name] = value;
  64371. return this;
  64372. };
  64373. ProceduralTexture.prototype.setFloats = function (name, value) {
  64374. this._checkUniform(name);
  64375. this._floatsArrays[name] = value;
  64376. return this;
  64377. };
  64378. ProceduralTexture.prototype.setColor3 = function (name, value) {
  64379. this._checkUniform(name);
  64380. this._colors3[name] = value;
  64381. return this;
  64382. };
  64383. ProceduralTexture.prototype.setColor4 = function (name, value) {
  64384. this._checkUniform(name);
  64385. this._colors4[name] = value;
  64386. return this;
  64387. };
  64388. ProceduralTexture.prototype.setVector2 = function (name, value) {
  64389. this._checkUniform(name);
  64390. this._vectors2[name] = value;
  64391. return this;
  64392. };
  64393. ProceduralTexture.prototype.setVector3 = function (name, value) {
  64394. this._checkUniform(name);
  64395. this._vectors3[name] = value;
  64396. return this;
  64397. };
  64398. ProceduralTexture.prototype.setMatrix = function (name, value) {
  64399. this._checkUniform(name);
  64400. this._matrices[name] = value;
  64401. return this;
  64402. };
  64403. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  64404. var scene = this.getScene();
  64405. if (!scene) {
  64406. return;
  64407. }
  64408. var engine = this._engine;
  64409. // Render
  64410. engine.enableEffect(this._effect);
  64411. engine.setState(false);
  64412. // Texture
  64413. for (var name in this._textures) {
  64414. this._effect.setTexture(name, this._textures[name]);
  64415. }
  64416. // Float
  64417. for (name in this._floats) {
  64418. this._effect.setFloat(name, this._floats[name]);
  64419. }
  64420. // Floats
  64421. for (name in this._floatsArrays) {
  64422. this._effect.setArray(name, this._floatsArrays[name]);
  64423. }
  64424. // Color3
  64425. for (name in this._colors3) {
  64426. this._effect.setColor3(name, this._colors3[name]);
  64427. }
  64428. // Color4
  64429. for (name in this._colors4) {
  64430. var color = this._colors4[name];
  64431. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  64432. }
  64433. // Vector2
  64434. for (name in this._vectors2) {
  64435. this._effect.setVector2(name, this._vectors2[name]);
  64436. }
  64437. // Vector3
  64438. for (name in this._vectors3) {
  64439. this._effect.setVector3(name, this._vectors3[name]);
  64440. }
  64441. // Matrix
  64442. for (name in this._matrices) {
  64443. this._effect.setMatrix(name, this._matrices[name]);
  64444. }
  64445. if (!this._texture) {
  64446. return;
  64447. }
  64448. if (this.isCube) {
  64449. for (var face = 0; face < 6; face++) {
  64450. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  64451. // VBOs
  64452. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  64453. this._effect.setFloat("face", face);
  64454. // Clear
  64455. engine.clear(scene.clearColor, true, true, true);
  64456. // Draw order
  64457. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  64458. // Mipmaps
  64459. if (face === 5) {
  64460. engine.generateMipMapsForCubemap(this._texture);
  64461. }
  64462. }
  64463. }
  64464. else {
  64465. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  64466. // VBOs
  64467. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  64468. // Clear
  64469. engine.clear(scene.clearColor, true, true, true);
  64470. // Draw order
  64471. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  64472. }
  64473. // Unbind
  64474. engine.unBindFramebuffer(this._texture, this.isCube);
  64475. if (this.onGenerated) {
  64476. this.onGenerated();
  64477. }
  64478. };
  64479. ProceduralTexture.prototype.clone = function () {
  64480. var textureSize = this.getSize();
  64481. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  64482. // Base texture
  64483. newTexture.hasAlpha = this.hasAlpha;
  64484. newTexture.level = this.level;
  64485. // RenderTarget Texture
  64486. newTexture.coordinatesMode = this.coordinatesMode;
  64487. return newTexture;
  64488. };
  64489. ProceduralTexture.prototype.dispose = function () {
  64490. var scene = this.getScene();
  64491. if (!scene) {
  64492. return;
  64493. }
  64494. var index = scene._proceduralTextures.indexOf(this);
  64495. if (index >= 0) {
  64496. scene._proceduralTextures.splice(index, 1);
  64497. }
  64498. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  64499. if (vertexBuffer) {
  64500. vertexBuffer.dispose();
  64501. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  64502. }
  64503. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  64504. this._indexBuffer = null;
  64505. }
  64506. _super.prototype.dispose.call(this);
  64507. };
  64508. return ProceduralTexture;
  64509. }(BABYLON.Texture));
  64510. BABYLON.ProceduralTexture = ProceduralTexture;
  64511. })(BABYLON || (BABYLON = {}));
  64512. //# sourceMappingURL=babylon.proceduralTexture.js.map
  64513. var BABYLON;
  64514. (function (BABYLON) {
  64515. var CustomProceduralTexture = /** @class */ (function (_super) {
  64516. __extends(CustomProceduralTexture, _super);
  64517. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  64518. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  64519. _this._animate = true;
  64520. _this._time = 0;
  64521. _this._texturePath = texturePath;
  64522. //Try to load json
  64523. _this.loadJson(texturePath);
  64524. _this.refreshRate = 1;
  64525. return _this;
  64526. }
  64527. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  64528. var _this = this;
  64529. var noConfigFile = function () {
  64530. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  64531. try {
  64532. _this.setFragment(_this._texturePath);
  64533. }
  64534. catch (ex) {
  64535. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  64536. }
  64537. };
  64538. var configFileUrl = jsonUrl + "/config.json";
  64539. var xhr = new XMLHttpRequest();
  64540. xhr.open("GET", configFileUrl, true);
  64541. xhr.addEventListener("load", function () {
  64542. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  64543. try {
  64544. _this._config = JSON.parse(xhr.response);
  64545. _this.updateShaderUniforms();
  64546. _this.updateTextures();
  64547. _this.setFragment(_this._texturePath + "/custom");
  64548. _this._animate = _this._config.animate;
  64549. _this.refreshRate = _this._config.refreshrate;
  64550. }
  64551. catch (ex) {
  64552. noConfigFile();
  64553. }
  64554. }
  64555. else {
  64556. noConfigFile();
  64557. }
  64558. }, false);
  64559. xhr.addEventListener("error", function () {
  64560. noConfigFile();
  64561. }, false);
  64562. try {
  64563. xhr.send();
  64564. }
  64565. catch (ex) {
  64566. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  64567. }
  64568. };
  64569. CustomProceduralTexture.prototype.isReady = function () {
  64570. if (!_super.prototype.isReady.call(this)) {
  64571. return false;
  64572. }
  64573. for (var name in this._textures) {
  64574. var texture = this._textures[name];
  64575. if (!texture.isReady()) {
  64576. return false;
  64577. }
  64578. }
  64579. return true;
  64580. };
  64581. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  64582. var scene = this.getScene();
  64583. if (this._animate && scene) {
  64584. this._time += scene.getAnimationRatio() * 0.03;
  64585. this.updateShaderUniforms();
  64586. }
  64587. _super.prototype.render.call(this, useCameraPostProcess);
  64588. };
  64589. CustomProceduralTexture.prototype.updateTextures = function () {
  64590. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  64591. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  64592. }
  64593. };
  64594. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  64595. if (this._config) {
  64596. for (var j = 0; j < this._config.uniforms.length; j++) {
  64597. var uniform = this._config.uniforms[j];
  64598. switch (uniform.type) {
  64599. case "float":
  64600. this.setFloat(uniform.name, uniform.value);
  64601. break;
  64602. case "color3":
  64603. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  64604. break;
  64605. case "color4":
  64606. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  64607. break;
  64608. case "vector2":
  64609. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  64610. break;
  64611. case "vector3":
  64612. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  64613. break;
  64614. }
  64615. }
  64616. }
  64617. this.setFloat("time", this._time);
  64618. };
  64619. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  64620. get: function () {
  64621. return this._animate;
  64622. },
  64623. set: function (value) {
  64624. this._animate = value;
  64625. },
  64626. enumerable: true,
  64627. configurable: true
  64628. });
  64629. return CustomProceduralTexture;
  64630. }(BABYLON.ProceduralTexture));
  64631. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  64632. })(BABYLON || (BABYLON = {}));
  64633. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  64634. var BABYLON;
  64635. (function (BABYLON) {
  64636. var FreeCameraGamepadInput = /** @class */ (function () {
  64637. function FreeCameraGamepadInput() {
  64638. this.gamepadAngularSensibility = 200;
  64639. this.gamepadMoveSensibility = 40;
  64640. // private members
  64641. this._cameraTransform = BABYLON.Matrix.Identity();
  64642. this._deltaTransform = BABYLON.Vector3.Zero();
  64643. this._vector3 = BABYLON.Vector3.Zero();
  64644. this._vector2 = BABYLON.Vector2.Zero();
  64645. }
  64646. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  64647. var _this = this;
  64648. var manager = this.camera.getScene().gamepadManager;
  64649. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  64650. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  64651. // prioritize XBOX gamepads.
  64652. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  64653. _this.gamepad = gamepad;
  64654. }
  64655. }
  64656. });
  64657. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  64658. if (_this.gamepad === gamepad) {
  64659. _this.gamepad = null;
  64660. }
  64661. });
  64662. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  64663. };
  64664. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  64665. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  64666. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  64667. this.gamepad = null;
  64668. };
  64669. FreeCameraGamepadInput.prototype.checkInputs = function () {
  64670. if (this.gamepad && this.gamepad.leftStick) {
  64671. var camera = this.camera;
  64672. var LSValues = this.gamepad.leftStick;
  64673. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  64674. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  64675. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  64676. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  64677. var RSValues = this.gamepad.rightStick;
  64678. if (RSValues) {
  64679. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  64680. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  64681. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  64682. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  64683. }
  64684. else {
  64685. RSValues = { x: 0, y: 0 };
  64686. }
  64687. if (!camera.rotationQuaternion) {
  64688. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  64689. }
  64690. else {
  64691. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  64692. }
  64693. var speed = camera._computeLocalCameraSpeed() * 50.0;
  64694. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  64695. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  64696. camera.cameraDirection.addInPlace(this._deltaTransform);
  64697. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  64698. camera.cameraRotation.addInPlace(this._vector2);
  64699. }
  64700. };
  64701. FreeCameraGamepadInput.prototype.getClassName = function () {
  64702. return "FreeCameraGamepadInput";
  64703. };
  64704. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  64705. return "gamepad";
  64706. };
  64707. __decorate([
  64708. BABYLON.serialize()
  64709. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  64710. __decorate([
  64711. BABYLON.serialize()
  64712. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  64713. return FreeCameraGamepadInput;
  64714. }());
  64715. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  64716. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  64717. })(BABYLON || (BABYLON = {}));
  64718. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  64719. var BABYLON;
  64720. (function (BABYLON) {
  64721. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  64722. function ArcRotateCameraGamepadInput() {
  64723. this.gamepadRotationSensibility = 80;
  64724. this.gamepadMoveSensibility = 40;
  64725. }
  64726. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  64727. var _this = this;
  64728. var manager = this.camera.getScene().gamepadManager;
  64729. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  64730. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  64731. // prioritize XBOX gamepads.
  64732. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  64733. _this.gamepad = gamepad;
  64734. }
  64735. }
  64736. });
  64737. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  64738. if (_this.gamepad === gamepad) {
  64739. _this.gamepad = null;
  64740. }
  64741. });
  64742. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  64743. };
  64744. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  64745. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  64746. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  64747. this.gamepad = null;
  64748. };
  64749. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  64750. if (this.gamepad) {
  64751. var camera = this.camera;
  64752. var RSValues = this.gamepad.rightStick;
  64753. if (RSValues) {
  64754. if (RSValues.x != 0) {
  64755. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  64756. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  64757. camera.inertialAlphaOffset += normalizedRX;
  64758. }
  64759. }
  64760. if (RSValues.y != 0) {
  64761. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  64762. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  64763. camera.inertialBetaOffset += normalizedRY;
  64764. }
  64765. }
  64766. }
  64767. var LSValues = this.gamepad.leftStick;
  64768. if (LSValues && LSValues.y != 0) {
  64769. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  64770. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  64771. this.camera.inertialRadiusOffset -= normalizedLY;
  64772. }
  64773. }
  64774. }
  64775. };
  64776. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  64777. return "ArcRotateCameraGamepadInput";
  64778. };
  64779. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  64780. return "gamepad";
  64781. };
  64782. __decorate([
  64783. BABYLON.serialize()
  64784. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  64785. __decorate([
  64786. BABYLON.serialize()
  64787. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  64788. return ArcRotateCameraGamepadInput;
  64789. }());
  64790. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  64791. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  64792. })(BABYLON || (BABYLON = {}));
  64793. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  64794. var BABYLON;
  64795. (function (BABYLON) {
  64796. var GamepadManager = /** @class */ (function () {
  64797. function GamepadManager(_scene) {
  64798. var _this = this;
  64799. this._scene = _scene;
  64800. this._babylonGamepads = [];
  64801. this._oneGamepadConnected = false;
  64802. this._isMonitoring = false;
  64803. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  64804. if (!BABYLON.Tools.IsWindowObjectExist()) {
  64805. this._gamepadEventSupported = false;
  64806. }
  64807. else {
  64808. this._gamepadEventSupported = 'GamepadEvent' in window;
  64809. this._gamepadSupport = (navigator.getGamepads ||
  64810. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  64811. }
  64812. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  64813. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  64814. for (var i in _this._babylonGamepads) {
  64815. var gamepad = _this._babylonGamepads[i];
  64816. if (gamepad && gamepad._isConnected) {
  64817. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  64818. }
  64819. }
  64820. });
  64821. this._onGamepadConnectedEvent = function (evt) {
  64822. var gamepad = evt.gamepad;
  64823. if (gamepad.index in _this._babylonGamepads) {
  64824. if (_this._babylonGamepads[gamepad.index].isConnected) {
  64825. return;
  64826. }
  64827. }
  64828. var newGamepad;
  64829. if (_this._babylonGamepads[gamepad.index]) {
  64830. newGamepad = _this._babylonGamepads[gamepad.index];
  64831. newGamepad.browserGamepad = gamepad;
  64832. newGamepad._isConnected = true;
  64833. }
  64834. else {
  64835. newGamepad = _this._addNewGamepad(gamepad);
  64836. }
  64837. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  64838. _this._startMonitoringGamepads();
  64839. };
  64840. this._onGamepadDisconnectedEvent = function (evt) {
  64841. var gamepad = evt.gamepad;
  64842. // Remove the gamepad from the list of gamepads to monitor.
  64843. for (var i in _this._babylonGamepads) {
  64844. if (_this._babylonGamepads[i].index === gamepad.index) {
  64845. var disconnectedGamepad = _this._babylonGamepads[i];
  64846. disconnectedGamepad._isConnected = false;
  64847. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  64848. break;
  64849. }
  64850. }
  64851. };
  64852. if (this._gamepadSupport) {
  64853. //first add already-connected gamepads
  64854. this._updateGamepadObjects();
  64855. if (this._babylonGamepads.length) {
  64856. this._startMonitoringGamepads();
  64857. }
  64858. // Checking if the gamepad connected event is supported (like in Firefox)
  64859. if (this._gamepadEventSupported) {
  64860. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  64861. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  64862. }
  64863. else {
  64864. this._startMonitoringGamepads();
  64865. }
  64866. }
  64867. }
  64868. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  64869. get: function () {
  64870. return this._babylonGamepads;
  64871. },
  64872. enumerable: true,
  64873. configurable: true
  64874. });
  64875. GamepadManager.prototype.getGamepadByType = function (type) {
  64876. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  64877. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  64878. var gamepad = _a[_i];
  64879. if (gamepad && gamepad.type === type) {
  64880. return gamepad;
  64881. }
  64882. }
  64883. return null;
  64884. };
  64885. GamepadManager.prototype.dispose = function () {
  64886. if (this._gamepadEventSupported) {
  64887. if (this._onGamepadConnectedEvent) {
  64888. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  64889. }
  64890. if (this._onGamepadDisconnectedEvent) {
  64891. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  64892. }
  64893. this._onGamepadConnectedEvent = null;
  64894. this._onGamepadDisconnectedEvent = null;
  64895. }
  64896. this._babylonGamepads.forEach(function (gamepad) {
  64897. gamepad.dispose();
  64898. });
  64899. this.onGamepadConnectedObservable.clear();
  64900. this.onGamepadDisconnectedObservable.clear();
  64901. this._oneGamepadConnected = false;
  64902. this._stopMonitoringGamepads();
  64903. this._babylonGamepads = [];
  64904. };
  64905. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  64906. if (!this._oneGamepadConnected) {
  64907. this._oneGamepadConnected = true;
  64908. }
  64909. var newGamepad;
  64910. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  64911. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  64912. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  64913. }
  64914. else if (gamepad.pose) {
  64915. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  64916. }
  64917. else {
  64918. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  64919. }
  64920. this._babylonGamepads[newGamepad.index] = newGamepad;
  64921. return newGamepad;
  64922. };
  64923. GamepadManager.prototype._startMonitoringGamepads = function () {
  64924. if (!this._isMonitoring) {
  64925. this._isMonitoring = true;
  64926. //back-comp
  64927. if (!this._scene) {
  64928. this._checkGamepadsStatus();
  64929. }
  64930. }
  64931. };
  64932. GamepadManager.prototype._stopMonitoringGamepads = function () {
  64933. this._isMonitoring = false;
  64934. };
  64935. GamepadManager.prototype._checkGamepadsStatus = function () {
  64936. var _this = this;
  64937. // Hack to be compatible Chrome
  64938. this._updateGamepadObjects();
  64939. for (var i in this._babylonGamepads) {
  64940. var gamepad = this._babylonGamepads[i];
  64941. if (!gamepad || !gamepad.isConnected) {
  64942. continue;
  64943. }
  64944. gamepad.update();
  64945. }
  64946. if (this._isMonitoring && !this._scene) {
  64947. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  64948. }
  64949. };
  64950. // This function is called only on Chrome, which does not properly support
  64951. // connection/disconnection events and forces you to recopy again the gamepad object
  64952. GamepadManager.prototype._updateGamepadObjects = function () {
  64953. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  64954. for (var i = 0; i < gamepads.length; i++) {
  64955. if (gamepads[i]) {
  64956. if (!this._babylonGamepads[gamepads[i].index]) {
  64957. var newGamepad = this._addNewGamepad(gamepads[i]);
  64958. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  64959. }
  64960. else {
  64961. // Forced to copy again this object for Chrome for unknown reason
  64962. this._babylonGamepads[i].browserGamepad = gamepads[i];
  64963. if (!this._babylonGamepads[i].isConnected) {
  64964. this._babylonGamepads[i]._isConnected = true;
  64965. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  64966. }
  64967. }
  64968. }
  64969. }
  64970. };
  64971. return GamepadManager;
  64972. }());
  64973. BABYLON.GamepadManager = GamepadManager;
  64974. })(BABYLON || (BABYLON = {}));
  64975. //# sourceMappingURL=babylon.gamepadManager.js.map
  64976. var BABYLON;
  64977. (function (BABYLON) {
  64978. var StickValues = /** @class */ (function () {
  64979. function StickValues(x, y) {
  64980. this.x = x;
  64981. this.y = y;
  64982. }
  64983. return StickValues;
  64984. }());
  64985. BABYLON.StickValues = StickValues;
  64986. var Gamepad = /** @class */ (function () {
  64987. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  64988. if (leftStickX === void 0) { leftStickX = 0; }
  64989. if (leftStickY === void 0) { leftStickY = 1; }
  64990. if (rightStickX === void 0) { rightStickX = 2; }
  64991. if (rightStickY === void 0) { rightStickY = 3; }
  64992. this.id = id;
  64993. this.index = index;
  64994. this.browserGamepad = browserGamepad;
  64995. this._isConnected = true;
  64996. this._invertLeftStickY = false;
  64997. this.type = Gamepad.GAMEPAD;
  64998. this._leftStickAxisX = leftStickX;
  64999. this._leftStickAxisY = leftStickY;
  65000. this._rightStickAxisX = rightStickX;
  65001. this._rightStickAxisY = rightStickY;
  65002. if (this.browserGamepad.axes.length >= 2) {
  65003. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  65004. }
  65005. if (this.browserGamepad.axes.length >= 4) {
  65006. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  65007. }
  65008. }
  65009. Object.defineProperty(Gamepad.prototype, "isConnected", {
  65010. get: function () {
  65011. return this._isConnected;
  65012. },
  65013. enumerable: true,
  65014. configurable: true
  65015. });
  65016. Gamepad.prototype.onleftstickchanged = function (callback) {
  65017. this._onleftstickchanged = callback;
  65018. };
  65019. Gamepad.prototype.onrightstickchanged = function (callback) {
  65020. this._onrightstickchanged = callback;
  65021. };
  65022. Object.defineProperty(Gamepad.prototype, "leftStick", {
  65023. get: function () {
  65024. return this._leftStick;
  65025. },
  65026. set: function (newValues) {
  65027. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  65028. this._onleftstickchanged(newValues);
  65029. }
  65030. this._leftStick = newValues;
  65031. },
  65032. enumerable: true,
  65033. configurable: true
  65034. });
  65035. Object.defineProperty(Gamepad.prototype, "rightStick", {
  65036. get: function () {
  65037. return this._rightStick;
  65038. },
  65039. set: function (newValues) {
  65040. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  65041. this._onrightstickchanged(newValues);
  65042. }
  65043. this._rightStick = newValues;
  65044. },
  65045. enumerable: true,
  65046. configurable: true
  65047. });
  65048. Gamepad.prototype.update = function () {
  65049. if (this._leftStick) {
  65050. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  65051. if (this._invertLeftStickY) {
  65052. this.leftStick.y *= -1;
  65053. }
  65054. }
  65055. if (this._rightStick) {
  65056. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  65057. }
  65058. };
  65059. Gamepad.prototype.dispose = function () {
  65060. };
  65061. Gamepad.GAMEPAD = 0;
  65062. Gamepad.GENERIC = 1;
  65063. Gamepad.XBOX = 2;
  65064. Gamepad.POSE_ENABLED = 3;
  65065. return Gamepad;
  65066. }());
  65067. BABYLON.Gamepad = Gamepad;
  65068. var GenericPad = /** @class */ (function (_super) {
  65069. __extends(GenericPad, _super);
  65070. function GenericPad(id, index, browserGamepad) {
  65071. var _this = _super.call(this, id, index, browserGamepad) || this;
  65072. _this.onButtonDownObservable = new BABYLON.Observable();
  65073. _this.onButtonUpObservable = new BABYLON.Observable();
  65074. _this.type = Gamepad.GENERIC;
  65075. _this._buttons = new Array(browserGamepad.buttons.length);
  65076. return _this;
  65077. }
  65078. GenericPad.prototype.onbuttondown = function (callback) {
  65079. this._onbuttondown = callback;
  65080. };
  65081. GenericPad.prototype.onbuttonup = function (callback) {
  65082. this._onbuttonup = callback;
  65083. };
  65084. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  65085. if (newValue !== currentValue) {
  65086. if (newValue === 1) {
  65087. if (this._onbuttondown) {
  65088. this._onbuttondown(buttonIndex);
  65089. }
  65090. this.onButtonDownObservable.notifyObservers(buttonIndex);
  65091. }
  65092. if (newValue === 0) {
  65093. if (this._onbuttonup) {
  65094. this._onbuttonup(buttonIndex);
  65095. }
  65096. this.onButtonUpObservable.notifyObservers(buttonIndex);
  65097. }
  65098. }
  65099. return newValue;
  65100. };
  65101. GenericPad.prototype.update = function () {
  65102. _super.prototype.update.call(this);
  65103. for (var index = 0; index < this._buttons.length; index++) {
  65104. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  65105. }
  65106. };
  65107. GenericPad.prototype.dispose = function () {
  65108. _super.prototype.dispose.call(this);
  65109. this.onButtonDownObservable.clear();
  65110. this.onButtonUpObservable.clear();
  65111. };
  65112. return GenericPad;
  65113. }(Gamepad));
  65114. BABYLON.GenericPad = GenericPad;
  65115. })(BABYLON || (BABYLON = {}));
  65116. //# sourceMappingURL=babylon.gamepad.js.map
  65117. var BABYLON;
  65118. (function (BABYLON) {
  65119. var Xbox360Button;
  65120. (function (Xbox360Button) {
  65121. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  65122. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  65123. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  65124. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  65125. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  65126. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  65127. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  65128. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  65129. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  65130. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  65131. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  65132. var Xbox360Dpad;
  65133. (function (Xbox360Dpad) {
  65134. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  65135. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  65136. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  65137. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  65138. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  65139. var Xbox360Pad = /** @class */ (function (_super) {
  65140. __extends(Xbox360Pad, _super);
  65141. function Xbox360Pad(id, index, gamepad, xboxOne) {
  65142. if (xboxOne === void 0) { xboxOne = false; }
  65143. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  65144. _this._leftTrigger = 0;
  65145. _this._rightTrigger = 0;
  65146. _this.onButtonDownObservable = new BABYLON.Observable();
  65147. _this.onButtonUpObservable = new BABYLON.Observable();
  65148. _this.onPadDownObservable = new BABYLON.Observable();
  65149. _this.onPadUpObservable = new BABYLON.Observable();
  65150. _this._buttonA = 0;
  65151. _this._buttonB = 0;
  65152. _this._buttonX = 0;
  65153. _this._buttonY = 0;
  65154. _this._buttonBack = 0;
  65155. _this._buttonStart = 0;
  65156. _this._buttonLB = 0;
  65157. _this._buttonRB = 0;
  65158. _this._buttonLeftStick = 0;
  65159. _this._buttonRightStick = 0;
  65160. _this._dPadUp = 0;
  65161. _this._dPadDown = 0;
  65162. _this._dPadLeft = 0;
  65163. _this._dPadRight = 0;
  65164. _this._isXboxOnePad = false;
  65165. _this.type = BABYLON.Gamepad.XBOX;
  65166. _this._isXboxOnePad = xboxOne;
  65167. return _this;
  65168. }
  65169. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  65170. this._onlefttriggerchanged = callback;
  65171. };
  65172. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  65173. this._onrighttriggerchanged = callback;
  65174. };
  65175. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  65176. get: function () {
  65177. return this._leftTrigger;
  65178. },
  65179. set: function (newValue) {
  65180. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  65181. this._onlefttriggerchanged(newValue);
  65182. }
  65183. this._leftTrigger = newValue;
  65184. },
  65185. enumerable: true,
  65186. configurable: true
  65187. });
  65188. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  65189. get: function () {
  65190. return this._rightTrigger;
  65191. },
  65192. set: function (newValue) {
  65193. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  65194. this._onrighttriggerchanged(newValue);
  65195. }
  65196. this._rightTrigger = newValue;
  65197. },
  65198. enumerable: true,
  65199. configurable: true
  65200. });
  65201. Xbox360Pad.prototype.onbuttondown = function (callback) {
  65202. this._onbuttondown = callback;
  65203. };
  65204. Xbox360Pad.prototype.onbuttonup = function (callback) {
  65205. this._onbuttonup = callback;
  65206. };
  65207. Xbox360Pad.prototype.ondpaddown = function (callback) {
  65208. this._ondpaddown = callback;
  65209. };
  65210. Xbox360Pad.prototype.ondpadup = function (callback) {
  65211. this._ondpadup = callback;
  65212. };
  65213. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  65214. if (newValue !== currentValue) {
  65215. if (newValue === 1) {
  65216. if (this._onbuttondown) {
  65217. this._onbuttondown(buttonType);
  65218. }
  65219. this.onButtonDownObservable.notifyObservers(buttonType);
  65220. }
  65221. if (newValue === 0) {
  65222. if (this._onbuttonup) {
  65223. this._onbuttonup(buttonType);
  65224. }
  65225. this.onButtonUpObservable.notifyObservers(buttonType);
  65226. }
  65227. }
  65228. return newValue;
  65229. };
  65230. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  65231. if (newValue !== currentValue) {
  65232. if (newValue === 1) {
  65233. if (this._ondpaddown) {
  65234. this._ondpaddown(buttonType);
  65235. }
  65236. this.onPadDownObservable.notifyObservers(buttonType);
  65237. }
  65238. if (newValue === 0) {
  65239. if (this._ondpadup) {
  65240. this._ondpadup(buttonType);
  65241. }
  65242. this.onPadUpObservable.notifyObservers(buttonType);
  65243. }
  65244. }
  65245. return newValue;
  65246. };
  65247. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  65248. get: function () {
  65249. return this._buttonA;
  65250. },
  65251. set: function (value) {
  65252. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  65253. },
  65254. enumerable: true,
  65255. configurable: true
  65256. });
  65257. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  65258. get: function () {
  65259. return this._buttonB;
  65260. },
  65261. set: function (value) {
  65262. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  65263. },
  65264. enumerable: true,
  65265. configurable: true
  65266. });
  65267. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  65268. get: function () {
  65269. return this._buttonX;
  65270. },
  65271. set: function (value) {
  65272. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  65273. },
  65274. enumerable: true,
  65275. configurable: true
  65276. });
  65277. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  65278. get: function () {
  65279. return this._buttonY;
  65280. },
  65281. set: function (value) {
  65282. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  65283. },
  65284. enumerable: true,
  65285. configurable: true
  65286. });
  65287. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  65288. get: function () {
  65289. return this._buttonStart;
  65290. },
  65291. set: function (value) {
  65292. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  65293. },
  65294. enumerable: true,
  65295. configurable: true
  65296. });
  65297. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  65298. get: function () {
  65299. return this._buttonBack;
  65300. },
  65301. set: function (value) {
  65302. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  65303. },
  65304. enumerable: true,
  65305. configurable: true
  65306. });
  65307. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  65308. get: function () {
  65309. return this._buttonLB;
  65310. },
  65311. set: function (value) {
  65312. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  65313. },
  65314. enumerable: true,
  65315. configurable: true
  65316. });
  65317. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  65318. get: function () {
  65319. return this._buttonRB;
  65320. },
  65321. set: function (value) {
  65322. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  65323. },
  65324. enumerable: true,
  65325. configurable: true
  65326. });
  65327. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  65328. get: function () {
  65329. return this._buttonLeftStick;
  65330. },
  65331. set: function (value) {
  65332. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  65333. },
  65334. enumerable: true,
  65335. configurable: true
  65336. });
  65337. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  65338. get: function () {
  65339. return this._buttonRightStick;
  65340. },
  65341. set: function (value) {
  65342. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  65343. },
  65344. enumerable: true,
  65345. configurable: true
  65346. });
  65347. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  65348. get: function () {
  65349. return this._dPadUp;
  65350. },
  65351. set: function (value) {
  65352. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  65353. },
  65354. enumerable: true,
  65355. configurable: true
  65356. });
  65357. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  65358. get: function () {
  65359. return this._dPadDown;
  65360. },
  65361. set: function (value) {
  65362. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  65363. },
  65364. enumerable: true,
  65365. configurable: true
  65366. });
  65367. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  65368. get: function () {
  65369. return this._dPadLeft;
  65370. },
  65371. set: function (value) {
  65372. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  65373. },
  65374. enumerable: true,
  65375. configurable: true
  65376. });
  65377. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  65378. get: function () {
  65379. return this._dPadRight;
  65380. },
  65381. set: function (value) {
  65382. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  65383. },
  65384. enumerable: true,
  65385. configurable: true
  65386. });
  65387. Xbox360Pad.prototype.update = function () {
  65388. _super.prototype.update.call(this);
  65389. if (this._isXboxOnePad) {
  65390. this.buttonA = this.browserGamepad.buttons[0].value;
  65391. this.buttonB = this.browserGamepad.buttons[1].value;
  65392. this.buttonX = this.browserGamepad.buttons[2].value;
  65393. this.buttonY = this.browserGamepad.buttons[3].value;
  65394. this.buttonLB = this.browserGamepad.buttons[4].value;
  65395. this.buttonRB = this.browserGamepad.buttons[5].value;
  65396. this.leftTrigger = this.browserGamepad.axes[2];
  65397. this.rightTrigger = this.browserGamepad.axes[5];
  65398. this.buttonBack = this.browserGamepad.buttons[9].value;
  65399. this.buttonStart = this.browserGamepad.buttons[8].value;
  65400. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  65401. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  65402. this.dPadUp = this.browserGamepad.buttons[11].value;
  65403. this.dPadDown = this.browserGamepad.buttons[12].value;
  65404. this.dPadLeft = this.browserGamepad.buttons[13].value;
  65405. this.dPadRight = this.browserGamepad.buttons[14].value;
  65406. }
  65407. else {
  65408. this.buttonA = this.browserGamepad.buttons[0].value;
  65409. this.buttonB = this.browserGamepad.buttons[1].value;
  65410. this.buttonX = this.browserGamepad.buttons[2].value;
  65411. this.buttonY = this.browserGamepad.buttons[3].value;
  65412. this.buttonLB = this.browserGamepad.buttons[4].value;
  65413. this.buttonRB = this.browserGamepad.buttons[5].value;
  65414. this.leftTrigger = this.browserGamepad.buttons[6].value;
  65415. this.rightTrigger = this.browserGamepad.buttons[7].value;
  65416. this.buttonBack = this.browserGamepad.buttons[8].value;
  65417. this.buttonStart = this.browserGamepad.buttons[9].value;
  65418. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  65419. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  65420. this.dPadUp = this.browserGamepad.buttons[12].value;
  65421. this.dPadDown = this.browserGamepad.buttons[13].value;
  65422. this.dPadLeft = this.browserGamepad.buttons[14].value;
  65423. this.dPadRight = this.browserGamepad.buttons[15].value;
  65424. }
  65425. };
  65426. Xbox360Pad.prototype.dispose = function () {
  65427. _super.prototype.dispose.call(this);
  65428. this.onButtonDownObservable.clear();
  65429. this.onButtonUpObservable.clear();
  65430. this.onPadDownObservable.clear();
  65431. this.onPadUpObservable.clear();
  65432. };
  65433. return Xbox360Pad;
  65434. }(BABYLON.Gamepad));
  65435. BABYLON.Xbox360Pad = Xbox360Pad;
  65436. })(BABYLON || (BABYLON = {}));
  65437. //# sourceMappingURL=babylon.xboxGamepad.js.map
  65438. var BABYLON;
  65439. (function (BABYLON) {
  65440. var PoseEnabledControllerType;
  65441. (function (PoseEnabledControllerType) {
  65442. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  65443. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  65444. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  65445. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  65446. /**
  65447. * Google Daydream
  65448. */
  65449. PoseEnabledControllerType[PoseEnabledControllerType["DAYDREAM"] = 4] = "DAYDREAM";
  65450. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 5] = "GENERIC";
  65451. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  65452. var PoseEnabledControllerHelper = /** @class */ (function () {
  65453. function PoseEnabledControllerHelper() {
  65454. }
  65455. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  65456. // Oculus Touch
  65457. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  65458. return new BABYLON.OculusTouchController(vrGamepad);
  65459. }
  65460. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  65461. return new BABYLON.WindowsMotionController(vrGamepad);
  65462. }
  65463. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  65464. return new BABYLON.ViveController(vrGamepad);
  65465. }
  65466. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0) {
  65467. return new BABYLON.GearVRController(vrGamepad);
  65468. }
  65469. else if (vrGamepad.id.indexOf(BABYLON.DaydreamController.GAMEPAD_ID_PREFIX) === 0) {
  65470. return new BABYLON.DaydreamController(vrGamepad);
  65471. }
  65472. else {
  65473. return new BABYLON.GenericController(vrGamepad);
  65474. }
  65475. };
  65476. return PoseEnabledControllerHelper;
  65477. }());
  65478. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  65479. var PoseEnabledController = /** @class */ (function (_super) {
  65480. __extends(PoseEnabledController, _super);
  65481. function PoseEnabledController(browserGamepad) {
  65482. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  65483. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  65484. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  65485. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  65486. // Represents device position and rotation in babylon space
  65487. _this.devicePosition = BABYLON.Vector3.Zero();
  65488. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  65489. _this.deviceScaleFactor = 1;
  65490. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  65491. _this._deviceToWorld = BABYLON.Matrix.Identity();
  65492. /**
  65493. * Node to be used when casting a ray from the controller
  65494. */
  65495. _this._pointingPoseNode = null;
  65496. _this._workingMatrix = BABYLON.Matrix.Identity();
  65497. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  65498. _this.controllerType = PoseEnabledControllerType.GENERIC;
  65499. _this.position = BABYLON.Vector3.Zero();
  65500. _this.rotationQuaternion = new BABYLON.Quaternion();
  65501. _this._calculatedPosition = BABYLON.Vector3.Zero();
  65502. _this._calculatedRotation = new BABYLON.Quaternion();
  65503. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  65504. return _this;
  65505. }
  65506. PoseEnabledController.prototype.update = function () {
  65507. _super.prototype.update.call(this);
  65508. var pose = this.browserGamepad.pose;
  65509. this.updateFromDevice(pose);
  65510. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  65511. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  65512. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  65513. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  65514. if (this._mesh) {
  65515. this._mesh.position.copyFrom(this.devicePosition);
  65516. if (this._mesh.rotationQuaternion) {
  65517. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  65518. }
  65519. }
  65520. };
  65521. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  65522. if (poseData) {
  65523. this.rawPose = poseData;
  65524. if (poseData.position) {
  65525. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  65526. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  65527. this._deviceRoomPosition.z *= -1;
  65528. }
  65529. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  65530. this._calculatedPosition.addInPlace(this.position);
  65531. }
  65532. var pose = this.rawPose;
  65533. if (poseData.orientation && pose.orientation) {
  65534. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  65535. if (this._mesh) {
  65536. if (this._mesh.getScene().useRightHandedSystem) {
  65537. this._deviceRoomRotationQuaternion.z *= -1;
  65538. this._deviceRoomRotationQuaternion.w *= -1;
  65539. }
  65540. else {
  65541. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  65542. }
  65543. }
  65544. // if the camera is set, rotate to the camera's rotation
  65545. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  65546. }
  65547. }
  65548. };
  65549. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  65550. if (this._mesh) {
  65551. this._mesh.parent = null;
  65552. }
  65553. this._mesh = mesh;
  65554. if (this._poseControlledCamera) {
  65555. this._mesh.parent = this._poseControlledCamera;
  65556. }
  65557. if (!this._mesh.rotationQuaternion) {
  65558. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  65559. }
  65560. };
  65561. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  65562. this._poseControlledCamera = camera;
  65563. if (this._mesh) {
  65564. this._mesh.parent = this._poseControlledCamera;
  65565. }
  65566. };
  65567. PoseEnabledController.prototype.dispose = function () {
  65568. if (this._mesh) {
  65569. this._mesh.dispose();
  65570. }
  65571. this._mesh = null;
  65572. _super.prototype.dispose.call(this);
  65573. };
  65574. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  65575. get: function () {
  65576. return this._mesh;
  65577. },
  65578. enumerable: true,
  65579. configurable: true
  65580. });
  65581. PoseEnabledController.prototype.getForwardRay = function (length) {
  65582. if (length === void 0) { length = 100; }
  65583. if (!this.mesh) {
  65584. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  65585. }
  65586. var m = this._pointingPoseNode ? this._pointingPoseNode.getWorldMatrix() : this.mesh.getWorldMatrix();
  65587. var origin = m.getTranslation();
  65588. var forward = new BABYLON.Vector3(0, 0, -1);
  65589. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  65590. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  65591. return new BABYLON.Ray(origin, direction, length);
  65592. };
  65593. /**
  65594. * Name of the child mesh that can be used to cast a ray from the controller
  65595. */
  65596. PoseEnabledController.POINTING_POSE = "POINTING_POSE";
  65597. return PoseEnabledController;
  65598. }(BABYLON.Gamepad));
  65599. BABYLON.PoseEnabledController = PoseEnabledController;
  65600. })(BABYLON || (BABYLON = {}));
  65601. //# sourceMappingURL=babylon.poseEnabledController.js.map
  65602. var BABYLON;
  65603. (function (BABYLON) {
  65604. var WebVRController = /** @class */ (function (_super) {
  65605. __extends(WebVRController, _super);
  65606. function WebVRController(vrGamepad) {
  65607. var _this = _super.call(this, vrGamepad) || this;
  65608. // Observables
  65609. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  65610. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  65611. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  65612. _this.onPadStateChangedObservable = new BABYLON.Observable();
  65613. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  65614. _this.pad = { x: 0, y: 0 };
  65615. // avoid GC, store state in a tmp object
  65616. _this._changes = {
  65617. pressChanged: false,
  65618. touchChanged: false,
  65619. valueChanged: false,
  65620. changed: false
  65621. };
  65622. _this._buttons = new Array(vrGamepad.buttons.length);
  65623. _this.hand = vrGamepad.hand;
  65624. return _this;
  65625. }
  65626. WebVRController.prototype.onButtonStateChange = function (callback) {
  65627. this._onButtonStateChange = callback;
  65628. };
  65629. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  65630. get: function () {
  65631. return this._defaultModel;
  65632. },
  65633. enumerable: true,
  65634. configurable: true
  65635. });
  65636. WebVRController.prototype.update = function () {
  65637. _super.prototype.update.call(this);
  65638. for (var index = 0; index < this._buttons.length; index++) {
  65639. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  65640. }
  65641. ;
  65642. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  65643. this.pad.x = this.leftStick.x;
  65644. this.pad.y = this.leftStick.y;
  65645. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  65646. }
  65647. };
  65648. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  65649. if (!newState) {
  65650. newState = {
  65651. pressed: false,
  65652. touched: false,
  65653. value: 0
  65654. };
  65655. }
  65656. if (!currentState) {
  65657. this._buttons[buttonIndex] = {
  65658. pressed: newState.pressed,
  65659. touched: newState.touched,
  65660. value: newState.value
  65661. };
  65662. return;
  65663. }
  65664. this._checkChanges(newState, currentState);
  65665. if (this._changes.changed) {
  65666. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  65667. this._handleButtonChange(buttonIndex, newState, this._changes);
  65668. }
  65669. this._buttons[buttonIndex].pressed = newState.pressed;
  65670. this._buttons[buttonIndex].touched = newState.touched;
  65671. // oculus triggers are never 0, thou not touched.
  65672. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  65673. };
  65674. WebVRController.prototype._checkChanges = function (newState, currentState) {
  65675. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  65676. this._changes.touchChanged = newState.touched !== currentState.touched;
  65677. this._changes.valueChanged = newState.value !== currentState.value;
  65678. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  65679. return this._changes;
  65680. };
  65681. WebVRController.prototype.dispose = function () {
  65682. _super.prototype.dispose.call(this);
  65683. this.onTriggerStateChangedObservable.clear();
  65684. this.onMainButtonStateChangedObservable.clear();
  65685. this.onSecondaryButtonStateChangedObservable.clear();
  65686. this.onPadStateChangedObservable.clear();
  65687. this.onPadValuesChangedObservable.clear();
  65688. };
  65689. return WebVRController;
  65690. }(BABYLON.PoseEnabledController));
  65691. BABYLON.WebVRController = WebVRController;
  65692. })(BABYLON || (BABYLON = {}));
  65693. //# sourceMappingURL=babylon.webVRController.js.map
  65694. var BABYLON;
  65695. (function (BABYLON) {
  65696. var OculusTouchController = /** @class */ (function (_super) {
  65697. __extends(OculusTouchController, _super);
  65698. function OculusTouchController(vrGamepad) {
  65699. var _this = _super.call(this, vrGamepad) || this;
  65700. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  65701. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  65702. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  65703. return _this;
  65704. }
  65705. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  65706. var _this = this;
  65707. var meshName;
  65708. // Hand
  65709. if (this.hand === 'left') {
  65710. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  65711. }
  65712. else {
  65713. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  65714. }
  65715. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  65716. /*
  65717. Parent Mesh name: oculus_touch_left
  65718. - body
  65719. - trigger
  65720. - thumbstick
  65721. - grip
  65722. - button_y
  65723. - button_x
  65724. - button_enter
  65725. */
  65726. _this._defaultModel = newMeshes[1];
  65727. _this.attachToMesh(_this._defaultModel);
  65728. if (meshLoaded) {
  65729. meshLoaded(_this._defaultModel);
  65730. }
  65731. });
  65732. };
  65733. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  65734. // helper getters for left and right hand.
  65735. get: function () {
  65736. if (this.hand === 'right') {
  65737. return this.onMainButtonStateChangedObservable;
  65738. }
  65739. else {
  65740. throw new Error('No A button on left hand');
  65741. }
  65742. },
  65743. enumerable: true,
  65744. configurable: true
  65745. });
  65746. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  65747. get: function () {
  65748. if (this.hand === 'right') {
  65749. return this.onSecondaryButtonStateChangedObservable;
  65750. }
  65751. else {
  65752. throw new Error('No B button on left hand');
  65753. }
  65754. },
  65755. enumerable: true,
  65756. configurable: true
  65757. });
  65758. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  65759. get: function () {
  65760. if (this.hand === 'left') {
  65761. return this.onMainButtonStateChangedObservable;
  65762. }
  65763. else {
  65764. throw new Error('No X button on right hand');
  65765. }
  65766. },
  65767. enumerable: true,
  65768. configurable: true
  65769. });
  65770. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  65771. get: function () {
  65772. if (this.hand === 'left') {
  65773. return this.onSecondaryButtonStateChangedObservable;
  65774. }
  65775. else {
  65776. throw new Error('No Y button on right hand');
  65777. }
  65778. },
  65779. enumerable: true,
  65780. configurable: true
  65781. });
  65782. /*
  65783. 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  65784. 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  65785. 2) secondary trigger (same)
  65786. 3) A (right) X (left), touch, pressed = value
  65787. 4) B / Y
  65788. 5) thumb rest
  65789. */
  65790. OculusTouchController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  65791. var notifyObject = state; //{ state: state, changes: changes };
  65792. var triggerDirection = this.hand === 'right' ? -1 : 1;
  65793. switch (buttonIdx) {
  65794. case 0:
  65795. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  65796. return;
  65797. case 1:// index trigger
  65798. if (this._defaultModel) {
  65799. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  65800. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  65801. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  65802. }
  65803. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  65804. return;
  65805. case 2:// secondary trigger
  65806. if (this._defaultModel) {
  65807. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  65808. }
  65809. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  65810. return;
  65811. case 3:
  65812. if (this._defaultModel) {
  65813. if (notifyObject.pressed) {
  65814. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  65815. }
  65816. else {
  65817. (this._defaultModel.getChildren()[1]).position.y = 0;
  65818. }
  65819. }
  65820. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  65821. return;
  65822. case 4:
  65823. if (this._defaultModel) {
  65824. if (notifyObject.pressed) {
  65825. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  65826. }
  65827. else {
  65828. (this._defaultModel.getChildren()[2]).position.y = 0;
  65829. }
  65830. }
  65831. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  65832. return;
  65833. case 5:
  65834. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  65835. return;
  65836. }
  65837. };
  65838. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  65839. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  65840. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  65841. return OculusTouchController;
  65842. }(BABYLON.WebVRController));
  65843. BABYLON.OculusTouchController = OculusTouchController;
  65844. })(BABYLON || (BABYLON = {}));
  65845. //# sourceMappingURL=babylon.oculusTouchController.js.map
  65846. var BABYLON;
  65847. (function (BABYLON) {
  65848. var ViveController = /** @class */ (function (_super) {
  65849. __extends(ViveController, _super);
  65850. function ViveController(vrGamepad) {
  65851. var _this = _super.call(this, vrGamepad) || this;
  65852. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  65853. _this._invertLeftStickY = true;
  65854. return _this;
  65855. }
  65856. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  65857. var _this = this;
  65858. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  65859. /*
  65860. Parent Mesh name: ViveWand
  65861. - body
  65862. - r_gripper
  65863. - l_gripper
  65864. - menu_button
  65865. - system_button
  65866. - trackpad
  65867. - trigger
  65868. - LED
  65869. */
  65870. _this._defaultModel = newMeshes[1];
  65871. _this.attachToMesh(_this._defaultModel);
  65872. if (meshLoaded) {
  65873. meshLoaded(_this._defaultModel);
  65874. }
  65875. });
  65876. };
  65877. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  65878. get: function () {
  65879. return this.onMainButtonStateChangedObservable;
  65880. },
  65881. enumerable: true,
  65882. configurable: true
  65883. });
  65884. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  65885. get: function () {
  65886. return this.onMainButtonStateChangedObservable;
  65887. },
  65888. enumerable: true,
  65889. configurable: true
  65890. });
  65891. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  65892. get: function () {
  65893. return this.onSecondaryButtonStateChangedObservable;
  65894. },
  65895. enumerable: true,
  65896. configurable: true
  65897. });
  65898. /**
  65899. * Vive mapping:
  65900. * 0: touchpad
  65901. * 1: trigger
  65902. * 2: left AND right buttons
  65903. * 3: menu button
  65904. */
  65905. ViveController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  65906. var notifyObject = state; //{ state: state, changes: changes };
  65907. switch (buttonIdx) {
  65908. case 0:
  65909. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  65910. return;
  65911. case 1:// index trigger
  65912. if (this._defaultModel) {
  65913. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  65914. }
  65915. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  65916. return;
  65917. case 2:// left AND right button
  65918. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  65919. return;
  65920. case 3:
  65921. if (this._defaultModel) {
  65922. if (notifyObject.pressed) {
  65923. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  65924. }
  65925. else {
  65926. (this._defaultModel.getChildren()[2]).position.y = 0;
  65927. }
  65928. }
  65929. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  65930. return;
  65931. }
  65932. };
  65933. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  65934. ViveController.MODEL_FILENAME = 'wand.babylon';
  65935. return ViveController;
  65936. }(BABYLON.WebVRController));
  65937. BABYLON.ViveController = ViveController;
  65938. })(BABYLON || (BABYLON = {}));
  65939. //# sourceMappingURL=babylon.viveController.js.map
  65940. var BABYLON;
  65941. (function (BABYLON) {
  65942. var GenericController = /** @class */ (function (_super) {
  65943. __extends(GenericController, _super);
  65944. function GenericController(vrGamepad) {
  65945. return _super.call(this, vrGamepad) || this;
  65946. }
  65947. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  65948. var _this = this;
  65949. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  65950. _this._defaultModel = newMeshes[1];
  65951. _this.attachToMesh(_this._defaultModel);
  65952. if (meshLoaded) {
  65953. meshLoaded(_this._defaultModel);
  65954. }
  65955. });
  65956. };
  65957. GenericController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  65958. console.log("Button id: " + buttonIdx + "state: ");
  65959. console.dir(state);
  65960. };
  65961. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  65962. GenericController.MODEL_FILENAME = 'generic.babylon';
  65963. return GenericController;
  65964. }(BABYLON.WebVRController));
  65965. BABYLON.GenericController = GenericController;
  65966. })(BABYLON || (BABYLON = {}));
  65967. //# sourceMappingURL=babylon.genericController.js.map
  65968. var BABYLON;
  65969. (function (BABYLON) {
  65970. var LoadedMeshInfo = /** @class */ (function () {
  65971. function LoadedMeshInfo() {
  65972. this.buttonMeshes = {};
  65973. this.axisMeshes = {};
  65974. }
  65975. return LoadedMeshInfo;
  65976. }());
  65977. var WindowsMotionController = /** @class */ (function (_super) {
  65978. __extends(WindowsMotionController, _super);
  65979. function WindowsMotionController(vrGamepad) {
  65980. var _this = _super.call(this, vrGamepad) || this;
  65981. _this._mapping = {
  65982. // Semantic button names
  65983. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  65984. // A mapping of the button name to glTF model node name
  65985. // that should be transformed by button value.
  65986. buttonMeshNames: {
  65987. 'trigger': 'SELECT',
  65988. 'menu': 'MENU',
  65989. 'grip': 'GRASP',
  65990. 'thumbstick': 'THUMBSTICK_PRESS',
  65991. 'trackpad': 'TOUCHPAD_PRESS'
  65992. },
  65993. // This mapping is used to translate from the Motion Controller to Babylon semantics
  65994. buttonObservableNames: {
  65995. 'trigger': 'onTriggerStateChangedObservable',
  65996. 'menu': 'onSecondaryButtonStateChangedObservable',
  65997. 'grip': 'onMainButtonStateChangedObservable',
  65998. 'thumbstick': 'onPadStateChangedObservable',
  65999. 'trackpad': 'onTrackpadChangedObservable'
  66000. },
  66001. // A mapping of the axis name to glTF model node name
  66002. // that should be transformed by axis value.
  66003. // This array mirrors the browserGamepad.axes array, such that
  66004. // the mesh corresponding to axis 0 is in this array index 0.
  66005. axisMeshNames: [
  66006. 'THUMBSTICK_X',
  66007. 'THUMBSTICK_Y',
  66008. 'TOUCHPAD_TOUCH_X',
  66009. 'TOUCHPAD_TOUCH_Y'
  66010. ],
  66011. pointingPoseMeshName: BABYLON.PoseEnabledController.POINTING_POSE
  66012. };
  66013. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  66014. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  66015. _this.trackpad = { x: 0, y: 0 };
  66016. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  66017. _this._loadedMeshInfo = null;
  66018. return _this;
  66019. }
  66020. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  66021. get: function () {
  66022. return this.onTriggerStateChangedObservable;
  66023. },
  66024. enumerable: true,
  66025. configurable: true
  66026. });
  66027. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  66028. get: function () {
  66029. return this.onSecondaryButtonStateChangedObservable;
  66030. },
  66031. enumerable: true,
  66032. configurable: true
  66033. });
  66034. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  66035. get: function () {
  66036. return this.onMainButtonStateChangedObservable;
  66037. },
  66038. enumerable: true,
  66039. configurable: true
  66040. });
  66041. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  66042. get: function () {
  66043. return this.onPadStateChangedObservable;
  66044. },
  66045. enumerable: true,
  66046. configurable: true
  66047. });
  66048. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  66049. get: function () {
  66050. return this.onTrackpadChangedObservable;
  66051. },
  66052. enumerable: true,
  66053. configurable: true
  66054. });
  66055. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  66056. get: function () {
  66057. return this.onTrackpadValuesChangedObservable;
  66058. },
  66059. enumerable: true,
  66060. configurable: true
  66061. });
  66062. /**
  66063. * Called once per frame by the engine.
  66064. */
  66065. WindowsMotionController.prototype.update = function () {
  66066. _super.prototype.update.call(this);
  66067. if (this.browserGamepad.axes) {
  66068. if (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y) {
  66069. this.trackpad.x = this.browserGamepad["axes"][2];
  66070. this.trackpad.y = this.browserGamepad["axes"][3];
  66071. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  66072. }
  66073. // Only need to animate axes if there is a loaded mesh
  66074. if (this._loadedMeshInfo) {
  66075. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  66076. this.lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  66077. }
  66078. }
  66079. }
  66080. };
  66081. /**
  66082. * Called once for each button that changed state since the last frame
  66083. * @param buttonIdx Which button index changed
  66084. * @param state New state of the button
  66085. * @param changes Which properties on the state changed since last frame
  66086. */
  66087. WindowsMotionController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  66088. var buttonName = this._mapping.buttons[buttonIdx];
  66089. if (!buttonName) {
  66090. return;
  66091. }
  66092. // Only emit events for buttons that we know how to map from index to name
  66093. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  66094. if (observable) {
  66095. observable.notifyObservers(state);
  66096. }
  66097. this.lerpButtonTransform(buttonName, state.value);
  66098. };
  66099. WindowsMotionController.prototype.lerpButtonTransform = function (buttonName, buttonValue) {
  66100. // If there is no loaded mesh, there is nothing to transform.
  66101. if (!this._loadedMeshInfo) {
  66102. return;
  66103. }
  66104. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  66105. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  66106. return;
  66107. }
  66108. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  66109. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  66110. };
  66111. WindowsMotionController.prototype.lerpAxisTransform = function (axis, axisValue) {
  66112. if (!this._loadedMeshInfo) {
  66113. return;
  66114. }
  66115. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  66116. if (!meshInfo) {
  66117. return;
  66118. }
  66119. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  66120. return;
  66121. }
  66122. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  66123. var lerpValue = axisValue * 0.5 + 0.5;
  66124. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  66125. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  66126. };
  66127. /**
  66128. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  66129. * @param scene scene in which to add meshes
  66130. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  66131. */
  66132. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  66133. var _this = this;
  66134. if (forceDefault === void 0) { forceDefault = false; }
  66135. var path;
  66136. var filename;
  66137. // Checking if GLB loader is present
  66138. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  66139. // Determine the device specific folder based on the ID suffix
  66140. var device = 'default';
  66141. if (this.id && !forceDefault) {
  66142. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  66143. device = ((match && match[0]) || device);
  66144. }
  66145. // Hand
  66146. if (this.hand === 'left') {
  66147. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  66148. }
  66149. else {
  66150. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  66151. }
  66152. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  66153. }
  66154. else {
  66155. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  66156. path = BABYLON.GenericController.MODEL_BASE_URL;
  66157. filename = BABYLON.GenericController.MODEL_FILENAME;
  66158. }
  66159. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  66160. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  66161. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  66162. if (!_this._loadedMeshInfo) {
  66163. return;
  66164. }
  66165. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  66166. _this.attachToMesh(_this._defaultModel);
  66167. if (meshLoaded) {
  66168. meshLoaded(_this._defaultModel);
  66169. }
  66170. }, null, function (scene, message) {
  66171. BABYLON.Tools.Log(message);
  66172. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  66173. if (!forceDefault) {
  66174. _this.initControllerMesh(scene, meshLoaded, true);
  66175. }
  66176. });
  66177. };
  66178. /**
  66179. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  66180. * can be transformed by button presses and axes values, based on this._mapping.
  66181. *
  66182. * @param scene scene in which the meshes exist
  66183. * @param meshes list of meshes that make up the controller model to process
  66184. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  66185. */
  66186. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  66187. var loadedMeshInfo = null;
  66188. // Create a new mesh to contain the glTF hierarchy
  66189. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  66190. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  66191. var childMesh = null;
  66192. for (var i = 0; i < meshes.length; i++) {
  66193. var mesh = meshes[i];
  66194. if (!mesh.parent) {
  66195. // Exclude controller meshes from picking results
  66196. mesh.isPickable = false;
  66197. // Handle root node, attach to the new parentMesh
  66198. childMesh = mesh;
  66199. break;
  66200. }
  66201. }
  66202. if (childMesh) {
  66203. childMesh.setParent(parentMesh);
  66204. // Create our mesh info. Note that this method will always return non-null.
  66205. loadedMeshInfo = this.createMeshInfo(parentMesh);
  66206. }
  66207. else {
  66208. BABYLON.Tools.Warn('Could not find root node in model file.');
  66209. }
  66210. return loadedMeshInfo;
  66211. };
  66212. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  66213. var loadedMeshInfo = new LoadedMeshInfo();
  66214. var i;
  66215. loadedMeshInfo.rootNode = rootNode;
  66216. // Reset the caches
  66217. loadedMeshInfo.buttonMeshes = {};
  66218. loadedMeshInfo.axisMeshes = {};
  66219. // Button Meshes
  66220. for (i = 0; i < this._mapping.buttons.length; i++) {
  66221. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  66222. if (!buttonMeshName) {
  66223. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  66224. continue;
  66225. }
  66226. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  66227. if (!buttonMesh) {
  66228. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  66229. continue;
  66230. }
  66231. var buttonMeshInfo = {
  66232. index: i,
  66233. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  66234. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  66235. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  66236. };
  66237. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  66238. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  66239. }
  66240. else {
  66241. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  66242. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  66243. '(VALUE: ' + !!buttonMeshInfo.value +
  66244. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  66245. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  66246. ')');
  66247. }
  66248. }
  66249. // Axis Meshes
  66250. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  66251. var axisMeshName = this._mapping.axisMeshNames[i];
  66252. if (!axisMeshName) {
  66253. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  66254. continue;
  66255. }
  66256. var axisMesh = getChildByName(rootNode, axisMeshName);
  66257. if (!axisMesh) {
  66258. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  66259. continue;
  66260. }
  66261. var axisMeshInfo = {
  66262. index: i,
  66263. value: getImmediateChildByName(axisMesh, 'VALUE'),
  66264. min: getImmediateChildByName(axisMesh, 'MIN'),
  66265. max: getImmediateChildByName(axisMesh, 'MAX')
  66266. };
  66267. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  66268. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  66269. }
  66270. else {
  66271. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  66272. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  66273. '(VALUE: ' + !!axisMeshInfo.value +
  66274. ', MIN: ' + !!axisMeshInfo.min +
  66275. ', MAX:' + !!axisMeshInfo.max +
  66276. ')');
  66277. }
  66278. }
  66279. // Pointing Ray
  66280. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  66281. if (!loadedMeshInfo.pointingPoseNode) {
  66282. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  66283. }
  66284. return loadedMeshInfo;
  66285. // Look through all children recursively. This will return null if no mesh exists with the given name.
  66286. function getChildByName(node, name) {
  66287. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  66288. }
  66289. // Look through only immediate children. This will return null if no mesh exists with the given name.
  66290. function getImmediateChildByName(node, name) {
  66291. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  66292. }
  66293. };
  66294. WindowsMotionController.prototype.getForwardRay = function (length) {
  66295. if (length === void 0) { length = 100; }
  66296. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  66297. return _super.prototype.getForwardRay.call(this, length);
  66298. }
  66299. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  66300. var origin = m.getTranslation();
  66301. var forward = new BABYLON.Vector3(0, 0, -1);
  66302. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  66303. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  66304. return new BABYLON.Ray(origin, direction, length);
  66305. };
  66306. WindowsMotionController.prototype.dispose = function () {
  66307. _super.prototype.dispose.call(this);
  66308. this.onTrackpadChangedObservable.clear();
  66309. };
  66310. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  66311. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  66312. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  66313. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  66314. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  66315. return WindowsMotionController;
  66316. }(BABYLON.WebVRController));
  66317. BABYLON.WindowsMotionController = WindowsMotionController;
  66318. })(BABYLON || (BABYLON = {}));
  66319. //# sourceMappingURL=babylon.windowsMotionController.js.map
  66320. var BABYLON;
  66321. (function (BABYLON) {
  66322. var GearVRController = /** @class */ (function (_super) {
  66323. __extends(GearVRController, _super);
  66324. function GearVRController(vrGamepad) {
  66325. var _this = _super.call(this, vrGamepad) || this;
  66326. _this._buttonIndexToObservableNameMap = [
  66327. 'onTrackpadChangedObservable',
  66328. 'onTriggerStateChangedObservable' // Trigger
  66329. ];
  66330. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  66331. return _this;
  66332. }
  66333. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  66334. var _this = this;
  66335. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  66336. _this._defaultModel = newMeshes[1];
  66337. _this.attachToMesh(_this._defaultModel);
  66338. if (meshLoaded) {
  66339. meshLoaded(_this._defaultModel);
  66340. }
  66341. });
  66342. };
  66343. GearVRController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  66344. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  66345. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  66346. // Only emit events for buttons that we know how to map from index to observable
  66347. var observable = this[observableName];
  66348. if (observable) {
  66349. observable.notifyObservers(state);
  66350. }
  66351. }
  66352. };
  66353. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  66354. GearVRController.MODEL_FILENAME = 'generic.babylon';
  66355. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  66356. return GearVRController;
  66357. }(BABYLON.WebVRController));
  66358. BABYLON.GearVRController = GearVRController;
  66359. })(BABYLON || (BABYLON = {}));
  66360. //# sourceMappingURL=babylon.gearVRController.js.map
  66361. var BABYLON;
  66362. (function (BABYLON) {
  66363. /**
  66364. * Google Daydream controller
  66365. */
  66366. var DaydreamController = /** @class */ (function (_super) {
  66367. __extends(DaydreamController, _super);
  66368. function DaydreamController(vrGamepad) {
  66369. var _this = _super.call(this, vrGamepad) || this;
  66370. _this.controllerType = BABYLON.PoseEnabledControllerType.DAYDREAM;
  66371. return _this;
  66372. }
  66373. DaydreamController.prototype.initControllerMesh = function (scene, meshLoaded) {
  66374. var _this = this;
  66375. BABYLON.SceneLoader.ImportMesh("", DaydreamController.MODEL_BASE_URL, DaydreamController.MODEL_FILENAME, scene, function (newMeshes) {
  66376. _this._defaultModel = newMeshes[1];
  66377. _this.attachToMesh(_this._defaultModel);
  66378. if (meshLoaded) {
  66379. meshLoaded(_this._defaultModel);
  66380. }
  66381. });
  66382. };
  66383. DaydreamController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  66384. // Daydream controller only has 1 GamepadButton (on the trackpad).
  66385. if (buttonIdx === 0) {
  66386. var observable = this.onTriggerStateChangedObservable;
  66387. if (observable) {
  66388. observable.notifyObservers(state);
  66389. }
  66390. }
  66391. else {
  66392. // If the app or home buttons are ever made available
  66393. BABYLON.Tools.Warn("Unrecognized Daydream button index: " + buttonIdx);
  66394. }
  66395. };
  66396. /**
  66397. * Base Url for the controller model.
  66398. */
  66399. DaydreamController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  66400. /**
  66401. * File name for the controller model.
  66402. */
  66403. DaydreamController.MODEL_FILENAME = 'generic.babylon';
  66404. /**
  66405. * Gamepad Id prefix used to identify Daydream Controller.
  66406. */
  66407. DaydreamController.GAMEPAD_ID_PREFIX = 'Daydream'; // id is 'Daydream Controller'
  66408. return DaydreamController;
  66409. }(BABYLON.WebVRController));
  66410. BABYLON.DaydreamController = DaydreamController;
  66411. })(BABYLON || (BABYLON = {}));
  66412. //# sourceMappingURL=babylon.daydreamController.js.map
  66413. var BABYLON;
  66414. (function (BABYLON) {
  66415. var FollowCamera = /** @class */ (function (_super) {
  66416. __extends(FollowCamera, _super);
  66417. function FollowCamera(name, position, scene, lockedTarget) {
  66418. if (lockedTarget === void 0) { lockedTarget = null; }
  66419. var _this = _super.call(this, name, position, scene) || this;
  66420. _this.radius = 12;
  66421. _this.rotationOffset = 0;
  66422. _this.heightOffset = 4;
  66423. _this.cameraAcceleration = 0.05;
  66424. _this.maxCameraSpeed = 20;
  66425. _this.lockedTarget = lockedTarget;
  66426. return _this;
  66427. }
  66428. FollowCamera.prototype.getRadians = function (degrees) {
  66429. return degrees * Math.PI / 180;
  66430. };
  66431. FollowCamera.prototype.follow = function (cameraTarget) {
  66432. if (!cameraTarget)
  66433. return;
  66434. var yRotation;
  66435. if (cameraTarget.rotationQuaternion) {
  66436. var rotMatrix = new BABYLON.Matrix();
  66437. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  66438. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  66439. }
  66440. else {
  66441. yRotation = cameraTarget.rotation.y;
  66442. }
  66443. var radians = this.getRadians(this.rotationOffset) + yRotation;
  66444. var targetPosition = cameraTarget.getAbsolutePosition();
  66445. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  66446. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  66447. var dx = targetX - this.position.x;
  66448. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  66449. var dz = (targetZ) - this.position.z;
  66450. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  66451. var vy = dy * this.cameraAcceleration;
  66452. var vz = dz * this.cameraAcceleration * 2;
  66453. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  66454. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  66455. }
  66456. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  66457. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  66458. }
  66459. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  66460. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  66461. }
  66462. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  66463. this.setTarget(targetPosition);
  66464. };
  66465. FollowCamera.prototype._checkInputs = function () {
  66466. _super.prototype._checkInputs.call(this);
  66467. if (this.lockedTarget) {
  66468. this.follow(this.lockedTarget);
  66469. }
  66470. };
  66471. FollowCamera.prototype.getClassName = function () {
  66472. return "FollowCamera";
  66473. };
  66474. __decorate([
  66475. BABYLON.serialize()
  66476. ], FollowCamera.prototype, "radius", void 0);
  66477. __decorate([
  66478. BABYLON.serialize()
  66479. ], FollowCamera.prototype, "rotationOffset", void 0);
  66480. __decorate([
  66481. BABYLON.serialize()
  66482. ], FollowCamera.prototype, "heightOffset", void 0);
  66483. __decorate([
  66484. BABYLON.serialize()
  66485. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  66486. __decorate([
  66487. BABYLON.serialize()
  66488. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  66489. __decorate([
  66490. BABYLON.serializeAsMeshReference("lockedTargetId")
  66491. ], FollowCamera.prototype, "lockedTarget", void 0);
  66492. return FollowCamera;
  66493. }(BABYLON.TargetCamera));
  66494. BABYLON.FollowCamera = FollowCamera;
  66495. var ArcFollowCamera = /** @class */ (function (_super) {
  66496. __extends(ArcFollowCamera, _super);
  66497. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  66498. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  66499. _this.alpha = alpha;
  66500. _this.beta = beta;
  66501. _this.radius = radius;
  66502. _this.target = target;
  66503. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  66504. _this.follow();
  66505. return _this;
  66506. }
  66507. ArcFollowCamera.prototype.follow = function () {
  66508. if (!this.target) {
  66509. return;
  66510. }
  66511. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  66512. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  66513. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  66514. var targetPosition = this.target.getAbsolutePosition();
  66515. this.position = targetPosition.add(this._cartesianCoordinates);
  66516. this.setTarget(targetPosition);
  66517. };
  66518. ArcFollowCamera.prototype._checkInputs = function () {
  66519. _super.prototype._checkInputs.call(this);
  66520. this.follow();
  66521. };
  66522. ArcFollowCamera.prototype.getClassName = function () {
  66523. return "ArcFollowCamera";
  66524. };
  66525. return ArcFollowCamera;
  66526. }(BABYLON.TargetCamera));
  66527. BABYLON.ArcFollowCamera = ArcFollowCamera;
  66528. })(BABYLON || (BABYLON = {}));
  66529. //# sourceMappingURL=babylon.followCamera.js.map
  66530. var BABYLON;
  66531. (function (BABYLON) {
  66532. // We're mainly based on the logic defined into the FreeCamera code
  66533. var UniversalCamera = /** @class */ (function (_super) {
  66534. __extends(UniversalCamera, _super);
  66535. //-- end properties for backward compatibility for inputs
  66536. function UniversalCamera(name, position, scene) {
  66537. var _this = _super.call(this, name, position, scene) || this;
  66538. _this.inputs.addGamepad();
  66539. return _this;
  66540. }
  66541. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  66542. //-- Begin properties for backward compatibility for inputs
  66543. get: function () {
  66544. var gamepad = this.inputs.attached["gamepad"];
  66545. if (gamepad)
  66546. return gamepad.gamepadAngularSensibility;
  66547. return 0;
  66548. },
  66549. set: function (value) {
  66550. var gamepad = this.inputs.attached["gamepad"];
  66551. if (gamepad)
  66552. gamepad.gamepadAngularSensibility = value;
  66553. },
  66554. enumerable: true,
  66555. configurable: true
  66556. });
  66557. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  66558. get: function () {
  66559. var gamepad = this.inputs.attached["gamepad"];
  66560. if (gamepad)
  66561. return gamepad.gamepadMoveSensibility;
  66562. return 0;
  66563. },
  66564. set: function (value) {
  66565. var gamepad = this.inputs.attached["gamepad"];
  66566. if (gamepad)
  66567. gamepad.gamepadMoveSensibility = value;
  66568. },
  66569. enumerable: true,
  66570. configurable: true
  66571. });
  66572. UniversalCamera.prototype.getClassName = function () {
  66573. return "UniversalCamera";
  66574. };
  66575. return UniversalCamera;
  66576. }(BABYLON.TouchCamera));
  66577. BABYLON.UniversalCamera = UniversalCamera;
  66578. })(BABYLON || (BABYLON = {}));
  66579. //# sourceMappingURL=babylon.universalCamera.js.map
  66580. var BABYLON;
  66581. (function (BABYLON) {
  66582. // We're mainly based on the logic defined into the FreeCamera code
  66583. var GamepadCamera = /** @class */ (function (_super) {
  66584. __extends(GamepadCamera, _super);
  66585. //-- end properties for backward compatibility for inputs
  66586. function GamepadCamera(name, position, scene) {
  66587. return _super.call(this, name, position, scene) || this;
  66588. }
  66589. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  66590. //-- Begin properties for backward compatibility for inputs
  66591. get: function () {
  66592. var gamepad = this.inputs.attached["gamepad"];
  66593. if (gamepad)
  66594. return gamepad.gamepadAngularSensibility;
  66595. return 0;
  66596. },
  66597. set: function (value) {
  66598. var gamepad = this.inputs.attached["gamepad"];
  66599. if (gamepad)
  66600. gamepad.gamepadAngularSensibility = value;
  66601. },
  66602. enumerable: true,
  66603. configurable: true
  66604. });
  66605. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  66606. get: function () {
  66607. var gamepad = this.inputs.attached["gamepad"];
  66608. if (gamepad)
  66609. return gamepad.gamepadMoveSensibility;
  66610. return 0;
  66611. },
  66612. set: function (value) {
  66613. var gamepad = this.inputs.attached["gamepad"];
  66614. if (gamepad)
  66615. gamepad.gamepadMoveSensibility = value;
  66616. },
  66617. enumerable: true,
  66618. configurable: true
  66619. });
  66620. GamepadCamera.prototype.getClassName = function () {
  66621. return "GamepadCamera";
  66622. };
  66623. return GamepadCamera;
  66624. }(BABYLON.UniversalCamera));
  66625. BABYLON.GamepadCamera = GamepadCamera;
  66626. })(BABYLON || (BABYLON = {}));
  66627. //# sourceMappingURL=babylon.gamepadCamera.js.map
  66628. var BABYLON;
  66629. (function (BABYLON) {
  66630. var PostProcessRenderPipelineManager = /** @class */ (function () {
  66631. function PostProcessRenderPipelineManager() {
  66632. this._renderPipelines = {};
  66633. }
  66634. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  66635. this._renderPipelines[renderPipeline._name] = renderPipeline;
  66636. };
  66637. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  66638. if (unique === void 0) { unique = false; }
  66639. var renderPipeline = this._renderPipelines[renderPipelineName];
  66640. if (!renderPipeline) {
  66641. return;
  66642. }
  66643. renderPipeline._attachCameras(cameras, unique);
  66644. };
  66645. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  66646. var renderPipeline = this._renderPipelines[renderPipelineName];
  66647. if (!renderPipeline) {
  66648. return;
  66649. }
  66650. renderPipeline._detachCameras(cameras);
  66651. };
  66652. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  66653. var renderPipeline = this._renderPipelines[renderPipelineName];
  66654. if (!renderPipeline) {
  66655. return;
  66656. }
  66657. renderPipeline._enableEffect(renderEffectName, cameras);
  66658. };
  66659. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  66660. var renderPipeline = this._renderPipelines[renderPipelineName];
  66661. if (!renderPipeline) {
  66662. return;
  66663. }
  66664. renderPipeline._disableEffect(renderEffectName, cameras);
  66665. };
  66666. PostProcessRenderPipelineManager.prototype.update = function () {
  66667. for (var renderPipelineName in this._renderPipelines) {
  66668. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  66669. var pipeline = this._renderPipelines[renderPipelineName];
  66670. if (!pipeline.isSupported) {
  66671. pipeline.dispose();
  66672. delete this._renderPipelines[renderPipelineName];
  66673. }
  66674. else {
  66675. pipeline._update();
  66676. }
  66677. }
  66678. }
  66679. };
  66680. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  66681. for (var renderPipelineName in this._renderPipelines) {
  66682. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  66683. var pipeline = this._renderPipelines[renderPipelineName];
  66684. pipeline._rebuild();
  66685. }
  66686. }
  66687. };
  66688. PostProcessRenderPipelineManager.prototype.dispose = function () {
  66689. for (var renderPipelineName in this._renderPipelines) {
  66690. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  66691. var pipeline = this._renderPipelines[renderPipelineName];
  66692. pipeline.dispose();
  66693. }
  66694. }
  66695. };
  66696. return PostProcessRenderPipelineManager;
  66697. }());
  66698. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  66699. })(BABYLON || (BABYLON = {}));
  66700. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  66701. var BABYLON;
  66702. (function (BABYLON) {
  66703. /**
  66704. * This represents a set of one or more post processes in Babylon.
  66705. * A post process can be used to apply a shader to a texture after it is rendered.
  66706. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  66707. */
  66708. var PostProcessRenderEffect = /** @class */ (function () {
  66709. /**
  66710. * Instantiates a post process render effect.
  66711. * A post process can be used to apply a shader to a texture after it is rendered.
  66712. * @param engine The engine the effect is tied to
  66713. * @param name The name of the effect
  66714. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  66715. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  66716. */
  66717. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  66718. this._name = name;
  66719. this._singleInstance = singleInstance || true;
  66720. this._getPostProcesses = getPostProcesses;
  66721. this._cameras = {};
  66722. this._indicesForCamera = {};
  66723. this._postProcesses = {};
  66724. }
  66725. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  66726. /**
  66727. * Checks if all the post processes in the effect are supported.
  66728. */
  66729. get: function () {
  66730. for (var index in this._postProcesses) {
  66731. for (var ppIndex in this._postProcesses[index]) {
  66732. if (!this._postProcesses[index][ppIndex].isSupported) {
  66733. return false;
  66734. }
  66735. }
  66736. }
  66737. return true;
  66738. },
  66739. enumerable: true,
  66740. configurable: true
  66741. });
  66742. /**
  66743. * Updates the current state of the effect
  66744. */
  66745. PostProcessRenderEffect.prototype._update = function () {
  66746. };
  66747. /**
  66748. * Attaches the effect on cameras
  66749. * @param cameras The camera to attach to.
  66750. */
  66751. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  66752. var _this = this;
  66753. var cameraKey;
  66754. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  66755. if (!cams) {
  66756. return;
  66757. }
  66758. for (var i = 0; i < cams.length; i++) {
  66759. var camera = cams[i];
  66760. var cameraName = camera.name;
  66761. if (this._singleInstance) {
  66762. cameraKey = 0;
  66763. }
  66764. else {
  66765. cameraKey = cameraName;
  66766. }
  66767. if (!this._postProcesses[cameraKey]) {
  66768. var postProcess = this._getPostProcesses();
  66769. if (postProcess) {
  66770. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  66771. }
  66772. }
  66773. if (!this._indicesForCamera[cameraName]) {
  66774. this._indicesForCamera[cameraName] = [];
  66775. }
  66776. this._postProcesses[cameraKey].forEach(function (postProcess) {
  66777. var index = camera.attachPostProcess(postProcess);
  66778. _this._indicesForCamera[cameraName].push(index);
  66779. });
  66780. if (!this._cameras[cameraName]) {
  66781. this._cameras[cameraName] = camera;
  66782. }
  66783. }
  66784. };
  66785. /**
  66786. * Detatches the effect on cameras
  66787. * @param cameras The camera to detatch from.
  66788. */
  66789. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  66790. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  66791. if (!cams) {
  66792. return;
  66793. }
  66794. for (var i = 0; i < cams.length; i++) {
  66795. var camera = cams[i];
  66796. var cameraName = camera.name;
  66797. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  66798. camera.detachPostProcess(postProcess);
  66799. });
  66800. if (this._cameras[cameraName]) {
  66801. //this._indicesForCamera.splice(index, 1);
  66802. this._cameras[cameraName] = null;
  66803. }
  66804. }
  66805. };
  66806. /**
  66807. * Enables the effect on given cameras
  66808. * @param cameras The camera to enable.
  66809. */
  66810. PostProcessRenderEffect.prototype._enable = function (cameras) {
  66811. var _this = this;
  66812. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  66813. if (!cams) {
  66814. return;
  66815. }
  66816. for (var i = 0; i < cams.length; i++) {
  66817. var camera = cams[i];
  66818. var cameraName = camera.name;
  66819. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  66820. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined || camera._postProcesses[this._indicesForCamera[cameraName][j]] === null) {
  66821. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  66822. cams[i].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);
  66823. });
  66824. }
  66825. }
  66826. }
  66827. };
  66828. /**
  66829. * Disables the effect on the given cameras
  66830. * @param cameras The camera to disable.
  66831. */
  66832. PostProcessRenderEffect.prototype._disable = function (cameras) {
  66833. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  66834. if (!cams) {
  66835. return;
  66836. }
  66837. for (var i = 0; i < cams.length; i++) {
  66838. var camera = cams[i];
  66839. var cameraName = camera.name;
  66840. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  66841. camera.detachPostProcess(postProcess);
  66842. });
  66843. }
  66844. };
  66845. /**
  66846. * Gets a list of the post processes contained in the effect.
  66847. * @param camera The camera to get the post processes on.
  66848. * @returns The list of the post processes in the effect.
  66849. */
  66850. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  66851. if (this._singleInstance) {
  66852. return this._postProcesses[0];
  66853. }
  66854. else {
  66855. if (!camera) {
  66856. return null;
  66857. }
  66858. return this._postProcesses[camera.name];
  66859. }
  66860. };
  66861. return PostProcessRenderEffect;
  66862. }());
  66863. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  66864. })(BABYLON || (BABYLON = {}));
  66865. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  66866. var BABYLON;
  66867. (function (BABYLON) {
  66868. var PostProcessRenderPipeline = /** @class */ (function () {
  66869. function PostProcessRenderPipeline(engine, name) {
  66870. this.engine = engine;
  66871. this._name = name;
  66872. this._renderEffects = {};
  66873. this._renderEffectsForIsolatedPass = new Array();
  66874. this._cameras = [];
  66875. }
  66876. PostProcessRenderPipeline.prototype.getClassName = function () {
  66877. return "PostProcessRenderPipeline";
  66878. };
  66879. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  66880. get: function () {
  66881. for (var renderEffectName in this._renderEffects) {
  66882. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  66883. if (!this._renderEffects[renderEffectName].isSupported) {
  66884. return false;
  66885. }
  66886. }
  66887. }
  66888. return true;
  66889. },
  66890. enumerable: true,
  66891. configurable: true
  66892. });
  66893. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  66894. this._renderEffects[renderEffect._name] = renderEffect;
  66895. };
  66896. // private
  66897. PostProcessRenderPipeline.prototype._rebuild = function () {
  66898. };
  66899. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  66900. var renderEffects = this._renderEffects[renderEffectName];
  66901. if (!renderEffects) {
  66902. return;
  66903. }
  66904. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  66905. };
  66906. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  66907. var renderEffects = this._renderEffects[renderEffectName];
  66908. if (!renderEffects) {
  66909. return;
  66910. }
  66911. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  66912. };
  66913. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  66914. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  66915. if (!cams) {
  66916. return;
  66917. }
  66918. var indicesToDelete = [];
  66919. var i;
  66920. for (i = 0; i < cams.length; i++) {
  66921. var camera = cams[i];
  66922. var cameraName = camera.name;
  66923. if (this._cameras.indexOf(camera) === -1) {
  66924. this._cameras[cameraName] = camera;
  66925. }
  66926. else if (unique) {
  66927. indicesToDelete.push(i);
  66928. }
  66929. }
  66930. for (i = 0; i < indicesToDelete.length; i++) {
  66931. cameras.splice(indicesToDelete[i], 1);
  66932. }
  66933. for (var renderEffectName in this._renderEffects) {
  66934. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  66935. this._renderEffects[renderEffectName]._attachCameras(cams);
  66936. }
  66937. }
  66938. };
  66939. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  66940. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  66941. if (!cams) {
  66942. return;
  66943. }
  66944. for (var renderEffectName in this._renderEffects) {
  66945. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  66946. this._renderEffects[renderEffectName]._detachCameras(cams);
  66947. }
  66948. }
  66949. for (var i = 0; i < cams.length; i++) {
  66950. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  66951. }
  66952. };
  66953. PostProcessRenderPipeline.prototype._update = function () {
  66954. for (var renderEffectName in this._renderEffects) {
  66955. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  66956. this._renderEffects[renderEffectName]._update();
  66957. }
  66958. }
  66959. for (var i = 0; i < this._cameras.length; i++) {
  66960. var cameraName = this._cameras[i].name;
  66961. if (this._renderEffectsForIsolatedPass[cameraName]) {
  66962. this._renderEffectsForIsolatedPass[cameraName]._update();
  66963. }
  66964. }
  66965. };
  66966. PostProcessRenderPipeline.prototype._reset = function () {
  66967. this._renderEffects = {};
  66968. this._renderEffectsForIsolatedPass = new Array();
  66969. };
  66970. PostProcessRenderPipeline.prototype._enableMSAAOnFirstPostProcess = function () {
  66971. // 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)
  66972. var effectKeys = Object.keys(this._renderEffects);
  66973. if (this.engine.webGLVersion >= 2 && effectKeys.length > 0) {
  66974. var postProcesses = this._renderEffects[effectKeys[0]].getPostProcesses();
  66975. if (postProcesses) {
  66976. postProcesses[0].samples = 4;
  66977. return true;
  66978. }
  66979. }
  66980. return false;
  66981. };
  66982. PostProcessRenderPipeline.prototype.dispose = function () {
  66983. // Must be implemented by children
  66984. };
  66985. __decorate([
  66986. BABYLON.serialize()
  66987. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  66988. return PostProcessRenderPipeline;
  66989. }());
  66990. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  66991. })(BABYLON || (BABYLON = {}));
  66992. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  66993. var BABYLON;
  66994. (function (BABYLON) {
  66995. /**
  66996. * This represents a depth renderer in Babylon.
  66997. * A depth renderer will render to it's depth map every frame which can be displayed or used in post processing
  66998. */
  66999. var DepthRenderer = /** @class */ (function () {
  67000. /**
  67001. * Instantiates a depth renderer
  67002. * @param scene The scene the renderer belongs to
  67003. * @param type The texture type of the depth map (default: Engine.TEXTURETYPE_FLOAT)
  67004. * @param camera The camera to be used to render the depth map (default: scene's active camera)
  67005. */
  67006. function DepthRenderer(scene, type, camera) {
  67007. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  67008. if (camera === void 0) { camera = null; }
  67009. var _this = this;
  67010. this._scene = scene;
  67011. this._camera = camera;
  67012. var engine = scene.getEngine();
  67013. // Render target
  67014. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  67015. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67016. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67017. this._depthMap.refreshRate = 1;
  67018. this._depthMap.renderParticles = false;
  67019. this._depthMap.renderList = null;
  67020. // Camera to get depth map from to support multiple concurrent cameras
  67021. this._depthMap.activeCamera = this._camera;
  67022. this._depthMap.ignoreCameraViewport = true;
  67023. this._depthMap.useCameraPostProcesses = false;
  67024. // set default depth value to 1.0 (far away)
  67025. this._depthMap.onClearObservable.add(function (engine) {
  67026. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  67027. });
  67028. // Custom render function
  67029. var renderSubMesh = function (subMesh) {
  67030. var mesh = subMesh.getRenderingMesh();
  67031. var scene = _this._scene;
  67032. var engine = scene.getEngine();
  67033. var material = subMesh.getMaterial();
  67034. if (!material) {
  67035. return;
  67036. }
  67037. // Culling and reverse (right handed system)
  67038. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  67039. // Managing instances
  67040. var batch = mesh._getInstancesRenderList(subMesh._id);
  67041. if (batch.mustReturn) {
  67042. return;
  67043. }
  67044. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  67045. var camera = _this._camera || scene.activeCamera;
  67046. if (_this.isReady(subMesh, hardwareInstancedRendering) && camera) {
  67047. engine.enableEffect(_this._effect);
  67048. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  67049. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  67050. _this._effect.setFloat2("depthValues", camera.minZ, camera.minZ + camera.maxZ);
  67051. // Alpha test
  67052. if (material && material.needAlphaTesting()) {
  67053. var alphaTexture = material.getAlphaTestTexture();
  67054. if (alphaTexture) {
  67055. _this._effect.setTexture("diffuseSampler", alphaTexture);
  67056. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  67057. }
  67058. }
  67059. // Bones
  67060. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  67061. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  67062. }
  67063. // Draw
  67064. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  67065. }
  67066. };
  67067. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  67068. var index;
  67069. if (depthOnlySubMeshes.length) {
  67070. engine.setColorWrite(false);
  67071. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  67072. renderSubMesh(depthOnlySubMeshes.data[index]);
  67073. }
  67074. engine.setColorWrite(true);
  67075. }
  67076. for (index = 0; index < opaqueSubMeshes.length; index++) {
  67077. renderSubMesh(opaqueSubMeshes.data[index]);
  67078. }
  67079. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  67080. renderSubMesh(alphaTestSubMeshes.data[index]);
  67081. }
  67082. };
  67083. }
  67084. /**
  67085. * Creates the depth rendering effect and checks if the effect is ready.
  67086. * @param subMesh The submesh to be used to render the depth map of
  67087. * @param useInstances If multiple world instances should be used
  67088. * @returns if the depth renderer is ready to render the depth map
  67089. */
  67090. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  67091. var material = subMesh.getMaterial();
  67092. if (material.disableDepthWrite) {
  67093. return false;
  67094. }
  67095. var defines = [];
  67096. var attribs = [BABYLON.VertexBuffer.PositionKind];
  67097. var mesh = subMesh.getMesh();
  67098. // Alpha test
  67099. if (material && material.needAlphaTesting() && material.getAlphaTestTexture()) {
  67100. defines.push("#define ALPHATEST");
  67101. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  67102. attribs.push(BABYLON.VertexBuffer.UVKind);
  67103. defines.push("#define UV1");
  67104. }
  67105. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  67106. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  67107. defines.push("#define UV2");
  67108. }
  67109. }
  67110. // Bones
  67111. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  67112. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  67113. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  67114. if (mesh.numBoneInfluencers > 4) {
  67115. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  67116. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  67117. }
  67118. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  67119. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  67120. }
  67121. else {
  67122. defines.push("#define NUM_BONE_INFLUENCERS 0");
  67123. }
  67124. // Instances
  67125. if (useInstances) {
  67126. defines.push("#define INSTANCES");
  67127. attribs.push("world0");
  67128. attribs.push("world1");
  67129. attribs.push("world2");
  67130. attribs.push("world3");
  67131. }
  67132. // Get correct effect
  67133. var join = defines.join("\n");
  67134. if (this._cachedDefines !== join) {
  67135. this._cachedDefines = join;
  67136. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  67137. }
  67138. return this._effect.isReady();
  67139. };
  67140. /**
  67141. * Gets the texture which the depth map will be written to.
  67142. * @returns The depth map texture
  67143. */
  67144. DepthRenderer.prototype.getDepthMap = function () {
  67145. return this._depthMap;
  67146. };
  67147. /**
  67148. * Disposes of the depth renderer.
  67149. */
  67150. DepthRenderer.prototype.dispose = function () {
  67151. this._depthMap.dispose();
  67152. };
  67153. return DepthRenderer;
  67154. }());
  67155. BABYLON.DepthRenderer = DepthRenderer;
  67156. })(BABYLON || (BABYLON = {}));
  67157. //# sourceMappingURL=babylon.depthRenderer.js.map
  67158. var BABYLON;
  67159. (function (BABYLON) {
  67160. var SSAORenderingPipeline = /** @class */ (function (_super) {
  67161. __extends(SSAORenderingPipeline, _super);
  67162. /**
  67163. * @constructor
  67164. * @param {string} name - The rendering pipeline name
  67165. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  67166. * @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 }
  67167. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  67168. */
  67169. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  67170. var _this = _super.call(this, scene.getEngine(), name) || this;
  67171. // Members
  67172. /**
  67173. * The PassPostProcess id in the pipeline that contains the original scene color
  67174. * @type {string}
  67175. */
  67176. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  67177. /**
  67178. * The SSAO PostProcess id in the pipeline
  67179. * @type {string}
  67180. */
  67181. _this.SSAORenderEffect = "SSAORenderEffect";
  67182. /**
  67183. * The horizontal blur PostProcess id in the pipeline
  67184. * @type {string}
  67185. */
  67186. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  67187. /**
  67188. * The vertical blur PostProcess id in the pipeline
  67189. * @type {string}
  67190. */
  67191. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  67192. /**
  67193. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  67194. * @type {string}
  67195. */
  67196. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  67197. /**
  67198. * The output strength of the SSAO post-process. Default value is 1.0.
  67199. * @type {number}
  67200. */
  67201. _this.totalStrength = 1.0;
  67202. /**
  67203. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  67204. * @type {number}
  67205. */
  67206. _this.radius = 0.0001;
  67207. /**
  67208. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  67209. * Must not be equal to fallOff and superior to fallOff.
  67210. * Default value is 0.975
  67211. * @type {number}
  67212. */
  67213. _this.area = 0.0075;
  67214. /**
  67215. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  67216. * Must not be equal to area and inferior to area.
  67217. * Default value is 0.0
  67218. * @type {number}
  67219. */
  67220. _this.fallOff = 0.000001;
  67221. /**
  67222. * The base color of the SSAO post-process
  67223. * The final result is "base + ssao" between [0, 1]
  67224. * @type {number}
  67225. */
  67226. _this.base = 0.5;
  67227. _this._firstUpdate = true;
  67228. _this._scene = scene;
  67229. // Set up assets
  67230. _this._createRandomTexture();
  67231. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  67232. var ssaoRatio = ratio.ssaoRatio || ratio;
  67233. var combineRatio = ratio.combineRatio || ratio;
  67234. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  67235. _this._createSSAOPostProcess(ssaoRatio);
  67236. _this._createBlurPostProcess(ssaoRatio);
  67237. _this._createSSAOCombinePostProcess(combineRatio);
  67238. // Set up pipeline
  67239. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  67240. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  67241. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  67242. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  67243. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  67244. // Finish
  67245. scene.postProcessRenderPipelineManager.addPipeline(_this);
  67246. if (cameras)
  67247. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  67248. return _this;
  67249. }
  67250. // Public Methods
  67251. /**
  67252. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  67253. */
  67254. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  67255. if (disableDepthRender === void 0) { disableDepthRender = false; }
  67256. for (var i = 0; i < this._scene.cameras.length; i++) {
  67257. var camera = this._scene.cameras[i];
  67258. this._originalColorPostProcess.dispose(camera);
  67259. this._ssaoPostProcess.dispose(camera);
  67260. this._blurHPostProcess.dispose(camera);
  67261. this._blurVPostProcess.dispose(camera);
  67262. this._ssaoCombinePostProcess.dispose(camera);
  67263. }
  67264. this._randomTexture.dispose();
  67265. if (disableDepthRender)
  67266. this._scene.disableDepthRenderer();
  67267. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  67268. _super.prototype.dispose.call(this);
  67269. };
  67270. // Private Methods
  67271. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  67272. var _this = this;
  67273. var size = 16;
  67274. 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);
  67275. 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);
  67276. this._blurHPostProcess.onActivateObservable.add(function () {
  67277. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  67278. _this._blurHPostProcess.kernel = size * dw;
  67279. });
  67280. this._blurVPostProcess.onActivateObservable.add(function () {
  67281. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  67282. _this._blurVPostProcess.kernel = size * dw;
  67283. });
  67284. };
  67285. SSAORenderingPipeline.prototype._rebuild = function () {
  67286. this._firstUpdate = true;
  67287. _super.prototype._rebuild.call(this);
  67288. };
  67289. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  67290. var _this = this;
  67291. var numSamples = 16;
  67292. var sampleSphere = [
  67293. 0.5381, 0.1856, -0.4319,
  67294. 0.1379, 0.2486, 0.4430,
  67295. 0.3371, 0.5679, -0.0057,
  67296. -0.6999, -0.0451, -0.0019,
  67297. 0.0689, -0.1598, -0.8547,
  67298. 0.0560, 0.0069, -0.1843,
  67299. -0.0146, 0.1402, 0.0762,
  67300. 0.0100, -0.1924, -0.0344,
  67301. -0.3577, -0.5301, -0.4358,
  67302. -0.3169, 0.1063, 0.0158,
  67303. 0.0103, -0.5869, 0.0046,
  67304. -0.0897, -0.4940, 0.3287,
  67305. 0.7119, -0.0154, -0.0918,
  67306. -0.0533, 0.0596, -0.5411,
  67307. 0.0352, -0.0631, 0.5460,
  67308. -0.4776, 0.2847, -0.0271
  67309. ];
  67310. var samplesFactor = 1.0 / numSamples;
  67311. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  67312. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  67313. "area", "fallOff", "base", "range", "viewport"
  67314. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  67315. this._ssaoPostProcess.onApply = function (effect) {
  67316. if (_this._firstUpdate) {
  67317. effect.setArray3("sampleSphere", sampleSphere);
  67318. effect.setFloat("samplesFactor", samplesFactor);
  67319. effect.setFloat("randTextureTiles", 4.0);
  67320. }
  67321. effect.setFloat("totalStrength", _this.totalStrength);
  67322. effect.setFloat("radius", _this.radius);
  67323. effect.setFloat("area", _this.area);
  67324. effect.setFloat("fallOff", _this.fallOff);
  67325. effect.setFloat("base", _this.base);
  67326. effect.setTexture("textureSampler", _this._depthTexture);
  67327. effect.setTexture("randomSampler", _this._randomTexture);
  67328. };
  67329. };
  67330. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  67331. var _this = this;
  67332. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  67333. this._ssaoCombinePostProcess.onApply = function (effect) {
  67334. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  67335. };
  67336. };
  67337. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  67338. var size = 512;
  67339. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  67340. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  67341. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  67342. var context = this._randomTexture.getContext();
  67343. var rand = function (min, max) {
  67344. return Math.random() * (max - min) + min;
  67345. };
  67346. var randVector = BABYLON.Vector3.Zero();
  67347. for (var x = 0; x < size; x++) {
  67348. for (var y = 0; y < size; y++) {
  67349. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  67350. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  67351. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  67352. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  67353. context.fillRect(x, y, 1, 1);
  67354. }
  67355. }
  67356. this._randomTexture.update(false);
  67357. };
  67358. __decorate([
  67359. BABYLON.serialize()
  67360. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  67361. __decorate([
  67362. BABYLON.serialize()
  67363. ], SSAORenderingPipeline.prototype, "radius", void 0);
  67364. __decorate([
  67365. BABYLON.serialize()
  67366. ], SSAORenderingPipeline.prototype, "area", void 0);
  67367. __decorate([
  67368. BABYLON.serialize()
  67369. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  67370. __decorate([
  67371. BABYLON.serialize()
  67372. ], SSAORenderingPipeline.prototype, "base", void 0);
  67373. return SSAORenderingPipeline;
  67374. }(BABYLON.PostProcessRenderPipeline));
  67375. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  67376. })(BABYLON || (BABYLON = {}));
  67377. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  67378. var BABYLON;
  67379. (function (BABYLON) {
  67380. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  67381. __extends(SSAO2RenderingPipeline, _super);
  67382. /**
  67383. * @constructor
  67384. * @param {string} name - The rendering pipeline name
  67385. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  67386. * @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 }
  67387. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  67388. */
  67389. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  67390. var _this = _super.call(this, scene.getEngine(), name) || this;
  67391. // Members
  67392. /**
  67393. * The PassPostProcess id in the pipeline that contains the original scene color
  67394. * @type {string}
  67395. */
  67396. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  67397. /**
  67398. * The SSAO PostProcess id in the pipeline
  67399. * @type {string}
  67400. */
  67401. _this.SSAORenderEffect = "SSAORenderEffect";
  67402. /**
  67403. * The horizontal blur PostProcess id in the pipeline
  67404. * @type {string}
  67405. */
  67406. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  67407. /**
  67408. * The vertical blur PostProcess id in the pipeline
  67409. * @type {string}
  67410. */
  67411. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  67412. /**
  67413. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  67414. * @type {string}
  67415. */
  67416. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  67417. /**
  67418. * The output strength of the SSAO post-process. Default value is 1.0.
  67419. * @type {number}
  67420. */
  67421. _this.totalStrength = 1.0;
  67422. /**
  67423. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  67424. * @type {number}
  67425. */
  67426. _this.maxZ = 100.0;
  67427. /**
  67428. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  67429. * @type {number}
  67430. */
  67431. _this.minZAspect = 0.2;
  67432. /**
  67433. * Number of samples used for the SSAO calculations. Default value is 8
  67434. * @type {number}
  67435. */
  67436. _this._samples = 8;
  67437. /**
  67438. * Are we using bilateral blur ?
  67439. * @type {boolean}
  67440. */
  67441. _this._expensiveBlur = true;
  67442. /**
  67443. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  67444. * @type {number}
  67445. */
  67446. _this.radius = 2.0;
  67447. /**
  67448. * The base color of the SSAO post-process
  67449. * The final result is "base + ssao" between [0, 1]
  67450. * @type {number}
  67451. */
  67452. _this.base = 0.1;
  67453. _this._firstUpdate = true;
  67454. _this._scene = scene;
  67455. if (!_this.isSupported) {
  67456. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  67457. return _this;
  67458. }
  67459. var ssaoRatio = ratio.ssaoRatio || ratio;
  67460. var blurRatio = ratio.blurRatio || ratio;
  67461. // Set up assets
  67462. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  67463. _this._createRandomTexture();
  67464. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  67465. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  67466. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  67467. _this._createSSAOPostProcess(1.0);
  67468. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  67469. _this._createSSAOCombinePostProcess(blurRatio);
  67470. // Set up pipeline
  67471. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  67472. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  67473. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  67474. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  67475. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  67476. // Finish
  67477. scene.postProcessRenderPipelineManager.addPipeline(_this);
  67478. if (cameras)
  67479. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  67480. return _this;
  67481. }
  67482. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  67483. get: function () {
  67484. return this._samples;
  67485. },
  67486. set: function (n) {
  67487. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  67488. this._samples = n;
  67489. this._sampleSphere = this._generateHemisphere();
  67490. this._firstUpdate = true;
  67491. },
  67492. enumerable: true,
  67493. configurable: true
  67494. });
  67495. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  67496. get: function () {
  67497. return this._expensiveBlur;
  67498. },
  67499. set: function (b) {
  67500. 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"]);
  67501. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  67502. this._expensiveBlur = b;
  67503. this._firstUpdate = true;
  67504. },
  67505. enumerable: true,
  67506. configurable: true
  67507. });
  67508. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  67509. /**
  67510. * Support test.
  67511. * @type {boolean}
  67512. */
  67513. get: function () {
  67514. var engine = BABYLON.Engine.LastCreatedEngine;
  67515. if (!engine) {
  67516. return false;
  67517. }
  67518. return engine.getCaps().drawBuffersExtension;
  67519. },
  67520. enumerable: true,
  67521. configurable: true
  67522. });
  67523. // Public Methods
  67524. /**
  67525. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  67526. */
  67527. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  67528. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  67529. for (var i = 0; i < this._scene.cameras.length; i++) {
  67530. var camera = this._scene.cameras[i];
  67531. this._originalColorPostProcess.dispose(camera);
  67532. this._ssaoPostProcess.dispose(camera);
  67533. this._blurHPostProcess.dispose(camera);
  67534. this._blurVPostProcess.dispose(camera);
  67535. this._ssaoCombinePostProcess.dispose(camera);
  67536. }
  67537. this._randomTexture.dispose();
  67538. if (disableGeometryBufferRenderer)
  67539. this._scene.disableGeometryBufferRenderer();
  67540. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  67541. _super.prototype.dispose.call(this);
  67542. };
  67543. // Private Methods
  67544. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  67545. var _this = this;
  67546. this._samplerOffsets = [];
  67547. var expensive = this.expensiveBlur;
  67548. for (var i = -8; i < 8; i++) {
  67549. this._samplerOffsets.push(i * 2 + 0.5);
  67550. }
  67551. 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");
  67552. this._blurHPostProcess.onApply = function (effect) {
  67553. if (!_this._scene.activeCamera) {
  67554. return;
  67555. }
  67556. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  67557. effect.setFloat("near", _this._scene.activeCamera.minZ);
  67558. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  67559. effect.setFloat("radius", _this.radius);
  67560. effect.setTexture("depthSampler", _this._depthTexture);
  67561. if (_this._firstUpdate) {
  67562. effect.setArray("samplerOffsets", _this._samplerOffsets);
  67563. }
  67564. };
  67565. 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");
  67566. this._blurVPostProcess.onApply = function (effect) {
  67567. if (!_this._scene.activeCamera) {
  67568. return;
  67569. }
  67570. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  67571. effect.setFloat("near", _this._scene.activeCamera.minZ);
  67572. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  67573. effect.setFloat("radius", _this.radius);
  67574. effect.setTexture("depthSampler", _this._depthTexture);
  67575. if (_this._firstUpdate) {
  67576. effect.setArray("samplerOffsets", _this._samplerOffsets);
  67577. _this._firstUpdate = false;
  67578. }
  67579. };
  67580. };
  67581. SSAO2RenderingPipeline.prototype._rebuild = function () {
  67582. this._firstUpdate = true;
  67583. _super.prototype._rebuild.call(this);
  67584. };
  67585. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  67586. var numSamples = this.samples;
  67587. var result = [];
  67588. var vector, scale;
  67589. var rand = function (min, max) {
  67590. return Math.random() * (max - min) + min;
  67591. };
  67592. var i = 0;
  67593. while (i < numSamples) {
  67594. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  67595. vector.normalize();
  67596. scale = i / numSamples;
  67597. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  67598. vector.scaleInPlace(scale);
  67599. result.push(vector.x, vector.y, vector.z);
  67600. i++;
  67601. }
  67602. return result;
  67603. };
  67604. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  67605. var _this = this;
  67606. var numSamples = this.samples;
  67607. this._sampleSphere = this._generateHemisphere();
  67608. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  67609. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  67610. "base", "range", "projection", "near", "far", "texelSize",
  67611. "xViewport", "yViewport", "maxZ", "minZAspect"
  67612. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  67613. this._ssaoPostProcess.onApply = function (effect) {
  67614. if (_this._firstUpdate) {
  67615. effect.setArray3("sampleSphere", _this._sampleSphere);
  67616. effect.setFloat("randTextureTiles", 4.0);
  67617. }
  67618. if (!_this._scene.activeCamera) {
  67619. return;
  67620. }
  67621. effect.setFloat("samplesFactor", 1 / _this.samples);
  67622. effect.setFloat("totalStrength", _this.totalStrength);
  67623. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  67624. effect.setFloat("radius", _this.radius);
  67625. effect.setFloat("maxZ", _this.maxZ);
  67626. effect.setFloat("minZAspect", _this.minZAspect);
  67627. effect.setFloat("base", _this.base);
  67628. effect.setFloat("near", _this._scene.activeCamera.minZ);
  67629. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  67630. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  67631. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  67632. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  67633. effect.setTexture("textureSampler", _this._depthTexture);
  67634. effect.setTexture("normalSampler", _this._normalTexture);
  67635. effect.setTexture("randomSampler", _this._randomTexture);
  67636. };
  67637. };
  67638. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  67639. var _this = this;
  67640. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  67641. this._ssaoCombinePostProcess.onApply = function (effect) {
  67642. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  67643. };
  67644. };
  67645. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  67646. var size = 512;
  67647. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  67648. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  67649. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  67650. var context = this._randomTexture.getContext();
  67651. var rand = function (min, max) {
  67652. return Math.random() * (max - min) + min;
  67653. };
  67654. var randVector = BABYLON.Vector3.Zero();
  67655. for (var x = 0; x < size; x++) {
  67656. for (var y = 0; y < size; y++) {
  67657. randVector.x = rand(0.0, 1.0);
  67658. randVector.y = rand(0.0, 1.0);
  67659. randVector.z = 0.0;
  67660. randVector.normalize();
  67661. randVector.scaleInPlace(255);
  67662. randVector.x = Math.floor(randVector.x);
  67663. randVector.y = Math.floor(randVector.y);
  67664. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  67665. context.fillRect(x, y, 1, 1);
  67666. }
  67667. }
  67668. this._randomTexture.update(false);
  67669. };
  67670. __decorate([
  67671. BABYLON.serialize()
  67672. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  67673. __decorate([
  67674. BABYLON.serialize()
  67675. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  67676. __decorate([
  67677. BABYLON.serialize()
  67678. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  67679. __decorate([
  67680. BABYLON.serialize("samples")
  67681. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  67682. __decorate([
  67683. BABYLON.serialize("expensiveBlur")
  67684. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  67685. __decorate([
  67686. BABYLON.serialize()
  67687. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  67688. __decorate([
  67689. BABYLON.serialize()
  67690. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  67691. return SSAO2RenderingPipeline;
  67692. }(BABYLON.PostProcessRenderPipeline));
  67693. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  67694. })(BABYLON || (BABYLON = {}));
  67695. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  67696. // BABYLON.JS Chromatic Aberration GLSL Shader
  67697. // Author: Olivier Guyot
  67698. // Separates very slightly R, G and B colors on the edges of the screen
  67699. // Inspired by Francois Tarlier & Martins Upitis
  67700. var BABYLON;
  67701. (function (BABYLON) {
  67702. var LensRenderingPipeline = /** @class */ (function (_super) {
  67703. __extends(LensRenderingPipeline, _super);
  67704. /**
  67705. * @constructor
  67706. *
  67707. * Effect parameters are as follow:
  67708. * {
  67709. * chromatic_aberration: number; // from 0 to x (1 for realism)
  67710. * edge_blur: number; // from 0 to x (1 for realism)
  67711. * distortion: number; // from 0 to x (1 for realism)
  67712. * grain_amount: number; // from 0 to 1
  67713. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  67714. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  67715. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  67716. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  67717. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  67718. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  67719. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  67720. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  67721. * }
  67722. * Note: if an effect parameter is unset, effect is disabled
  67723. *
  67724. * @param {string} name - The rendering pipeline name
  67725. * @param {object} parameters - An object containing all parameters (see above)
  67726. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  67727. * @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)
  67728. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  67729. */
  67730. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  67731. if (ratio === void 0) { ratio = 1.0; }
  67732. var _this = _super.call(this, scene.getEngine(), name) || this;
  67733. // Lens effects can be of the following:
  67734. // - chromatic aberration (slight shift of RGB colors)
  67735. // - blur on the edge of the lens
  67736. // - lens distortion
  67737. // - depth-of-field blur & highlights enhancing
  67738. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  67739. // - grain effect (noise or custom texture)
  67740. // Two additional texture samplers are needed:
  67741. // - depth map (for depth-of-field)
  67742. // - grain texture
  67743. /**
  67744. * The chromatic aberration PostProcess id in the pipeline
  67745. * @type {string}
  67746. */
  67747. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  67748. /**
  67749. * The highlights enhancing PostProcess id in the pipeline
  67750. * @type {string}
  67751. */
  67752. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  67753. /**
  67754. * The depth-of-field PostProcess id in the pipeline
  67755. * @type {string}
  67756. */
  67757. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  67758. _this._scene = scene;
  67759. // Fetch texture samplers
  67760. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  67761. if (parameters.grain_texture) {
  67762. _this._grainTexture = parameters.grain_texture;
  67763. }
  67764. else {
  67765. _this._createGrainTexture();
  67766. }
  67767. // save parameters
  67768. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  67769. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  67770. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  67771. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  67772. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  67773. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  67774. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  67775. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  67776. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  67777. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  67778. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  67779. // Create effects
  67780. _this._createChromaticAberrationPostProcess(ratio);
  67781. _this._createHighlightsPostProcess(ratio);
  67782. _this._createDepthOfFieldPostProcess(ratio / 4);
  67783. // Set up pipeline
  67784. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  67785. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  67786. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  67787. if (_this._highlightsGain === -1) {
  67788. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  67789. }
  67790. // Finish
  67791. scene.postProcessRenderPipelineManager.addPipeline(_this);
  67792. if (cameras) {
  67793. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  67794. }
  67795. return _this;
  67796. }
  67797. // public methods (self explanatory)
  67798. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  67799. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  67800. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  67801. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  67802. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  67803. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  67804. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  67805. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  67806. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  67807. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  67808. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  67809. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  67810. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  67811. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  67812. };
  67813. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  67814. this._highlightsPostProcess.updateEffect();
  67815. };
  67816. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  67817. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  67818. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  67819. this._highlightsGain = amount;
  67820. };
  67821. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  67822. if (this._highlightsGain === -1) {
  67823. this._highlightsGain = 1.0;
  67824. }
  67825. this._highlightsThreshold = amount;
  67826. };
  67827. LensRenderingPipeline.prototype.disableHighlights = function () {
  67828. this._highlightsGain = -1;
  67829. };
  67830. /**
  67831. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  67832. */
  67833. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  67834. if (disableDepthRender === void 0) { disableDepthRender = false; }
  67835. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  67836. this._chromaticAberrationPostProcess = null;
  67837. this._highlightsPostProcess = null;
  67838. this._depthOfFieldPostProcess = null;
  67839. this._grainTexture.dispose();
  67840. if (disableDepthRender)
  67841. this._scene.disableDepthRenderer();
  67842. };
  67843. // colors shifting and distortion
  67844. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  67845. var _this = this;
  67846. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], // uniforms
  67847. [], // samplers
  67848. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  67849. this._chromaticAberrationPostProcess.onApply = function (effect) {
  67850. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  67851. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  67852. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  67853. effect.setFloat('radialIntensity', 1);
  67854. effect.setFloat2('direction', 17, 17);
  67855. effect.setFloat2('centerPosition', 0.5, 0.5);
  67856. };
  67857. };
  67858. // highlights enhancing
  67859. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  67860. var _this = this;
  67861. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  67862. [], // samplers
  67863. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  67864. this._highlightsPostProcess.onApply = function (effect) {
  67865. effect.setFloat('gain', _this._highlightsGain);
  67866. effect.setFloat('threshold', _this._highlightsThreshold);
  67867. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  67868. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  67869. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  67870. };
  67871. };
  67872. // colors shifting and distortion
  67873. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  67874. var _this = this;
  67875. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  67876. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  67877. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  67878. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  67879. this._depthOfFieldPostProcess.onApply = function (effect) {
  67880. effect.setTexture("depthSampler", _this._depthTexture);
  67881. effect.setTexture("grainSampler", _this._grainTexture);
  67882. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  67883. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  67884. effect.setFloat('grain_amount', _this._grainAmount);
  67885. effect.setBool('blur_noise', _this._blurNoise);
  67886. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  67887. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  67888. effect.setFloat('distortion', _this._distortion);
  67889. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  67890. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  67891. effect.setFloat('aperture', _this._dofAperture);
  67892. effect.setFloat('darken', _this._dofDarken);
  67893. effect.setFloat('edge_blur', _this._edgeBlur);
  67894. effect.setBool('highlights', (_this._highlightsGain !== -1));
  67895. if (_this._scene.activeCamera) {
  67896. effect.setFloat('near', _this._scene.activeCamera.minZ);
  67897. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  67898. }
  67899. };
  67900. };
  67901. // creates a black and white random noise texture, 512x512
  67902. LensRenderingPipeline.prototype._createGrainTexture = function () {
  67903. var size = 512;
  67904. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  67905. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  67906. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  67907. var context = this._grainTexture.getContext();
  67908. var rand = function (min, max) {
  67909. return Math.random() * (max - min) + min;
  67910. };
  67911. var value;
  67912. for (var x = 0; x < size; x++) {
  67913. for (var y = 0; y < size; y++) {
  67914. value = Math.floor(rand(0.42, 0.58) * 255);
  67915. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  67916. context.fillRect(x, y, 1, 1);
  67917. }
  67918. }
  67919. this._grainTexture.update(false);
  67920. };
  67921. return LensRenderingPipeline;
  67922. }(BABYLON.PostProcessRenderPipeline));
  67923. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  67924. })(BABYLON || (BABYLON = {}));
  67925. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  67926. var BABYLON;
  67927. (function (BABYLON) {
  67928. var StandardRenderingPipeline = /** @class */ (function (_super) {
  67929. __extends(StandardRenderingPipeline, _super);
  67930. /**
  67931. * @constructor
  67932. * @param {string} name - The rendering pipeline name
  67933. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  67934. * @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)
  67935. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  67936. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  67937. */
  67938. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  67939. if (originalPostProcess === void 0) { originalPostProcess = null; }
  67940. var _this = _super.call(this, scene.getEngine(), name) || this;
  67941. _this.downSampleX4PostProcess = null;
  67942. _this.brightPassPostProcess = null;
  67943. _this.blurHPostProcesses = [];
  67944. _this.blurVPostProcesses = [];
  67945. _this.textureAdderPostProcess = null;
  67946. _this.volumetricLightPostProcess = null;
  67947. _this.volumetricLightSmoothXPostProcess = null;
  67948. _this.volumetricLightSmoothYPostProcess = null;
  67949. _this.volumetricLightMergePostProces = null;
  67950. _this.volumetricLightFinalPostProcess = null;
  67951. _this.luminancePostProcess = null;
  67952. _this.luminanceDownSamplePostProcesses = [];
  67953. _this.hdrPostProcess = null;
  67954. _this.textureAdderFinalPostProcess = null;
  67955. _this.lensFlareFinalPostProcess = null;
  67956. _this.hdrFinalPostProcess = null;
  67957. _this.lensFlarePostProcess = null;
  67958. _this.lensFlareComposePostProcess = null;
  67959. _this.motionBlurPostProcess = null;
  67960. _this.depthOfFieldPostProcess = null;
  67961. // Values
  67962. _this.brightThreshold = 1.0;
  67963. _this.blurWidth = 512.0;
  67964. _this.horizontalBlur = false;
  67965. _this.exposure = 1.0;
  67966. _this.lensTexture = null;
  67967. _this.volumetricLightCoefficient = 0.2;
  67968. _this.volumetricLightPower = 4.0;
  67969. _this.volumetricLightBlurScale = 64.0;
  67970. _this.sourceLight = null;
  67971. _this.hdrMinimumLuminance = 1.0;
  67972. _this.hdrDecreaseRate = 0.5;
  67973. _this.hdrIncreaseRate = 0.5;
  67974. _this.lensColorTexture = null;
  67975. _this.lensFlareStrength = 20.0;
  67976. _this.lensFlareGhostDispersal = 1.4;
  67977. _this.lensFlareHaloWidth = 0.7;
  67978. _this.lensFlareDistortionStrength = 16.0;
  67979. _this.lensStarTexture = null;
  67980. _this.lensFlareDirtTexture = null;
  67981. _this.depthOfFieldDistance = 10.0;
  67982. _this.depthOfFieldBlurWidth = 64.0;
  67983. _this.motionStrength = 1.0;
  67984. // IAnimatable
  67985. _this.animations = [];
  67986. _this._currentDepthOfFieldSource = null;
  67987. _this._hdrCurrentLuminance = 1.0;
  67988. // Getters and setters
  67989. _this._bloomEnabled = true;
  67990. _this._depthOfFieldEnabled = false;
  67991. _this._vlsEnabled = false;
  67992. _this._lensFlareEnabled = false;
  67993. _this._hdrEnabled = false;
  67994. _this._motionBlurEnabled = false;
  67995. _this._motionBlurSamples = 64.0;
  67996. _this._volumetricLightStepsCount = 50.0;
  67997. _this._cameras = cameras || [];
  67998. // Initialize
  67999. _this._scene = scene;
  68000. _this._basePostProcess = originalPostProcess;
  68001. _this._ratio = ratio;
  68002. // Misc
  68003. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  68004. // Finish
  68005. scene.postProcessRenderPipelineManager.addPipeline(_this);
  68006. _this._buildPipeline();
  68007. return _this;
  68008. }
  68009. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  68010. get: function () {
  68011. return this._bloomEnabled;
  68012. },
  68013. set: function (enabled) {
  68014. if (this._bloomEnabled === enabled) {
  68015. return;
  68016. }
  68017. this._bloomEnabled = enabled;
  68018. this._buildPipeline();
  68019. },
  68020. enumerable: true,
  68021. configurable: true
  68022. });
  68023. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  68024. get: function () {
  68025. return this._depthOfFieldEnabled;
  68026. },
  68027. set: function (enabled) {
  68028. if (this._depthOfFieldEnabled === enabled) {
  68029. return;
  68030. }
  68031. this._depthOfFieldEnabled = enabled;
  68032. this._buildPipeline();
  68033. },
  68034. enumerable: true,
  68035. configurable: true
  68036. });
  68037. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  68038. get: function () {
  68039. return this._lensFlareEnabled;
  68040. },
  68041. set: function (enabled) {
  68042. if (this._lensFlareEnabled === enabled) {
  68043. return;
  68044. }
  68045. this._lensFlareEnabled = enabled;
  68046. this._buildPipeline();
  68047. },
  68048. enumerable: true,
  68049. configurable: true
  68050. });
  68051. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  68052. get: function () {
  68053. return this._hdrEnabled;
  68054. },
  68055. set: function (enabled) {
  68056. if (this._hdrEnabled === enabled) {
  68057. return;
  68058. }
  68059. this._hdrEnabled = enabled;
  68060. this._buildPipeline();
  68061. },
  68062. enumerable: true,
  68063. configurable: true
  68064. });
  68065. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  68066. get: function () {
  68067. return this._vlsEnabled;
  68068. },
  68069. set: function (enabled) {
  68070. if (this._vlsEnabled === enabled) {
  68071. return;
  68072. }
  68073. if (enabled) {
  68074. var geometry = this._scene.enableGeometryBufferRenderer();
  68075. if (!geometry) {
  68076. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  68077. return;
  68078. }
  68079. }
  68080. this._vlsEnabled = enabled;
  68081. this._buildPipeline();
  68082. },
  68083. enumerable: true,
  68084. configurable: true
  68085. });
  68086. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  68087. get: function () {
  68088. return this._motionBlurEnabled;
  68089. },
  68090. set: function (enabled) {
  68091. if (this._motionBlurEnabled === enabled) {
  68092. return;
  68093. }
  68094. this._motionBlurEnabled = enabled;
  68095. this._buildPipeline();
  68096. },
  68097. enumerable: true,
  68098. configurable: true
  68099. });
  68100. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  68101. get: function () {
  68102. return this._volumetricLightStepsCount;
  68103. },
  68104. set: function (count) {
  68105. if (this.volumetricLightPostProcess) {
  68106. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  68107. }
  68108. this._volumetricLightStepsCount = count;
  68109. },
  68110. enumerable: true,
  68111. configurable: true
  68112. });
  68113. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  68114. get: function () {
  68115. return this._motionBlurSamples;
  68116. },
  68117. set: function (samples) {
  68118. if (this.motionBlurPostProcess) {
  68119. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  68120. }
  68121. this._motionBlurSamples = samples;
  68122. },
  68123. enumerable: true,
  68124. configurable: true
  68125. });
  68126. StandardRenderingPipeline.prototype._buildPipeline = function () {
  68127. var _this = this;
  68128. var ratio = this._ratio;
  68129. var scene = this._scene;
  68130. this._disposePostProcesses();
  68131. this._reset();
  68132. // Create pass post-process
  68133. if (!this._basePostProcess) {
  68134. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  68135. this.originalPostProcess.onApply = function (effect) {
  68136. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  68137. };
  68138. }
  68139. else {
  68140. this.originalPostProcess = this._basePostProcess;
  68141. }
  68142. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  68143. this._currentDepthOfFieldSource = this.originalPostProcess;
  68144. if (this._vlsEnabled) {
  68145. // Create volumetric light
  68146. this._createVolumetricLightPostProcess(scene, ratio);
  68147. // Create volumetric light final post-process
  68148. 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);
  68149. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  68150. }
  68151. if (this._bloomEnabled) {
  68152. // Create down sample X4 post-process
  68153. this._createDownSampleX4PostProcess(scene, ratio / 2);
  68154. // Create bright pass post-process
  68155. this._createBrightPassPostProcess(scene, ratio / 2);
  68156. // Create gaussian blur post-processes (down sampling blurs)
  68157. this._createBlurPostProcesses(scene, ratio / 4, 1);
  68158. // Create texture adder post-process
  68159. this._createTextureAdderPostProcess(scene, ratio);
  68160. // Create depth-of-field source post-process
  68161. 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);
  68162. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  68163. }
  68164. if (this._lensFlareEnabled) {
  68165. // Create lens flare post-process
  68166. this._createLensFlarePostProcess(scene, ratio);
  68167. // Create depth-of-field source post-process post lens-flare and disable it now
  68168. 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);
  68169. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  68170. }
  68171. if (this._hdrEnabled) {
  68172. // Create luminance
  68173. this._createLuminancePostProcesses(scene, this._floatTextureType);
  68174. // Create HDR
  68175. this._createHdrPostProcess(scene, ratio);
  68176. // Create depth-of-field source post-process post hdr and disable it now
  68177. 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);
  68178. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  68179. }
  68180. if (this._depthOfFieldEnabled) {
  68181. // Create gaussian blur used by depth-of-field
  68182. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  68183. // Create depth-of-field post-process
  68184. this._createDepthOfFieldPostProcess(scene, ratio);
  68185. }
  68186. if (this._motionBlurEnabled) {
  68187. // Create motion blur post-process
  68188. this._createMotionBlurPostProcess(scene, ratio);
  68189. }
  68190. if (this._cameras !== null) {
  68191. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  68192. }
  68193. };
  68194. // Down Sample X4 Post-Processs
  68195. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  68196. var _this = this;
  68197. var downSampleX4Offsets = new Array(32);
  68198. 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);
  68199. this.downSampleX4PostProcess.onApply = function (effect) {
  68200. var id = 0;
  68201. var width = _this.downSampleX4PostProcess.width;
  68202. var height = _this.downSampleX4PostProcess.height;
  68203. for (var i = -2; i < 2; i++) {
  68204. for (var j = -2; j < 2; j++) {
  68205. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  68206. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  68207. id += 2;
  68208. }
  68209. }
  68210. effect.setArray2("dsOffsets", downSampleX4Offsets);
  68211. };
  68212. // Add to pipeline
  68213. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  68214. };
  68215. // Brightpass Post-Process
  68216. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  68217. var _this = this;
  68218. var brightOffsets = new Array(8);
  68219. 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);
  68220. this.brightPassPostProcess.onApply = function (effect) {
  68221. var sU = (1.0 / _this.brightPassPostProcess.width);
  68222. var sV = (1.0 / _this.brightPassPostProcess.height);
  68223. brightOffsets[0] = -0.5 * sU;
  68224. brightOffsets[1] = 0.5 * sV;
  68225. brightOffsets[2] = 0.5 * sU;
  68226. brightOffsets[3] = 0.5 * sV;
  68227. brightOffsets[4] = -0.5 * sU;
  68228. brightOffsets[5] = -0.5 * sV;
  68229. brightOffsets[6] = 0.5 * sU;
  68230. brightOffsets[7] = -0.5 * sV;
  68231. effect.setArray2("dsOffsets", brightOffsets);
  68232. effect.setFloat("brightThreshold", _this.brightThreshold);
  68233. };
  68234. // Add to pipeline
  68235. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  68236. };
  68237. // Create blur H&V post-processes
  68238. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  68239. var _this = this;
  68240. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  68241. var engine = scene.getEngine();
  68242. 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);
  68243. 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);
  68244. blurX.onActivateObservable.add(function () {
  68245. var dw = blurX.width / engine.getRenderWidth();
  68246. blurX.kernel = _this[blurWidthKey] * dw;
  68247. });
  68248. blurY.onActivateObservable.add(function () {
  68249. var dw = blurY.height / engine.getRenderHeight();
  68250. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  68251. });
  68252. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  68253. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  68254. this.blurHPostProcesses.push(blurX);
  68255. this.blurVPostProcesses.push(blurY);
  68256. };
  68257. // Create texture adder post-process
  68258. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  68259. var _this = this;
  68260. 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);
  68261. this.textureAdderPostProcess.onApply = function (effect) {
  68262. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  68263. effect.setTexture("lensSampler", _this.lensTexture);
  68264. effect.setFloat("exposure", _this.exposure);
  68265. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  68266. };
  68267. // Add to pipeline
  68268. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  68269. };
  68270. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  68271. var _this = this;
  68272. var geometryRenderer = scene.enableGeometryBufferRenderer();
  68273. geometryRenderer.enablePosition = true;
  68274. var geometry = geometryRenderer.getGBuffer();
  68275. // Base post-process
  68276. 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));
  68277. var depthValues = BABYLON.Vector2.Zero();
  68278. this.volumetricLightPostProcess.onApply = function (effect) {
  68279. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  68280. var generator = _this.sourceLight.getShadowGenerator();
  68281. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  68282. effect.setTexture("positionSampler", geometry.textures[2]);
  68283. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  68284. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  68285. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  68286. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  68287. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  68288. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  68289. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  68290. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  68291. effect.setVector2("depthValues", depthValues);
  68292. }
  68293. };
  68294. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  68295. // Smooth
  68296. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  68297. // Merge
  68298. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  68299. this.volumetricLightMergePostProces.onApply = function (effect) {
  68300. effect.setTextureFromPostProcess("originalSampler", _this.originalPostProcess);
  68301. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  68302. };
  68303. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  68304. };
  68305. // Create luminance
  68306. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  68307. var _this = this;
  68308. // Create luminance
  68309. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  68310. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  68311. var offsets = [];
  68312. this.luminancePostProcess.onApply = function (effect) {
  68313. var sU = (1.0 / _this.luminancePostProcess.width);
  68314. var sV = (1.0 / _this.luminancePostProcess.height);
  68315. offsets[0] = -0.5 * sU;
  68316. offsets[1] = 0.5 * sV;
  68317. offsets[2] = 0.5 * sU;
  68318. offsets[3] = 0.5 * sV;
  68319. offsets[4] = -0.5 * sU;
  68320. offsets[5] = -0.5 * sV;
  68321. offsets[6] = 0.5 * sU;
  68322. offsets[7] = -0.5 * sV;
  68323. effect.setArray2("lumOffsets", offsets);
  68324. };
  68325. // Add to pipeline
  68326. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  68327. // Create down sample luminance
  68328. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  68329. var size = Math.pow(3, i);
  68330. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  68331. if (i === 0) {
  68332. defines += "#define FINAL_DOWN_SAMPLER";
  68333. }
  68334. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  68335. this.luminanceDownSamplePostProcesses.push(postProcess);
  68336. }
  68337. // Create callbacks and add effects
  68338. var lastLuminance = this.luminancePostProcess;
  68339. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  68340. var downSampleOffsets = new Array(18);
  68341. pp.onApply = function (effect) {
  68342. if (!lastLuminance) {
  68343. return;
  68344. }
  68345. var id = 0;
  68346. for (var x = -1; x < 2; x++) {
  68347. for (var y = -1; y < 2; y++) {
  68348. downSampleOffsets[id] = x / lastLuminance.width;
  68349. downSampleOffsets[id + 1] = y / lastLuminance.height;
  68350. id += 2;
  68351. }
  68352. }
  68353. effect.setArray2("dsOffsets", downSampleOffsets);
  68354. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  68355. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  68356. lastLuminance = _this.luminancePostProcess;
  68357. }
  68358. else {
  68359. lastLuminance = pp;
  68360. }
  68361. };
  68362. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  68363. pp.onAfterRender = function (effect) {
  68364. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  68365. 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);
  68366. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  68367. };
  68368. }
  68369. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  68370. });
  68371. };
  68372. // Create HDR post-process
  68373. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  68374. var _this = this;
  68375. 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);
  68376. var outputLiminance = 1;
  68377. var time = 0;
  68378. var lastTime = 0;
  68379. this.hdrPostProcess.onApply = function (effect) {
  68380. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  68381. time += scene.getEngine().getDeltaTime();
  68382. if (outputLiminance < 0) {
  68383. outputLiminance = _this._hdrCurrentLuminance;
  68384. }
  68385. else {
  68386. var dt = (lastTime - time) / 1000.0;
  68387. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  68388. outputLiminance += _this.hdrDecreaseRate * dt;
  68389. }
  68390. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  68391. outputLiminance -= _this.hdrIncreaseRate * dt;
  68392. }
  68393. else {
  68394. outputLiminance = _this._hdrCurrentLuminance;
  68395. }
  68396. }
  68397. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  68398. effect.setFloat("averageLuminance", outputLiminance);
  68399. lastTime = time;
  68400. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  68401. };
  68402. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  68403. };
  68404. // Create lens flare post-process
  68405. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  68406. var _this = this;
  68407. 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);
  68408. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  68409. this._createBlurPostProcesses(scene, ratio / 4, 2);
  68410. 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);
  68411. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  68412. var resolution = new BABYLON.Vector2(0, 0);
  68413. // Lens flare
  68414. this.lensFlarePostProcess.onApply = function (effect) {
  68415. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  68416. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  68417. effect.setFloat("strength", _this.lensFlareStrength);
  68418. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  68419. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  68420. // Shift
  68421. resolution.x = _this.lensFlarePostProcess.width;
  68422. resolution.y = _this.lensFlarePostProcess.height;
  68423. effect.setVector2("resolution", resolution);
  68424. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  68425. };
  68426. // Compose
  68427. 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);
  68428. 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);
  68429. this.lensFlareComposePostProcess.onApply = function (effect) {
  68430. if (!_this._scene.activeCamera) {
  68431. return;
  68432. }
  68433. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  68434. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  68435. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  68436. // Lens start rotation matrix
  68437. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  68438. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  68439. 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));
  68440. camRot *= 4.0;
  68441. 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);
  68442. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  68443. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  68444. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  68445. };
  68446. };
  68447. // Create depth-of-field post-process
  68448. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  68449. var _this = this;
  68450. 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);
  68451. this.depthOfFieldPostProcess.onApply = function (effect) {
  68452. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  68453. effect.setTexture("depthSampler", _this._getDepthTexture());
  68454. effect.setFloat("distance", _this.depthOfFieldDistance);
  68455. };
  68456. // Add to pipeline
  68457. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  68458. };
  68459. // Create motion blur post-process
  68460. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  68461. var _this = this;
  68462. 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);
  68463. var motionScale = 0;
  68464. var prevViewProjection = BABYLON.Matrix.Identity();
  68465. var invViewProjection = BABYLON.Matrix.Identity();
  68466. var viewProjection = BABYLON.Matrix.Identity();
  68467. var screenSize = BABYLON.Vector2.Zero();
  68468. this.motionBlurPostProcess.onApply = function (effect) {
  68469. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  68470. viewProjection.invertToRef(invViewProjection);
  68471. effect.setMatrix("inverseViewProjection", invViewProjection);
  68472. effect.setMatrix("prevViewProjection", prevViewProjection);
  68473. prevViewProjection = viewProjection;
  68474. screenSize.x = _this.motionBlurPostProcess.width;
  68475. screenSize.y = _this.motionBlurPostProcess.height;
  68476. effect.setVector2("screenSize", screenSize);
  68477. motionScale = scene.getEngine().getFps() / 60.0;
  68478. effect.setFloat("motionScale", motionScale);
  68479. effect.setFloat("motionStrength", _this.motionStrength);
  68480. effect.setTexture("depthSampler", _this._getDepthTexture());
  68481. };
  68482. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  68483. };
  68484. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  68485. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  68486. var renderer = this._scene.enableGeometryBufferRenderer();
  68487. return renderer.getGBuffer().textures[0];
  68488. }
  68489. return this._scene.enableDepthRenderer().getDepthMap();
  68490. };
  68491. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  68492. for (var i = 0; i < this._cameras.length; i++) {
  68493. var camera = this._cameras[i];
  68494. if (this.originalPostProcess) {
  68495. this.originalPostProcess.dispose(camera);
  68496. }
  68497. if (this.downSampleX4PostProcess) {
  68498. this.downSampleX4PostProcess.dispose(camera);
  68499. }
  68500. if (this.brightPassPostProcess) {
  68501. this.brightPassPostProcess.dispose(camera);
  68502. }
  68503. if (this.textureAdderPostProcess) {
  68504. this.textureAdderPostProcess.dispose(camera);
  68505. }
  68506. if (this.textureAdderFinalPostProcess) {
  68507. this.textureAdderFinalPostProcess.dispose(camera);
  68508. }
  68509. if (this.volumetricLightPostProcess) {
  68510. this.volumetricLightPostProcess.dispose(camera);
  68511. }
  68512. if (this.volumetricLightSmoothXPostProcess) {
  68513. this.volumetricLightSmoothXPostProcess.dispose(camera);
  68514. }
  68515. if (this.volumetricLightSmoothYPostProcess) {
  68516. this.volumetricLightSmoothYPostProcess.dispose(camera);
  68517. }
  68518. if (this.volumetricLightMergePostProces) {
  68519. this.volumetricLightMergePostProces.dispose(camera);
  68520. }
  68521. if (this.volumetricLightFinalPostProcess) {
  68522. this.volumetricLightFinalPostProcess.dispose(camera);
  68523. }
  68524. if (this.lensFlarePostProcess) {
  68525. this.lensFlarePostProcess.dispose(camera);
  68526. }
  68527. if (this.lensFlareComposePostProcess) {
  68528. this.lensFlareComposePostProcess.dispose(camera);
  68529. }
  68530. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  68531. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  68532. }
  68533. if (this.luminancePostProcess) {
  68534. this.luminancePostProcess.dispose(camera);
  68535. }
  68536. if (this.hdrPostProcess) {
  68537. this.hdrPostProcess.dispose(camera);
  68538. }
  68539. if (this.hdrFinalPostProcess) {
  68540. this.hdrFinalPostProcess.dispose(camera);
  68541. }
  68542. if (this.depthOfFieldPostProcess) {
  68543. this.depthOfFieldPostProcess.dispose(camera);
  68544. }
  68545. if (this.motionBlurPostProcess) {
  68546. this.motionBlurPostProcess.dispose(camera);
  68547. }
  68548. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  68549. this.blurHPostProcesses[j].dispose(camera);
  68550. }
  68551. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  68552. this.blurVPostProcesses[j].dispose(camera);
  68553. }
  68554. }
  68555. this.originalPostProcess = null;
  68556. this.downSampleX4PostProcess = null;
  68557. this.brightPassPostProcess = null;
  68558. this.textureAdderPostProcess = null;
  68559. this.textureAdderFinalPostProcess = null;
  68560. this.volumetricLightPostProcess = null;
  68561. this.volumetricLightSmoothXPostProcess = null;
  68562. this.volumetricLightSmoothYPostProcess = null;
  68563. this.volumetricLightMergePostProces = null;
  68564. this.volumetricLightFinalPostProcess = null;
  68565. this.lensFlarePostProcess = null;
  68566. this.lensFlareComposePostProcess = null;
  68567. this.luminancePostProcess = null;
  68568. this.hdrPostProcess = null;
  68569. this.hdrFinalPostProcess = null;
  68570. this.depthOfFieldPostProcess = null;
  68571. this.motionBlurPostProcess = null;
  68572. this.luminanceDownSamplePostProcesses = [];
  68573. this.blurHPostProcesses = [];
  68574. this.blurVPostProcesses = [];
  68575. };
  68576. // Dispose
  68577. StandardRenderingPipeline.prototype.dispose = function () {
  68578. this._disposePostProcesses();
  68579. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  68580. _super.prototype.dispose.call(this);
  68581. };
  68582. // Serialize rendering pipeline
  68583. StandardRenderingPipeline.prototype.serialize = function () {
  68584. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  68585. serializationObject.customType = "StandardRenderingPipeline";
  68586. return serializationObject;
  68587. };
  68588. /**
  68589. * Static members
  68590. */
  68591. // Parse serialized pipeline
  68592. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  68593. return BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  68594. };
  68595. // Luminance steps
  68596. StandardRenderingPipeline.LuminanceSteps = 6;
  68597. __decorate([
  68598. BABYLON.serialize()
  68599. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  68600. __decorate([
  68601. BABYLON.serialize()
  68602. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  68603. __decorate([
  68604. BABYLON.serialize()
  68605. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  68606. __decorate([
  68607. BABYLON.serialize()
  68608. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  68609. __decorate([
  68610. BABYLON.serializeAsTexture("lensTexture")
  68611. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  68612. __decorate([
  68613. BABYLON.serialize()
  68614. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  68615. __decorate([
  68616. BABYLON.serialize()
  68617. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  68618. __decorate([
  68619. BABYLON.serialize()
  68620. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  68621. __decorate([
  68622. BABYLON.serialize()
  68623. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  68624. __decorate([
  68625. BABYLON.serialize()
  68626. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  68627. __decorate([
  68628. BABYLON.serialize()
  68629. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  68630. __decorate([
  68631. BABYLON.serializeAsTexture("lensColorTexture")
  68632. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  68633. __decorate([
  68634. BABYLON.serialize()
  68635. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  68636. __decorate([
  68637. BABYLON.serialize()
  68638. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  68639. __decorate([
  68640. BABYLON.serialize()
  68641. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  68642. __decorate([
  68643. BABYLON.serialize()
  68644. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  68645. __decorate([
  68646. BABYLON.serializeAsTexture("lensStarTexture")
  68647. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  68648. __decorate([
  68649. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  68650. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  68651. __decorate([
  68652. BABYLON.serialize()
  68653. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  68654. __decorate([
  68655. BABYLON.serialize()
  68656. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  68657. __decorate([
  68658. BABYLON.serialize()
  68659. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  68660. __decorate([
  68661. BABYLON.serialize()
  68662. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  68663. __decorate([
  68664. BABYLON.serialize()
  68665. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  68666. __decorate([
  68667. BABYLON.serialize()
  68668. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  68669. __decorate([
  68670. BABYLON.serialize()
  68671. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  68672. __decorate([
  68673. BABYLON.serialize()
  68674. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  68675. __decorate([
  68676. BABYLON.serialize()
  68677. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  68678. __decorate([
  68679. BABYLON.serialize()
  68680. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  68681. __decorate([
  68682. BABYLON.serialize()
  68683. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  68684. __decorate([
  68685. BABYLON.serialize()
  68686. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  68687. return StandardRenderingPipeline;
  68688. }(BABYLON.PostProcessRenderPipeline));
  68689. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  68690. })(BABYLON || (BABYLON = {}));
  68691. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  68692. var BABYLON;
  68693. (function (BABYLON) {
  68694. var FxaaPostProcess = /** @class */ (function (_super) {
  68695. __extends(FxaaPostProcess, _super);
  68696. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  68697. if (camera === void 0) { camera = null; }
  68698. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  68699. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa") || this;
  68700. _this.onApplyObservable.add(function (effect) {
  68701. var texelSize = _this.texelSize;
  68702. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  68703. });
  68704. return _this;
  68705. }
  68706. return FxaaPostProcess;
  68707. }(BABYLON.PostProcess));
  68708. BABYLON.FxaaPostProcess = FxaaPostProcess;
  68709. })(BABYLON || (BABYLON = {}));
  68710. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  68711. var BABYLON;
  68712. (function (BABYLON) {
  68713. /**
  68714. * The ChromaticAberrationPostProcess separates the rgb channels in an image to produce chromatic distortion around the edges of the screen
  68715. */
  68716. var ChromaticAberrationPostProcess = /** @class */ (function (_super) {
  68717. __extends(ChromaticAberrationPostProcess, _super);
  68718. /**
  68719. * Creates a new instance of @see ChromaticAberrationPostProcess
  68720. * @param name The name of the effect.
  68721. * @param screenWidth The width of the screen to apply the effect on.
  68722. * @param screenHeight The height of the screen to apply the effect on.
  68723. * @param options The required width/height ratio to downsize to before computing the render pass.
  68724. * @param camera The camera to apply the render pass to.
  68725. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  68726. * @param engine The engine which the post process will be applied. (default: current engine)
  68727. * @param reusable If the post process can be reused on the same frame. (default: false)
  68728. * @param textureType Type of textures used when performing the post process. (default: 0)
  68729. * @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)
  68730. */
  68731. function ChromaticAberrationPostProcess(name, screenWidth, screenHeight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  68732. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  68733. if (blockCompilation === void 0) { blockCompilation = false; }
  68734. 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;
  68735. /**
  68736. * The amount of seperation of rgb channels (default: 30)
  68737. */
  68738. _this.aberrationAmount = 30;
  68739. /**
  68740. * The amount the effect will increase for pixels closer to the edge of the screen. (default: 0)
  68741. */
  68742. _this.radialIntensity = 0;
  68743. /**
  68744. * 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))
  68745. */
  68746. _this.direction = new BABYLON.Vector2(0.707, 0.707);
  68747. /**
  68748. * 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))
  68749. */
  68750. _this.centerPosition = new BABYLON.Vector2(0.5, 0.5);
  68751. _this.onApplyObservable.add(function (effect) {
  68752. effect.setFloat('chromatic_aberration', _this.aberrationAmount);
  68753. effect.setFloat('screen_width', screenWidth);
  68754. effect.setFloat('screen_height', screenHeight);
  68755. effect.setFloat('radialIntensity', _this.radialIntensity);
  68756. effect.setFloat2('direction', _this.direction.x, _this.direction.y);
  68757. effect.setFloat2('centerPosition', _this.centerPosition.x, _this.centerPosition.y);
  68758. });
  68759. return _this;
  68760. }
  68761. return ChromaticAberrationPostProcess;
  68762. }(BABYLON.PostProcess));
  68763. BABYLON.ChromaticAberrationPostProcess = ChromaticAberrationPostProcess;
  68764. })(BABYLON || (BABYLON = {}));
  68765. //# sourceMappingURL=babylon.chromaticAberrationPostProcess.js.map
  68766. var BABYLON;
  68767. (function (BABYLON) {
  68768. /**
  68769. * The SharpenPostProcess applies a sharpen kernel to every pixel
  68770. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  68771. */
  68772. var SharpenPostProcess = /** @class */ (function (_super) {
  68773. __extends(SharpenPostProcess, _super);
  68774. /**
  68775. * Creates a new instance of @see ConvolutionPostProcess
  68776. * @param name The name of the effect.
  68777. * @param options The required width/height ratio to downsize to before computing the render pass.
  68778. * @param camera The camera to apply the render pass to.
  68779. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  68780. * @param engine The engine which the post process will be applied. (default: current engine)
  68781. * @param reusable If the post process can be reused on the same frame. (default: false)
  68782. * @param textureType Type of textures used when performing the post process. (default: 0)
  68783. * @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)
  68784. */
  68785. function SharpenPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  68786. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  68787. if (blockCompilation === void 0) { blockCompilation = false; }
  68788. var _this = _super.call(this, name, "sharpen", ["sharpnessAmounts", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  68789. /**
  68790. * How much of the original color should be applied. Setting this to 0 will display edge detection. (default: 1)
  68791. */
  68792. _this.colorAmount = 1.0;
  68793. /**
  68794. * How much sharpness should be applied (default: 0.3)
  68795. */
  68796. _this.edgeAmount = 0.3;
  68797. _this.onApply = function (effect) {
  68798. effect.setFloat2("screenSize", _this.width, _this.height);
  68799. effect.setFloat2("sharpnessAmounts", _this.edgeAmount, _this.colorAmount);
  68800. };
  68801. return _this;
  68802. }
  68803. return SharpenPostProcess;
  68804. }(BABYLON.PostProcess));
  68805. BABYLON.SharpenPostProcess = SharpenPostProcess;
  68806. })(BABYLON || (BABYLON = {}));
  68807. //# sourceMappingURL=babylon.sharpenPostProcess.js.map
  68808. var BABYLON;
  68809. (function (BABYLON) {
  68810. /**
  68811. * The Blur Post Process which blurs an image based on a kernel and direction.
  68812. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  68813. */
  68814. var BlurPostProcess = /** @class */ (function (_super) {
  68815. __extends(BlurPostProcess, _super);
  68816. /**
  68817. * Creates a new instance of @see BlurPostProcess
  68818. * @param name The name of the effect.
  68819. * @param direction The direction in which to blur the image.
  68820. * @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.
  68821. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  68822. * @param camera The camera to apply the render pass to.
  68823. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  68824. * @param engine The engine which the post process will be applied. (default: current engine)
  68825. * @param reusable If the post process can be reused on the same frame. (default: false)
  68826. * @param textureType Type of textures used when performing the post process. (default: 0)
  68827. * @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)
  68828. */
  68829. function BlurPostProcess(name, /** The direction in which to blur the image. */ direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines, blockCompilation) {
  68830. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  68831. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  68832. if (defines === void 0) { defines = ""; }
  68833. if (blockCompilation === void 0) { blockCompilation = false; }
  68834. 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;
  68835. _this.direction = direction;
  68836. _this.blockCompilation = blockCompilation;
  68837. _this._packedFloat = false;
  68838. _this._staticDefines = "";
  68839. _this._staticDefines = defines;
  68840. _this.onApplyObservable.add(function (effect) {
  68841. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  68842. });
  68843. _this.kernel = kernel;
  68844. return _this;
  68845. }
  68846. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  68847. /**
  68848. * Gets the length in pixels of the blur sample region
  68849. */
  68850. get: function () {
  68851. return this._idealKernel;
  68852. },
  68853. /**
  68854. * Sets the length in pixels of the blur sample region
  68855. */
  68856. set: function (v) {
  68857. if (this._idealKernel === v) {
  68858. return;
  68859. }
  68860. v = Math.max(v, 1);
  68861. this._idealKernel = v;
  68862. this._kernel = this._nearestBestKernel(v);
  68863. if (!this.blockCompilation) {
  68864. this._updateParameters();
  68865. }
  68866. },
  68867. enumerable: true,
  68868. configurable: true
  68869. });
  68870. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  68871. /**
  68872. * Gets wether or not the blur is unpacking/repacking floats
  68873. */
  68874. get: function () {
  68875. return this._packedFloat;
  68876. },
  68877. /**
  68878. * Sets wether or not the blur needs to unpack/repack floats
  68879. */
  68880. set: function (v) {
  68881. if (this._packedFloat === v) {
  68882. return;
  68883. }
  68884. this._packedFloat = v;
  68885. if (!this.blockCompilation) {
  68886. this._updateParameters();
  68887. }
  68888. },
  68889. enumerable: true,
  68890. configurable: true
  68891. });
  68892. /**
  68893. * Updates the effect with the current post process compile time values and recompiles the shader.
  68894. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  68895. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  68896. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  68897. * @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
  68898. * @param onCompiled Called when the shader has been compiled.
  68899. * @param onError Called if there is an error when compiling a shader.
  68900. */
  68901. BlurPostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  68902. if (defines === void 0) { defines = null; }
  68903. if (uniforms === void 0) { uniforms = null; }
  68904. if (samplers === void 0) { samplers = null; }
  68905. this._updateParameters(onCompiled, onError);
  68906. };
  68907. BlurPostProcess.prototype._updateParameters = function (onCompiled, onError) {
  68908. // Generate sampling offsets and weights
  68909. var N = this._kernel;
  68910. var centerIndex = (N - 1) / 2;
  68911. // Generate Gaussian sampling weights over kernel
  68912. var offsets = [];
  68913. var weights = [];
  68914. var totalWeight = 0;
  68915. for (var i = 0; i < N; i++) {
  68916. var u = i / (N - 1);
  68917. var w = this._gaussianWeight(u * 2.0 - 1);
  68918. offsets[i] = (i - centerIndex);
  68919. weights[i] = w;
  68920. totalWeight += w;
  68921. }
  68922. // Normalize weights
  68923. for (var i = 0; i < weights.length; i++) {
  68924. weights[i] /= totalWeight;
  68925. }
  68926. // Optimize: combine samples to take advantage of hardware linear sampling
  68927. // Walk from left to center, combining pairs (symmetrically)
  68928. var linearSamplingWeights = [];
  68929. var linearSamplingOffsets = [];
  68930. var linearSamplingMap = [];
  68931. for (var i = 0; i <= centerIndex; i += 2) {
  68932. var j = Math.min(i + 1, Math.floor(centerIndex));
  68933. var singleCenterSample = i === j;
  68934. if (singleCenterSample) {
  68935. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  68936. }
  68937. else {
  68938. var sharedCell = j === centerIndex;
  68939. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  68940. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  68941. if (offsetLinear === 0) {
  68942. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  68943. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  68944. }
  68945. else {
  68946. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  68947. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  68948. }
  68949. }
  68950. }
  68951. for (var i = 0; i < linearSamplingMap.length; i++) {
  68952. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  68953. linearSamplingWeights[i] = linearSamplingMap[i].w;
  68954. }
  68955. // Replace with optimized
  68956. offsets = linearSamplingOffsets;
  68957. weights = linearSamplingWeights;
  68958. // Generate shaders
  68959. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  68960. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  68961. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  68962. var defines = "";
  68963. defines += this._staticDefines;
  68964. for (var i = 0; i < varyingCount; i++) {
  68965. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  68966. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  68967. }
  68968. var depCount = 0;
  68969. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  68970. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  68971. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  68972. depCount++;
  68973. }
  68974. if (this.packedFloat) {
  68975. defines += "#define PACKEDFLOAT 1";
  68976. }
  68977. _super.prototype.updateEffect.call(this, defines, null, null, {
  68978. varyingCount: varyingCount,
  68979. depCount: depCount
  68980. }, onCompiled, onError);
  68981. };
  68982. /**
  68983. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  68984. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  68985. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  68986. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  68987. * The gaps between physical kernels are compensated for in the weighting of the samples
  68988. * @param idealKernel Ideal blur kernel.
  68989. * @return Nearest best kernel.
  68990. */
  68991. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  68992. var v = Math.round(idealKernel);
  68993. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  68994. var k = _a[_i];
  68995. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  68996. return Math.max(k, 3);
  68997. }
  68998. }
  68999. return Math.max(v, 3);
  69000. };
  69001. /**
  69002. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  69003. * @param x The point on the Gaussian distribution to sample.
  69004. * @return the value of the Gaussian function at x.
  69005. */
  69006. BlurPostProcess.prototype._gaussianWeight = function (x) {
  69007. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  69008. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  69009. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  69010. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  69011. // truncated at around 1.3% of peak strength.
  69012. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  69013. var sigma = (1 / 3);
  69014. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  69015. var exponent = -((x * x) / (2.0 * sigma * sigma));
  69016. var weight = (1.0 / denominator) * Math.exp(exponent);
  69017. return weight;
  69018. };
  69019. /**
  69020. * Generates a string that can be used as a floating point number in GLSL.
  69021. * @param x Value to print.
  69022. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  69023. * @return GLSL float string.
  69024. */
  69025. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  69026. if (decimalFigures === void 0) { decimalFigures = 8; }
  69027. return x.toFixed(decimalFigures).replace(/0+$/, '');
  69028. };
  69029. return BlurPostProcess;
  69030. }(BABYLON.PostProcess));
  69031. BABYLON.BlurPostProcess = BlurPostProcess;
  69032. })(BABYLON || (BABYLON = {}));
  69033. //# sourceMappingURL=babylon.blurPostProcess.js.map
  69034. var BABYLON;
  69035. (function (BABYLON) {
  69036. /**
  69037. * The DepthOfFieldBlurPostProcess applied a blur in a give direction.
  69038. * This blur differs from the standard BlurPostProcess as it attempts to avoid blurring pixels
  69039. * based on samples that have a large difference in distance than the center pixel.
  69040. * See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  69041. */
  69042. var DepthOfFieldBlurPostProcess = /** @class */ (function (_super) {
  69043. __extends(DepthOfFieldBlurPostProcess, _super);
  69044. /**
  69045. * Creates a new instance of @see CircleOfConfusionPostProcess
  69046. * @param name The name of the effect.
  69047. * @param scene The scene the effect belongs to.
  69048. * @param direction The direction the blur should be applied.
  69049. * @param kernel The size of the kernel used to blur.
  69050. * @param options The required width/height ratio to downsize to before computing the render pass.
  69051. * @param camera The camera to apply the render pass to.
  69052. * @param circleOfConfusion The circle of confusion + depth map to be used to avoid blurring accross edges
  69053. * @param imageToBlur The image to apply the blur to (default: Current rendered frame)
  69054. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  69055. * @param engine The engine which the post process will be applied. (default: current engine)
  69056. * @param reusable If the post process can be reused on the same frame. (default: false)
  69057. * @param textureType Type of textures used when performing the post process. (default: 0)
  69058. * @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)
  69059. */
  69060. function DepthOfFieldBlurPostProcess(name, scene, direction, kernel, options, camera, circleOfConfusion, imageToBlur, samplingMode, engine, reusable, textureType, blockCompilation) {
  69061. if (imageToBlur === void 0) { imageToBlur = null; }
  69062. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  69063. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69064. if (blockCompilation === void 0) { blockCompilation = false; }
  69065. 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;
  69066. _this.direction = direction;
  69067. _this.onApplyObservable.add(function (effect) {
  69068. if (imageToBlur != null) {
  69069. effect.setTextureFromPostProcess("textureSampler", imageToBlur);
  69070. }
  69071. effect.setTextureFromPostProcess("circleOfConfusionSampler", circleOfConfusion);
  69072. if (scene.activeCamera) {
  69073. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  69074. }
  69075. });
  69076. return _this;
  69077. }
  69078. return DepthOfFieldBlurPostProcess;
  69079. }(BABYLON.BlurPostProcess));
  69080. BABYLON.DepthOfFieldBlurPostProcess = DepthOfFieldBlurPostProcess;
  69081. })(BABYLON || (BABYLON = {}));
  69082. //# sourceMappingURL=babylon.depthOfFieldBlurPostProcess.js.map
  69083. var BABYLON;
  69084. (function (BABYLON) {
  69085. /**
  69086. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  69087. */
  69088. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  69089. __extends(DepthOfFieldMergePostProcess, _super);
  69090. /**
  69091. * Creates a new instance of @see CircleOfConfusionPostProcess
  69092. * @param name The name of the effect.
  69093. * @param original The non-blurred image to be modified
  69094. * @param circleOfConfusion The circle of confusion post process that will determine how blurred each pixel should become.
  69095. * @param blurSteps Incrimental bluring post processes.
  69096. * @param options The required width/height ratio to downsize to before computing the render pass.
  69097. * @param camera The camera to apply the render pass to.
  69098. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  69099. * @param engine The engine which the post process will be applied. (default: current engine)
  69100. * @param reusable If the post process can be reused on the same frame. (default: false)
  69101. * @param textureType Type of textures used when performing the post process. (default: 0)
  69102. * @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)
  69103. */
  69104. function DepthOfFieldMergePostProcess(name, original, circleOfConfusion, blurSteps, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  69105. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69106. if (blockCompilation === void 0) { blockCompilation = false; }
  69107. var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "originalSampler", "blurStep1", "blurStep2"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  69108. _this.blurSteps = blurSteps;
  69109. _this.onApplyObservable.add(function (effect) {
  69110. effect.setTextureFromPostProcess("circleOfConfusionSampler", circleOfConfusion);
  69111. effect.setTextureFromPostProcess("originalSampler", original);
  69112. blurSteps.forEach(function (step, index) {
  69113. effect.setTextureFromPostProcess("blurStep" + (index + 1), step);
  69114. });
  69115. });
  69116. if (!blockCompilation) {
  69117. _this.updateEffect();
  69118. }
  69119. return _this;
  69120. }
  69121. /**
  69122. * Updates the effect with the current post process compile time values and recompiles the shader.
  69123. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  69124. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  69125. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  69126. * @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
  69127. * @param onCompiled Called when the shader has been compiled.
  69128. * @param onError Called if there is an error when compiling a shader.
  69129. */
  69130. DepthOfFieldMergePostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  69131. if (defines === void 0) { defines = null; }
  69132. if (uniforms === void 0) { uniforms = null; }
  69133. if (samplers === void 0) { samplers = null; }
  69134. _super.prototype.updateEffect.call(this, defines ? defines : "#define BLUR_LEVEL " + this.blurSteps.length + "\n", uniforms, samplers, indexParameters, onCompiled, onError);
  69135. };
  69136. return DepthOfFieldMergePostProcess;
  69137. }(BABYLON.PostProcess));
  69138. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  69139. })(BABYLON || (BABYLON = {}));
  69140. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  69141. var BABYLON;
  69142. (function (BABYLON) {
  69143. /**
  69144. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  69145. */
  69146. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  69147. __extends(CircleOfConfusionPostProcess, _super);
  69148. /**
  69149. * Creates a new instance of @see CircleOfConfusionPostProcess
  69150. * @param name The name of the effect.
  69151. * @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.
  69152. * @param options The required width/height ratio to downsize to before computing the render pass.
  69153. * @param camera The camera to apply the render pass to.
  69154. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  69155. * @param engine The engine which the post process will be applied. (default: current engine)
  69156. * @param reusable If the post process can be reused on the same frame. (default: false)
  69157. * @param textureType Type of textures used when performing the post process. (default: 0)
  69158. * @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)
  69159. */
  69160. function CircleOfConfusionPostProcess(name, depthTexture, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  69161. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69162. if (blockCompilation === void 0) { blockCompilation = false; }
  69163. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  69164. /**
  69165. * 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.
  69166. */
  69167. _this.lensSize = 50;
  69168. /**
  69169. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  69170. */
  69171. _this.fStop = 1.4;
  69172. /**
  69173. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  69174. */
  69175. _this.focusDistance = 2000;
  69176. /**
  69177. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  69178. */
  69179. _this.focalLength = 50;
  69180. _this._depthTexture = null;
  69181. _this._depthTexture = depthTexture;
  69182. _this.onApplyObservable.add(function (effect) {
  69183. if (!_this._depthTexture) {
  69184. BABYLON.Tools.Warn("No depth texture set on CircleOfConfusionPostProcess");
  69185. return;
  69186. }
  69187. effect.setTexture("depthSampler", _this._depthTexture);
  69188. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  69189. var aperture = _this.lensSize / _this.fStop;
  69190. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  69191. effect.setFloat('focusDistance', _this.focusDistance);
  69192. effect.setFloat('cocPrecalculation', cocPrecalculation);
  69193. effect.setFloat2('cameraMinMaxZ', _this._depthTexture.activeCamera.minZ, _this._depthTexture.activeCamera.maxZ);
  69194. });
  69195. return _this;
  69196. }
  69197. Object.defineProperty(CircleOfConfusionPostProcess.prototype, "depthTexture", {
  69198. /**
  69199. * 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.
  69200. */
  69201. set: function (value) {
  69202. this._depthTexture = value;
  69203. },
  69204. enumerable: true,
  69205. configurable: true
  69206. });
  69207. return CircleOfConfusionPostProcess;
  69208. }(BABYLON.PostProcess));
  69209. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  69210. })(BABYLON || (BABYLON = {}));
  69211. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  69212. var BABYLON;
  69213. (function (BABYLON) {
  69214. /**
  69215. * Specifies the level of max blur that should be applied when using the depth of field effect
  69216. */
  69217. var DepthOfFieldEffectBlurLevel;
  69218. (function (DepthOfFieldEffectBlurLevel) {
  69219. /**
  69220. * Subtle blur
  69221. */
  69222. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Low"] = 0] = "Low";
  69223. /**
  69224. * Medium blur
  69225. */
  69226. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium";
  69227. /**
  69228. * Large blur
  69229. */
  69230. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["High"] = 2] = "High";
  69231. })(DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel || (BABYLON.DepthOfFieldEffectBlurLevel = {}));
  69232. ;
  69233. /**
  69234. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  69235. */
  69236. var DepthOfFieldEffect = /** @class */ (function (_super) {
  69237. __extends(DepthOfFieldEffect, _super);
  69238. /**
  69239. * Creates a new instance of @see DepthOfFieldEffect
  69240. * @param scene The scene the effect belongs to.
  69241. * @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.
  69242. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  69243. * @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)
  69244. */
  69245. function DepthOfFieldEffect(scene, depthTexture, blurLevel, pipelineTextureType, blockCompilation) {
  69246. if (blurLevel === void 0) { blurLevel = DepthOfFieldEffectBlurLevel.Low; }
  69247. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  69248. if (blockCompilation === void 0) { blockCompilation = false; }
  69249. var _this = _super.call(this, scene.getEngine(), "depth of field", function () {
  69250. return _this._effects;
  69251. }, true) || this;
  69252. _this._effects = [];
  69253. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  69254. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", depthTexture, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  69255. // Capture circle of confusion texture
  69256. _this._depthOfFieldPass = new BABYLON.PassPostProcess("depthOfFieldPass", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  69257. _this._depthOfFieldPass.autoClear = false;
  69258. // 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)
  69259. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  69260. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  69261. _this._depthOfFieldBlurY = [];
  69262. _this._depthOfFieldBlurX = [];
  69263. var blurCount = 1;
  69264. var kernelSize = 15;
  69265. switch (blurLevel) {
  69266. case DepthOfFieldEffectBlurLevel.High: {
  69267. blurCount = 3;
  69268. kernelSize = 51;
  69269. break;
  69270. }
  69271. case DepthOfFieldEffectBlurLevel.Medium: {
  69272. blurCount = 2;
  69273. kernelSize = 31;
  69274. break;
  69275. }
  69276. default: {
  69277. kernelSize = 15;
  69278. blurCount = 1;
  69279. break;
  69280. }
  69281. }
  69282. var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);
  69283. for (var i = 0; i < blurCount; i++) {
  69284. var blurY = new BABYLON.DepthOfFieldBlurPostProcess("verticle blur", scene, new BABYLON.Vector2(0, 1.0), adjustedKernelSize, 1.0 / Math.pow(2, i), null, _this._depthOfFieldPass, i == 0 ? _this._circleOfConfusion : null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  69285. blurY.autoClear = false;
  69286. var blurX = new BABYLON.DepthOfFieldBlurPostProcess("horizontal blur", scene, new BABYLON.Vector2(1.0, 0), adjustedKernelSize, 1.0 / Math.pow(2, i), null, _this._depthOfFieldPass, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  69287. blurX.autoClear = false;
  69288. _this._depthOfFieldBlurY.push(blurY);
  69289. _this._depthOfFieldBlurX.push(blurX);
  69290. }
  69291. // Merge blurred images with original image based on circleOfConfusion
  69292. _this._depthOfFieldMerge = new BABYLON.DepthOfFieldMergePostProcess("depthOfFieldMerge", _this._circleOfConfusion, _this._depthOfFieldPass, _this._depthOfFieldBlurY.slice(1), 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  69293. _this._depthOfFieldMerge.autoClear = false;
  69294. // Set all post processes on the effect.
  69295. _this._effects = [_this._circleOfConfusion, _this._depthOfFieldPass];
  69296. for (var i = 0; i < _this._depthOfFieldBlurX.length; i++) {
  69297. _this._effects.push(_this._depthOfFieldBlurY[i]);
  69298. _this._effects.push(_this._depthOfFieldBlurX[i]);
  69299. }
  69300. _this._effects.push(_this._depthOfFieldMerge);
  69301. return _this;
  69302. }
  69303. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  69304. get: function () {
  69305. return this._circleOfConfusion.focalLength;
  69306. },
  69307. /**
  69308. * The focal the length of the camera used in the effect
  69309. */
  69310. set: function (value) {
  69311. this._circleOfConfusion.focalLength = value;
  69312. },
  69313. enumerable: true,
  69314. configurable: true
  69315. });
  69316. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  69317. get: function () {
  69318. return this._circleOfConfusion.fStop;
  69319. },
  69320. /**
  69321. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  69322. */
  69323. set: function (value) {
  69324. this._circleOfConfusion.fStop = value;
  69325. },
  69326. enumerable: true,
  69327. configurable: true
  69328. });
  69329. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  69330. get: function () {
  69331. return this._circleOfConfusion.focusDistance;
  69332. },
  69333. /**
  69334. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  69335. */
  69336. set: function (value) {
  69337. this._circleOfConfusion.focusDistance = value;
  69338. },
  69339. enumerable: true,
  69340. configurable: true
  69341. });
  69342. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  69343. get: function () {
  69344. return this._circleOfConfusion.lensSize;
  69345. },
  69346. /**
  69347. * 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.
  69348. */
  69349. set: function (value) {
  69350. this._circleOfConfusion.lensSize = value;
  69351. },
  69352. enumerable: true,
  69353. configurable: true
  69354. });
  69355. Object.defineProperty(DepthOfFieldEffect.prototype, "depthTexture", {
  69356. /**
  69357. * 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.
  69358. */
  69359. set: function (value) {
  69360. this._circleOfConfusion.depthTexture = value;
  69361. },
  69362. enumerable: true,
  69363. configurable: true
  69364. });
  69365. /**
  69366. * Disposes each of the internal effects for a given camera.
  69367. * @param camera The camera to dispose the effect on.
  69368. */
  69369. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  69370. this._depthOfFieldPass.dispose(camera);
  69371. this._circleOfConfusion.dispose(camera);
  69372. this._depthOfFieldBlurX.forEach(function (element) {
  69373. element.dispose(camera);
  69374. });
  69375. this._depthOfFieldBlurY.forEach(function (element) {
  69376. element.dispose(camera);
  69377. });
  69378. this._depthOfFieldMerge.dispose(camera);
  69379. };
  69380. /**
  69381. * Internal
  69382. */
  69383. DepthOfFieldEffect.prototype._updateEffects = function () {
  69384. for (var effect in this._effects) {
  69385. this._effects[effect].updateEffect();
  69386. }
  69387. };
  69388. /**
  69389. * Internal
  69390. * @returns if all the contained post processes are ready.
  69391. */
  69392. DepthOfFieldEffect.prototype._isReady = function () {
  69393. for (var effect in this._effects) {
  69394. if (!this._effects[effect].isReady()) {
  69395. return false;
  69396. }
  69397. }
  69398. return true;
  69399. };
  69400. return DepthOfFieldEffect;
  69401. }(BABYLON.PostProcessRenderEffect));
  69402. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  69403. })(BABYLON || (BABYLON = {}));
  69404. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  69405. var BABYLON;
  69406. (function (BABYLON) {
  69407. /**
  69408. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  69409. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  69410. */
  69411. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  69412. __extends(DefaultRenderingPipeline, _super);
  69413. /**
  69414. * @constructor
  69415. * @param {string} name - The rendering pipeline name
  69416. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  69417. * @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)
  69418. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  69419. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline
  69420. */
  69421. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  69422. if (automaticBuild === void 0) { automaticBuild = true; }
  69423. var _this = _super.call(this, scene.getEngine(), name) || this;
  69424. _this._originalCameras = [];
  69425. /**
  69426. * ID of the sharpen post process,
  69427. */
  69428. _this.SharpenPostProcessId = "SharpenPostProcessEffect";
  69429. /**
  69430. * ID of the pass post process used for bloom,
  69431. */
  69432. _this.PassPostProcessId = "PassPostProcessEffect";
  69433. /**
  69434. * ID of the highlight post process used for bloom,
  69435. */
  69436. _this.HighLightsPostProcessId = "HighLightsPostProcessEffect";
  69437. /**
  69438. * ID of the blurX post process used for bloom,
  69439. */
  69440. _this.BlurXPostProcessId = "BlurXPostProcessEffect";
  69441. /**
  69442. * ID of the blurY post process used for bloom,
  69443. */
  69444. _this.BlurYPostProcessId = "BlurYPostProcessEffect";
  69445. /**
  69446. * ID of the copy back post process used for bloom,
  69447. */
  69448. _this.CopyBackPostProcessId = "CopyBackPostProcessEffect";
  69449. /**
  69450. * ID of the image processing post process;
  69451. */
  69452. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  69453. /**
  69454. * ID of the Fast Approximate Anti-Aliasing post process;
  69455. */
  69456. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  69457. /**
  69458. * ID of the final merge post process;
  69459. */
  69460. _this.FinalMergePostProcessId = "FinalMergePostProcessEffect";
  69461. /**
  69462. * ID of the chromatic aberration post process,
  69463. */
  69464. _this.ChromaticAberrationPostProcessId = "ChromaticAberrationPostProcessEffect";
  69465. /**
  69466. * Animations which can be used to tweak settings over a period of time
  69467. */
  69468. _this.animations = [];
  69469. // Values
  69470. _this._sharpenEnabled = false;
  69471. _this._bloomEnabled = false;
  69472. _this._depthOfFieldEnabled = false;
  69473. _this._depthOfFieldBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel.Low;
  69474. _this._fxaaEnabled = false;
  69475. _this._msaaEnabled = false;
  69476. _this._imageProcessingEnabled = true;
  69477. _this._bloomScale = 0.6;
  69478. _this._chromaticAberrationEnabled = false;
  69479. _this._buildAllowed = true;
  69480. /**
  69481. * Specifies the size of the bloom blur kernel, relative to the final output size
  69482. */
  69483. _this.bloomKernel = 64;
  69484. /**
  69485. * Specifies the weight of the bloom in the final rendering
  69486. */
  69487. _this._bloomWeight = 0.15;
  69488. _this._prevPostProcess = null;
  69489. _this._prevPrevPostProcess = null;
  69490. _this._cameras = cameras || [];
  69491. _this._originalCameras = _this._cameras.slice();
  69492. _this._buildAllowed = automaticBuild;
  69493. // Initialize
  69494. _this._scene = scene;
  69495. var caps = _this._scene.getEngine().getCaps();
  69496. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  69497. // Misc
  69498. if (_this._hdr) {
  69499. if (caps.textureHalfFloatRender) {
  69500. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  69501. }
  69502. else if (caps.textureFloatRender) {
  69503. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  69504. }
  69505. }
  69506. else {
  69507. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  69508. }
  69509. // Attach
  69510. scene.postProcessRenderPipelineManager.addPipeline(_this);
  69511. var engine = _this._scene.getEngine();
  69512. // Create post processes before hand so they can be modified before enabled.
  69513. // Block compilation flag is set to true to avoid compilation prior to use, these will be updated on first use in build pipeline.
  69514. _this.sharpen = new BABYLON.SharpenPostProcess("sharpen", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  69515. _this._sharpenEffect = new BABYLON.PostProcessRenderEffect(engine, _this.SharpenPostProcessId, function () { return _this.sharpen; }, true);
  69516. _this.depthOfField = new BABYLON.DepthOfFieldEffect(_this._scene, null, _this._depthOfFieldBlurLevel, _this._defaultPipelineTextureType, true);
  69517. _this.chromaticAberration = new BABYLON.ChromaticAberrationPostProcess("ChromaticAberration", engine.getRenderWidth(), engine.getRenderHeight(), 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  69518. _this._chromaticAberrationEffect = new BABYLON.PostProcessRenderEffect(engine, _this.ChromaticAberrationPostProcessId, function () { return _this.chromaticAberration; }, true);
  69519. _this._buildPipeline();
  69520. return _this;
  69521. }
  69522. Object.defineProperty(DefaultRenderingPipeline.prototype, "sharpenEnabled", {
  69523. get: function () {
  69524. return this._sharpenEnabled;
  69525. },
  69526. /**
  69527. * Enable or disable the sharpen process from the pipeline
  69528. */
  69529. set: function (enabled) {
  69530. if (this._sharpenEnabled === enabled) {
  69531. return;
  69532. }
  69533. this._sharpenEnabled = enabled;
  69534. this._buildPipeline();
  69535. },
  69536. enumerable: true,
  69537. configurable: true
  69538. });
  69539. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  69540. get: function () {
  69541. return this._bloomWeight;
  69542. },
  69543. /**
  69544. * The strength of the bloom.
  69545. */
  69546. set: function (value) {
  69547. if (this._bloomWeight === value) {
  69548. return;
  69549. }
  69550. this._bloomWeight = value;
  69551. if (this._hdr && this.copyBack) {
  69552. this.copyBack.alphaConstants = new BABYLON.Color4(value, value, value, value);
  69553. }
  69554. },
  69555. enumerable: true,
  69556. configurable: true
  69557. });
  69558. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  69559. get: function () {
  69560. return this._bloomScale;
  69561. },
  69562. /**
  69563. * The scale of the bloom, lower value will provide better performance.
  69564. */
  69565. set: function (value) {
  69566. if (this._bloomScale === value) {
  69567. return;
  69568. }
  69569. this._bloomScale = value;
  69570. this._buildPipeline();
  69571. },
  69572. enumerable: true,
  69573. configurable: true
  69574. });
  69575. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  69576. get: function () {
  69577. return this._bloomEnabled;
  69578. },
  69579. /**
  69580. * Enable or disable the bloom from the pipeline
  69581. */
  69582. set: function (enabled) {
  69583. if (this._bloomEnabled === enabled) {
  69584. return;
  69585. }
  69586. this._bloomEnabled = enabled;
  69587. this._buildPipeline();
  69588. },
  69589. enumerable: true,
  69590. configurable: true
  69591. });
  69592. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  69593. /**
  69594. * If the depth of field is enabled.
  69595. */
  69596. get: function () {
  69597. return this._depthOfFieldEnabled;
  69598. },
  69599. set: function (enabled) {
  69600. if (this._depthOfFieldEnabled === enabled) {
  69601. return;
  69602. }
  69603. this._depthOfFieldEnabled = enabled;
  69604. this._buildPipeline();
  69605. },
  69606. enumerable: true,
  69607. configurable: true
  69608. });
  69609. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", {
  69610. /**
  69611. * Blur level of the depth of field effect. (Higher blur will effect performance)
  69612. */
  69613. get: function () {
  69614. return this._depthOfFieldBlurLevel;
  69615. },
  69616. set: function (value) {
  69617. if (this._depthOfFieldBlurLevel === value) {
  69618. return;
  69619. }
  69620. this._depthOfFieldBlurLevel = value;
  69621. // recreate dof and dispose old as this setting is not dynamic
  69622. var oldDof = this.depthOfField;
  69623. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, null, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType);
  69624. this.depthOfField.focalLength = oldDof.focalLength;
  69625. this.depthOfField.focusDistance = oldDof.focusDistance;
  69626. this.depthOfField.fStop = oldDof.fStop;
  69627. this.depthOfField.lensSize = oldDof.lensSize;
  69628. for (var i = 0; i < this._cameras.length; i++) {
  69629. oldDof.disposeEffects(this._cameras[i]);
  69630. }
  69631. this._buildPipeline();
  69632. },
  69633. enumerable: true,
  69634. configurable: true
  69635. });
  69636. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  69637. get: function () {
  69638. return this._fxaaEnabled;
  69639. },
  69640. /**
  69641. * If the anti aliasing is enabled.
  69642. */
  69643. set: function (enabled) {
  69644. if (this._fxaaEnabled === enabled) {
  69645. return;
  69646. }
  69647. this._fxaaEnabled = enabled;
  69648. this._buildPipeline();
  69649. },
  69650. enumerable: true,
  69651. configurable: true
  69652. });
  69653. Object.defineProperty(DefaultRenderingPipeline.prototype, "msaaEnabled", {
  69654. get: function () {
  69655. return this._msaaEnabled;
  69656. },
  69657. /**
  69658. * If the multisample anti-aliasing is enabled.
  69659. */
  69660. set: function (enabled) {
  69661. if (this._msaaEnabled === enabled) {
  69662. return;
  69663. }
  69664. this._msaaEnabled = enabled;
  69665. this._buildPipeline();
  69666. },
  69667. enumerable: true,
  69668. configurable: true
  69669. });
  69670. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  69671. get: function () {
  69672. return this._imageProcessingEnabled;
  69673. },
  69674. /**
  69675. * If image processing is enabled.
  69676. */
  69677. set: function (enabled) {
  69678. if (this._imageProcessingEnabled === enabled) {
  69679. return;
  69680. }
  69681. this._imageProcessingEnabled = enabled;
  69682. this._buildPipeline();
  69683. },
  69684. enumerable: true,
  69685. configurable: true
  69686. });
  69687. Object.defineProperty(DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", {
  69688. get: function () {
  69689. return this._chromaticAberrationEnabled;
  69690. },
  69691. /**
  69692. * Enable or disable the chromaticAberration process from the pipeline
  69693. */
  69694. set: function (enabled) {
  69695. if (this._chromaticAberrationEnabled === enabled) {
  69696. return;
  69697. }
  69698. this._chromaticAberrationEnabled = enabled;
  69699. this._buildPipeline();
  69700. },
  69701. enumerable: true,
  69702. configurable: true
  69703. });
  69704. /**
  69705. * Force the compilation of the entire pipeline.
  69706. */
  69707. DefaultRenderingPipeline.prototype.prepare = function () {
  69708. var previousState = this._buildAllowed;
  69709. this._buildAllowed = true;
  69710. this._buildPipeline();
  69711. this._buildAllowed = previousState;
  69712. };
  69713. DefaultRenderingPipeline.prototype._setAutoClearAndTextureSharing = function (postProcess, skipTextureSharing) {
  69714. if (skipTextureSharing === void 0) { skipTextureSharing = false; }
  69715. if (this._prevPostProcess && this._prevPostProcess.autoClear) {
  69716. postProcess.autoClear = false;
  69717. }
  69718. else {
  69719. postProcess.autoClear = true;
  69720. }
  69721. if (!skipTextureSharing) {
  69722. if (this._prevPrevPostProcess) {
  69723. postProcess.shareOutputWith(this._prevPrevPostProcess);
  69724. }
  69725. else {
  69726. postProcess.useOwnOutput();
  69727. }
  69728. if (this._prevPostProcess) {
  69729. this._prevPrevPostProcess = this._prevPostProcess;
  69730. }
  69731. this._prevPostProcess = postProcess;
  69732. }
  69733. };
  69734. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  69735. var _this = this;
  69736. if (!this._buildAllowed) {
  69737. return;
  69738. }
  69739. var engine = this._scene.getEngine();
  69740. this._disposePostProcesses();
  69741. if (this._cameras !== null) {
  69742. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  69743. // get back cameras to be used to reattach pipeline
  69744. this._cameras = this._originalCameras.slice();
  69745. }
  69746. this._reset();
  69747. this._prevPostProcess = null;
  69748. this._prevPrevPostProcess = null;
  69749. if (this.sharpenEnabled) {
  69750. if (!this.sharpen.isReady()) {
  69751. this.sharpen.updateEffect();
  69752. }
  69753. this.addEffect(this._sharpenEffect);
  69754. this._setAutoClearAndTextureSharing(this.sharpen);
  69755. }
  69756. if (this.depthOfFieldEnabled) {
  69757. var depthTexture = this._scene.enableDepthRenderer(this._cameras[0]).getDepthMap();
  69758. this.depthOfField.depthTexture = depthTexture;
  69759. if (!this.depthOfField._isReady()) {
  69760. this.depthOfField._updateEffects();
  69761. }
  69762. this.addEffect(this.depthOfField);
  69763. this._setAutoClearAndTextureSharing(this.depthOfField._depthOfFieldMerge);
  69764. }
  69765. if (this.bloomEnabled) {
  69766. this.pass = new BABYLON.PassPostProcess("sceneRenderTarget", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  69767. this._setAutoClearAndTextureSharing(this.pass, true);
  69768. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.PassPostProcessId, function () { return _this.pass; }, true));
  69769. if (!this._hdr) {
  69770. this.highlights = new BABYLON.HighlightsPostProcess("highlights", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  69771. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.HighLightsPostProcessId, function () { return _this.highlights; }, true));
  69772. this.highlights.autoClear = false;
  69773. this.highlights.alwaysForcePOT = true;
  69774. }
  69775. 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);
  69776. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurXPostProcessId, function () { return _this.blurX; }, true));
  69777. this.blurX.alwaysForcePOT = true;
  69778. this.blurX.autoClear = false;
  69779. this.blurX.onActivateObservable.add(function () {
  69780. var dw = _this.blurX.width / engine.getRenderWidth(true);
  69781. _this.blurX.kernel = _this.bloomKernel * dw;
  69782. });
  69783. 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);
  69784. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurYPostProcessId, function () { return _this.blurY; }, true));
  69785. this.blurY.alwaysForcePOT = true;
  69786. this.blurY.autoClear = false;
  69787. this.blurY.onActivateObservable.add(function () {
  69788. var dh = _this.blurY.height / engine.getRenderHeight(true);
  69789. _this.blurY.kernel = _this.bloomKernel * dh;
  69790. });
  69791. this.copyBack = new BABYLON.PassPostProcess("bloomBlendBlit", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  69792. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.CopyBackPostProcessId, function () { return _this.copyBack; }, true));
  69793. this.copyBack.alwaysForcePOT = true;
  69794. if (this._hdr) {
  69795. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_INTERPOLATE;
  69796. var w = this.bloomWeight;
  69797. this.copyBack.alphaConstants = new BABYLON.Color4(w, w, w, w);
  69798. }
  69799. else {
  69800. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_SCREENMODE;
  69801. }
  69802. this.copyBack.autoClear = false;
  69803. }
  69804. if (this._imageProcessingEnabled) {
  69805. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  69806. if (this._hdr) {
  69807. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  69808. }
  69809. else {
  69810. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  69811. }
  69812. }
  69813. if (this._hdr && this.imageProcessing) {
  69814. this.finalMerge = this.imageProcessing;
  69815. }
  69816. else {
  69817. this.finalMerge = new BABYLON.PassPostProcess("finalMerge", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  69818. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FinalMergePostProcessId, function () { return _this.finalMerge; }, true));
  69819. this._setAutoClearAndTextureSharing(this.finalMerge, true);
  69820. this.finalMerge.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  69821. }
  69822. if (this.bloomEnabled) {
  69823. if (this._hdr) {
  69824. this.copyBack.shareOutputWith(this.blurX);
  69825. if (this.imageProcessing) {
  69826. this.imageProcessing.shareOutputWith(this.pass);
  69827. this.imageProcessing.autoClear = false;
  69828. }
  69829. else {
  69830. this.finalMerge.shareOutputWith(this.pass);
  69831. }
  69832. }
  69833. else {
  69834. this.finalMerge.shareOutputWith(this.pass);
  69835. }
  69836. }
  69837. if (this.fxaaEnabled) {
  69838. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  69839. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  69840. this._setAutoClearAndTextureSharing(this.fxaa);
  69841. }
  69842. if (this.chromaticAberrationEnabled) {
  69843. if (!this.chromaticAberration.isReady()) {
  69844. this.chromaticAberration.updateEffect();
  69845. }
  69846. this.addEffect(this._chromaticAberrationEffect);
  69847. this._setAutoClearAndTextureSharing(this.chromaticAberration);
  69848. }
  69849. if (this._cameras !== null) {
  69850. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  69851. }
  69852. if (this.msaaEnabled) {
  69853. if (!this._enableMSAAOnFirstPostProcess()) {
  69854. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  69855. }
  69856. }
  69857. };
  69858. DefaultRenderingPipeline.prototype._disposePostProcesses = function (disposeNonRecreated) {
  69859. if (disposeNonRecreated === void 0) { disposeNonRecreated = false; }
  69860. for (var i = 0; i < this._cameras.length; i++) {
  69861. var camera = this._cameras[i];
  69862. if (this.pass) {
  69863. this.pass.dispose(camera);
  69864. }
  69865. if (this.highlights) {
  69866. this.highlights.dispose(camera);
  69867. }
  69868. if (this.blurX) {
  69869. this.blurX.dispose(camera);
  69870. }
  69871. if (this.blurY) {
  69872. this.blurY.dispose(camera);
  69873. }
  69874. if (this.copyBack) {
  69875. this.copyBack.dispose(camera);
  69876. }
  69877. if (this.imageProcessing) {
  69878. this.imageProcessing.dispose(camera);
  69879. }
  69880. if (this.fxaa) {
  69881. this.fxaa.dispose(camera);
  69882. }
  69883. if (this.finalMerge) {
  69884. this.finalMerge.dispose(camera);
  69885. }
  69886. // These are created in the constructor and should not be disposed on every pipeline change
  69887. if (disposeNonRecreated) {
  69888. if (this.sharpen) {
  69889. this.sharpen.dispose(camera);
  69890. }
  69891. if (this.depthOfField) {
  69892. this.depthOfField.disposeEffects(camera);
  69893. }
  69894. if (this.chromaticAberration) {
  69895. this.chromaticAberration.dispose(camera);
  69896. }
  69897. }
  69898. }
  69899. this.pass = null;
  69900. this.highlights = null;
  69901. this.blurX = null;
  69902. this.blurY = null;
  69903. this.copyBack = null;
  69904. this.imageProcessing = null;
  69905. this.fxaa = null;
  69906. this.finalMerge = null;
  69907. if (disposeNonRecreated) {
  69908. this.sharpen = null;
  69909. this.depthOfField = null;
  69910. this.chromaticAberration = null;
  69911. }
  69912. };
  69913. /**
  69914. * Dispose of the pipeline and stop all post processes
  69915. */
  69916. DefaultRenderingPipeline.prototype.dispose = function () {
  69917. this._disposePostProcesses(true);
  69918. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  69919. _super.prototype.dispose.call(this);
  69920. };
  69921. /**
  69922. * Serialize the rendering pipeline (Used when exporting)
  69923. * @returns the serialized object
  69924. */
  69925. DefaultRenderingPipeline.prototype.serialize = function () {
  69926. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  69927. serializationObject.customType = "DefaultRenderingPipeline";
  69928. return serializationObject;
  69929. };
  69930. /**
  69931. * Parse the serialized pipeline
  69932. * @param source Source pipeline.
  69933. * @param scene The scene to load the pipeline to.
  69934. * @param rootUrl The URL of the serialized pipeline.
  69935. * @returns An instantiated pipeline from the serialized object.
  69936. */
  69937. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  69938. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  69939. };
  69940. __decorate([
  69941. BABYLON.serialize()
  69942. ], DefaultRenderingPipeline.prototype, "sharpenEnabled", null);
  69943. __decorate([
  69944. BABYLON.serialize()
  69945. ], DefaultRenderingPipeline.prototype, "bloomKernel", void 0);
  69946. __decorate([
  69947. BABYLON.serialize()
  69948. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  69949. __decorate([
  69950. BABYLON.serialize()
  69951. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  69952. __decorate([
  69953. BABYLON.serialize()
  69954. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  69955. __decorate([
  69956. BABYLON.serialize()
  69957. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  69958. __decorate([
  69959. BABYLON.serialize()
  69960. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  69961. __decorate([
  69962. BABYLON.serialize()
  69963. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  69964. __decorate([
  69965. BABYLON.serialize()
  69966. ], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null);
  69967. __decorate([
  69968. BABYLON.serialize()
  69969. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  69970. __decorate([
  69971. BABYLON.serialize()
  69972. ], DefaultRenderingPipeline.prototype, "msaaEnabled", null);
  69973. __decorate([
  69974. BABYLON.serialize()
  69975. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  69976. __decorate([
  69977. BABYLON.serialize()
  69978. ], DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", null);
  69979. return DefaultRenderingPipeline;
  69980. }(BABYLON.PostProcessRenderPipeline));
  69981. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  69982. })(BABYLON || (BABYLON = {}));
  69983. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  69984. var BABYLON;
  69985. (function (BABYLON) {
  69986. /**
  69987. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  69988. */
  69989. var GeometryBufferRenderer = /** @class */ (function () {
  69990. /**
  69991. * Creates a new G Buffer for the scene. @see GeometryBufferRenderer
  69992. * @param scene The scene the buffer belongs to
  69993. * @param ratio How big is the buffer related to the main canvas.
  69994. */
  69995. function GeometryBufferRenderer(scene, ratio) {
  69996. if (ratio === void 0) { ratio = 1; }
  69997. this._enablePosition = false;
  69998. this._scene = scene;
  69999. this._ratio = ratio;
  70000. // Render target
  70001. this._createRenderTargets();
  70002. }
  70003. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  70004. /**
  70005. * Set the render list (meshes to be rendered) used in the G buffer.
  70006. */
  70007. set: function (meshes) {
  70008. this._multiRenderTarget.renderList = meshes;
  70009. },
  70010. enumerable: true,
  70011. configurable: true
  70012. });
  70013. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  70014. /**
  70015. * Gets wether or not G buffer are supported by the running hardware.
  70016. * This requires draw buffer supports
  70017. */
  70018. get: function () {
  70019. return this._multiRenderTarget.isSupported;
  70020. },
  70021. enumerable: true,
  70022. configurable: true
  70023. });
  70024. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  70025. /**
  70026. * Gets wether or not position are enabled for the G buffer.
  70027. */
  70028. get: function () {
  70029. return this._enablePosition;
  70030. },
  70031. /**
  70032. * Sets wether or not position are enabled for the G buffer.
  70033. */
  70034. set: function (enable) {
  70035. this._enablePosition = enable;
  70036. this.dispose();
  70037. this._createRenderTargets();
  70038. },
  70039. enumerable: true,
  70040. configurable: true
  70041. });
  70042. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  70043. /**
  70044. * Gets the scene associated with the buffer.
  70045. */
  70046. get: function () {
  70047. return this._scene;
  70048. },
  70049. enumerable: true,
  70050. configurable: true
  70051. });
  70052. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  70053. /**
  70054. * Gets the ratio used by the buffer during its creation.
  70055. * How big is the buffer related to the main canvas.
  70056. */
  70057. get: function () {
  70058. return this._ratio;
  70059. },
  70060. enumerable: true,
  70061. configurable: true
  70062. });
  70063. /**
  70064. * Checks wether everything is ready to render a submesh to the G buffer.
  70065. * @param subMesh the submesh to check readiness for
  70066. * @param useInstances is the mesh drawn using instance or not
  70067. * @returns true if ready otherwise false
  70068. */
  70069. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  70070. var material = subMesh.getMaterial();
  70071. if (material && material.disableDepthWrite) {
  70072. return false;
  70073. }
  70074. var defines = [];
  70075. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  70076. var mesh = subMesh.getMesh();
  70077. // Alpha test
  70078. if (material && material.needAlphaTesting()) {
  70079. defines.push("#define ALPHATEST");
  70080. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  70081. attribs.push(BABYLON.VertexBuffer.UVKind);
  70082. defines.push("#define UV1");
  70083. }
  70084. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  70085. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  70086. defines.push("#define UV2");
  70087. }
  70088. }
  70089. // Buffers
  70090. if (this._enablePosition) {
  70091. defines.push("#define POSITION");
  70092. }
  70093. // Bones
  70094. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  70095. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  70096. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  70097. if (mesh.numBoneInfluencers > 4) {
  70098. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  70099. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  70100. }
  70101. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  70102. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  70103. }
  70104. else {
  70105. defines.push("#define NUM_BONE_INFLUENCERS 0");
  70106. }
  70107. // Instances
  70108. if (useInstances) {
  70109. defines.push("#define INSTANCES");
  70110. attribs.push("world0");
  70111. attribs.push("world1");
  70112. attribs.push("world2");
  70113. attribs.push("world3");
  70114. }
  70115. // Get correct effect
  70116. var join = defines.join("\n");
  70117. if (this._cachedDefines !== join) {
  70118. this._cachedDefines = join;
  70119. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  70120. }
  70121. return this._effect.isReady();
  70122. };
  70123. /**
  70124. * Gets the current underlying G Buffer.
  70125. * @returns the buffer
  70126. */
  70127. GeometryBufferRenderer.prototype.getGBuffer = function () {
  70128. return this._multiRenderTarget;
  70129. };
  70130. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  70131. /**
  70132. * Gets the number of samples used to render the buffer (anti aliasing).
  70133. */
  70134. get: function () {
  70135. return this._multiRenderTarget.samples;
  70136. },
  70137. /**
  70138. * Sets the number of samples used to render the buffer (anti aliasing).
  70139. */
  70140. set: function (value) {
  70141. this._multiRenderTarget.samples = value;
  70142. },
  70143. enumerable: true,
  70144. configurable: true
  70145. });
  70146. /**
  70147. * Disposes the renderer and frees up associated resources.
  70148. */
  70149. GeometryBufferRenderer.prototype.dispose = function () {
  70150. this.getGBuffer().dispose();
  70151. };
  70152. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  70153. var _this = this;
  70154. var engine = this._scene.getEngine();
  70155. var count = this._enablePosition ? 3 : 2;
  70156. 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 });
  70157. if (!this.isSupported) {
  70158. return;
  70159. }
  70160. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  70161. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  70162. this._multiRenderTarget.refreshRate = 1;
  70163. this._multiRenderTarget.renderParticles = false;
  70164. this._multiRenderTarget.renderList = null;
  70165. // set default depth value to 1.0 (far away)
  70166. this._multiRenderTarget.onClearObservable.add(function (engine) {
  70167. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  70168. });
  70169. // Custom render function
  70170. var renderSubMesh = function (subMesh) {
  70171. var mesh = subMesh.getRenderingMesh();
  70172. var scene = _this._scene;
  70173. var engine = scene.getEngine();
  70174. var material = subMesh.getMaterial();
  70175. if (!material) {
  70176. return;
  70177. }
  70178. // Culling
  70179. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  70180. // Managing instances
  70181. var batch = mesh._getInstancesRenderList(subMesh._id);
  70182. if (batch.mustReturn) {
  70183. return;
  70184. }
  70185. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  70186. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  70187. engine.enableEffect(_this._effect);
  70188. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  70189. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  70190. _this._effect.setMatrix("view", scene.getViewMatrix());
  70191. // Alpha test
  70192. if (material && material.needAlphaTesting()) {
  70193. var alphaTexture = material.getAlphaTestTexture();
  70194. if (alphaTexture) {
  70195. _this._effect.setTexture("diffuseSampler", alphaTexture);
  70196. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  70197. }
  70198. }
  70199. // Bones
  70200. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  70201. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  70202. }
  70203. // Draw
  70204. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  70205. }
  70206. };
  70207. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  70208. var index;
  70209. if (depthOnlySubMeshes.length) {
  70210. engine.setColorWrite(false);
  70211. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  70212. renderSubMesh(depthOnlySubMeshes.data[index]);
  70213. }
  70214. engine.setColorWrite(true);
  70215. }
  70216. for (index = 0; index < opaqueSubMeshes.length; index++) {
  70217. renderSubMesh(opaqueSubMeshes.data[index]);
  70218. }
  70219. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  70220. renderSubMesh(alphaTestSubMeshes.data[index]);
  70221. }
  70222. };
  70223. };
  70224. return GeometryBufferRenderer;
  70225. }());
  70226. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  70227. })(BABYLON || (BABYLON = {}));
  70228. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  70229. var BABYLON;
  70230. (function (BABYLON) {
  70231. var RefractionPostProcess = /** @class */ (function (_super) {
  70232. __extends(RefractionPostProcess, _super);
  70233. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  70234. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  70235. _this.color = color;
  70236. _this.depth = depth;
  70237. _this.colorLevel = colorLevel;
  70238. _this._ownRefractionTexture = true;
  70239. _this.onActivateObservable.add(function (cam) {
  70240. _this._refTexture = _this._refTexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  70241. });
  70242. _this.onApplyObservable.add(function (effect) {
  70243. effect.setColor3("baseColor", _this.color);
  70244. effect.setFloat("depth", _this.depth);
  70245. effect.setFloat("colorLevel", _this.colorLevel);
  70246. effect.setTexture("refractionSampler", _this._refTexture);
  70247. });
  70248. return _this;
  70249. }
  70250. Object.defineProperty(RefractionPostProcess.prototype, "refractionTexture", {
  70251. /**
  70252. * Gets or sets the refraction texture
  70253. * Please note that you are responsible for disposing the texture if you set it manually
  70254. */
  70255. get: function () {
  70256. return this._refTexture;
  70257. },
  70258. set: function (value) {
  70259. if (this._refTexture && this._ownRefractionTexture) {
  70260. this._refTexture.dispose();
  70261. }
  70262. this._refTexture = value;
  70263. this._ownRefractionTexture = false;
  70264. },
  70265. enumerable: true,
  70266. configurable: true
  70267. });
  70268. // Methods
  70269. RefractionPostProcess.prototype.dispose = function (camera) {
  70270. if (this._refTexture && this._ownRefractionTexture) {
  70271. this._refTexture.dispose();
  70272. this._refTexture = null;
  70273. }
  70274. _super.prototype.dispose.call(this, camera);
  70275. };
  70276. return RefractionPostProcess;
  70277. }(BABYLON.PostProcess));
  70278. BABYLON.RefractionPostProcess = RefractionPostProcess;
  70279. })(BABYLON || (BABYLON = {}));
  70280. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  70281. var BABYLON;
  70282. (function (BABYLON) {
  70283. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  70284. __extends(BlackAndWhitePostProcess, _super);
  70285. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  70286. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  70287. _this.degree = 1;
  70288. _this.onApplyObservable.add(function (effect) {
  70289. effect.setFloat("degree", _this.degree);
  70290. });
  70291. return _this;
  70292. }
  70293. return BlackAndWhitePostProcess;
  70294. }(BABYLON.PostProcess));
  70295. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  70296. })(BABYLON || (BABYLON = {}));
  70297. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  70298. var BABYLON;
  70299. (function (BABYLON) {
  70300. /**
  70301. * The ConvolutionPostProcess applies a 3x3 kernel to every pixel of the
  70302. * input texture to perform effects such as edge detection or sharpening
  70303. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  70304. */
  70305. var ConvolutionPostProcess = /** @class */ (function (_super) {
  70306. __extends(ConvolutionPostProcess, _super);
  70307. /**
  70308. * Creates a new instance of @see ConvolutionPostProcess
  70309. * @param name The name of the effect.
  70310. * @param kernel Array of 9 values corrisponding to the 3x3 kernel to be applied
  70311. * @param options The required width/height ratio to downsize to before computing the render pass.
  70312. * @param camera The camera to apply the render pass to.
  70313. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  70314. * @param engine The engine which the post process will be applied. (default: current engine)
  70315. * @param reusable If the post process can be reused on the same frame. (default: false)
  70316. * @param textureType Type of textures used when performing the post process. (default: 0)
  70317. */
  70318. function ConvolutionPostProcess(name, /** Array of 9 values corrisponding to the 3x3 kernel to be applied */ kernel, options, camera, samplingMode, engine, reusable, textureType) {
  70319. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  70320. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  70321. _this.kernel = kernel;
  70322. _this.onApply = function (effect) {
  70323. effect.setFloat2("screenSize", _this.width, _this.height);
  70324. effect.setArray("kernel", _this.kernel);
  70325. };
  70326. return _this;
  70327. }
  70328. // Statics
  70329. /**
  70330. * Edge detection 0 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  70331. */
  70332. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  70333. /**
  70334. * Edge detection 1 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  70335. */
  70336. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  70337. /**
  70338. * Edge detection 2 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  70339. */
  70340. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  70341. /**
  70342. * Kernel to sharpen an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  70343. */
  70344. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  70345. /**
  70346. * Kernel to emboss an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  70347. */
  70348. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  70349. /**
  70350. * Kernel to blur an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  70351. */
  70352. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  70353. return ConvolutionPostProcess;
  70354. }(BABYLON.PostProcess));
  70355. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  70356. })(BABYLON || (BABYLON = {}));
  70357. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  70358. var BABYLON;
  70359. (function (BABYLON) {
  70360. var FilterPostProcess = /** @class */ (function (_super) {
  70361. __extends(FilterPostProcess, _super);
  70362. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  70363. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  70364. _this.kernelMatrix = kernelMatrix;
  70365. _this.onApply = function (effect) {
  70366. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  70367. };
  70368. return _this;
  70369. }
  70370. return FilterPostProcess;
  70371. }(BABYLON.PostProcess));
  70372. BABYLON.FilterPostProcess = FilterPostProcess;
  70373. })(BABYLON || (BABYLON = {}));
  70374. //# sourceMappingURL=babylon.filterPostProcess.js.map
  70375. var BABYLON;
  70376. (function (BABYLON) {
  70377. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  70378. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  70379. __extends(VolumetricLightScatteringPostProcess, _super);
  70380. /**
  70381. * @constructor
  70382. * @param {string} name - The post-process name
  70383. * @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)
  70384. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  70385. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  70386. * @param {number} samples - The post-process quality, default 100
  70387. * @param {number} samplingMode - The post-process filtering mode
  70388. * @param {BABYLON.Engine} engine - The babylon engine
  70389. * @param {boolean} reusable - If the post-process is reusable
  70390. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  70391. */
  70392. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  70393. if (samples === void 0) { samples = 100; }
  70394. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  70395. 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;
  70396. _this._screenCoordinates = BABYLON.Vector2.Zero();
  70397. /**
  70398. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  70399. * @type {Vector3}
  70400. */
  70401. _this.customMeshPosition = BABYLON.Vector3.Zero();
  70402. /**
  70403. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  70404. * @type {boolean}
  70405. */
  70406. _this.useCustomMeshPosition = false;
  70407. /**
  70408. * If the post-process should inverse the light scattering direction
  70409. * @type {boolean}
  70410. */
  70411. _this.invert = true;
  70412. /**
  70413. * Array containing the excluded meshes not rendered in the internal pass
  70414. */
  70415. _this.excludedMeshes = new Array();
  70416. /**
  70417. * Controls the overall intensity of the post-process
  70418. * @type {number}
  70419. */
  70420. _this.exposure = 0.3;
  70421. /**
  70422. * Dissipates each sample's contribution in range [0, 1]
  70423. * @type {number}
  70424. */
  70425. _this.decay = 0.96815;
  70426. /**
  70427. * Controls the overall intensity of each sample
  70428. * @type {number}
  70429. */
  70430. _this.weight = 0.58767;
  70431. /**
  70432. * Controls the density of each sample
  70433. * @type {number}
  70434. */
  70435. _this.density = 0.926;
  70436. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  70437. engine = scene.getEngine();
  70438. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  70439. // Configure mesh
  70440. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  70441. // Configure
  70442. _this._createPass(scene, ratio.passRatio || ratio);
  70443. _this.onActivate = function (camera) {
  70444. if (!_this.isSupported) {
  70445. _this.dispose(camera);
  70446. }
  70447. _this.onActivate = null;
  70448. };
  70449. _this.onApplyObservable.add(function (effect) {
  70450. _this._updateMeshScreenCoordinates(scene);
  70451. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  70452. effect.setFloat("exposure", _this.exposure);
  70453. effect.setFloat("decay", _this.decay);
  70454. effect.setFloat("weight", _this.weight);
  70455. effect.setFloat("density", _this.density);
  70456. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  70457. });
  70458. return _this;
  70459. }
  70460. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  70461. get: function () {
  70462. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  70463. return false;
  70464. },
  70465. set: function (useDiffuseColor) {
  70466. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  70467. },
  70468. enumerable: true,
  70469. configurable: true
  70470. });
  70471. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  70472. return "VolumetricLightScatteringPostProcess";
  70473. };
  70474. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  70475. var mesh = subMesh.getMesh();
  70476. // Render this.mesh as default
  70477. if (mesh === this.mesh && mesh.material) {
  70478. return mesh.material.isReady(mesh);
  70479. }
  70480. var defines = [];
  70481. var attribs = [BABYLON.VertexBuffer.PositionKind];
  70482. var material = subMesh.getMaterial();
  70483. // Alpha test
  70484. if (material) {
  70485. if (material.needAlphaTesting()) {
  70486. defines.push("#define ALPHATEST");
  70487. }
  70488. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  70489. attribs.push(BABYLON.VertexBuffer.UVKind);
  70490. defines.push("#define UV1");
  70491. }
  70492. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  70493. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  70494. defines.push("#define UV2");
  70495. }
  70496. }
  70497. // Bones
  70498. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  70499. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  70500. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  70501. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  70502. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  70503. }
  70504. else {
  70505. defines.push("#define NUM_BONE_INFLUENCERS 0");
  70506. }
  70507. // Instances
  70508. if (useInstances) {
  70509. defines.push("#define INSTANCES");
  70510. attribs.push("world0");
  70511. attribs.push("world1");
  70512. attribs.push("world2");
  70513. attribs.push("world3");
  70514. }
  70515. // Get correct effect
  70516. var join = defines.join("\n");
  70517. if (this._cachedDefines !== join) {
  70518. this._cachedDefines = join;
  70519. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  70520. }
  70521. return this._volumetricLightScatteringPass.isReady();
  70522. };
  70523. /**
  70524. * Sets the new light position for light scattering effect
  70525. * @param {BABYLON.Vector3} The new custom light position
  70526. */
  70527. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  70528. this.customMeshPosition = position;
  70529. };
  70530. /**
  70531. * Returns the light position for light scattering effect
  70532. * @return {BABYLON.Vector3} The custom light position
  70533. */
  70534. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  70535. return this.customMeshPosition;
  70536. };
  70537. /**
  70538. * Disposes the internal assets and detaches the post-process from the camera
  70539. */
  70540. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  70541. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  70542. if (rttIndex !== -1) {
  70543. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  70544. }
  70545. this._volumetricLightScatteringRTT.dispose();
  70546. _super.prototype.dispose.call(this, camera);
  70547. };
  70548. /**
  70549. * Returns the render target texture used by the post-process
  70550. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  70551. */
  70552. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  70553. return this._volumetricLightScatteringRTT;
  70554. };
  70555. // Private methods
  70556. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  70557. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  70558. return true;
  70559. }
  70560. return false;
  70561. };
  70562. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  70563. var _this = this;
  70564. var engine = scene.getEngine();
  70565. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  70566. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  70567. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  70568. this._volumetricLightScatteringRTT.renderList = null;
  70569. this._volumetricLightScatteringRTT.renderParticles = false;
  70570. this._volumetricLightScatteringRTT.ignoreCameraViewport = true;
  70571. var camera = this.getCamera();
  70572. if (camera) {
  70573. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  70574. }
  70575. else {
  70576. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  70577. }
  70578. // Custom render function for submeshes
  70579. var renderSubMesh = function (subMesh) {
  70580. var mesh = subMesh.getRenderingMesh();
  70581. if (_this._meshExcluded(mesh)) {
  70582. return;
  70583. }
  70584. var material = subMesh.getMaterial();
  70585. if (!material) {
  70586. return;
  70587. }
  70588. var scene = mesh.getScene();
  70589. var engine = scene.getEngine();
  70590. // Culling
  70591. engine.setState(material.backFaceCulling);
  70592. // Managing instances
  70593. var batch = mesh._getInstancesRenderList(subMesh._id);
  70594. if (batch.mustReturn) {
  70595. return;
  70596. }
  70597. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  70598. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  70599. var effect = _this._volumetricLightScatteringPass;
  70600. if (mesh === _this.mesh) {
  70601. if (subMesh.effect) {
  70602. effect = subMesh.effect;
  70603. }
  70604. else {
  70605. effect = material.getEffect();
  70606. }
  70607. }
  70608. engine.enableEffect(effect);
  70609. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  70610. if (mesh === _this.mesh) {
  70611. material.bind(mesh.getWorldMatrix(), mesh);
  70612. }
  70613. else {
  70614. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  70615. // Alpha test
  70616. if (material && material.needAlphaTesting()) {
  70617. var alphaTexture = material.getAlphaTestTexture();
  70618. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  70619. if (alphaTexture) {
  70620. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  70621. }
  70622. }
  70623. // Bones
  70624. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  70625. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  70626. }
  70627. }
  70628. // Draw
  70629. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  70630. }
  70631. };
  70632. // Render target texture callbacks
  70633. var savedSceneClearColor;
  70634. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  70635. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  70636. savedSceneClearColor = scene.clearColor;
  70637. scene.clearColor = sceneClearColor;
  70638. });
  70639. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  70640. scene.clearColor = savedSceneClearColor;
  70641. });
  70642. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  70643. var engine = scene.getEngine();
  70644. var index;
  70645. if (depthOnlySubMeshes.length) {
  70646. engine.setColorWrite(false);
  70647. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  70648. renderSubMesh(depthOnlySubMeshes.data[index]);
  70649. }
  70650. engine.setColorWrite(true);
  70651. }
  70652. for (index = 0; index < opaqueSubMeshes.length; index++) {
  70653. renderSubMesh(opaqueSubMeshes.data[index]);
  70654. }
  70655. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  70656. renderSubMesh(alphaTestSubMeshes.data[index]);
  70657. }
  70658. if (transparentSubMeshes.length) {
  70659. // Sort sub meshes
  70660. for (index = 0; index < transparentSubMeshes.length; index++) {
  70661. var submesh = transparentSubMeshes.data[index];
  70662. var boundingInfo = submesh.getBoundingInfo();
  70663. if (boundingInfo && scene.activeCamera) {
  70664. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  70665. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  70666. }
  70667. }
  70668. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  70669. sortedArray.sort(function (a, b) {
  70670. // Alpha index first
  70671. if (a._alphaIndex > b._alphaIndex) {
  70672. return 1;
  70673. }
  70674. if (a._alphaIndex < b._alphaIndex) {
  70675. return -1;
  70676. }
  70677. // Then distance to camera
  70678. if (a._distanceToCamera < b._distanceToCamera) {
  70679. return 1;
  70680. }
  70681. if (a._distanceToCamera > b._distanceToCamera) {
  70682. return -1;
  70683. }
  70684. return 0;
  70685. });
  70686. // Render sub meshes
  70687. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  70688. for (index = 0; index < sortedArray.length; index++) {
  70689. renderSubMesh(sortedArray[index]);
  70690. }
  70691. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  70692. }
  70693. };
  70694. };
  70695. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  70696. var transform = scene.getTransformMatrix();
  70697. var meshPosition;
  70698. if (this.useCustomMeshPosition) {
  70699. meshPosition = this.customMeshPosition;
  70700. }
  70701. else if (this.attachedNode) {
  70702. meshPosition = this.attachedNode.position;
  70703. }
  70704. else {
  70705. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  70706. }
  70707. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  70708. this._screenCoordinates.x = pos.x / this._viewPort.width;
  70709. this._screenCoordinates.y = pos.y / this._viewPort.height;
  70710. if (this.invert)
  70711. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  70712. };
  70713. // Static methods
  70714. /**
  70715. * Creates a default mesh for the Volumeric Light Scattering post-process
  70716. * @param {string} The mesh name
  70717. * @param {BABYLON.Scene} The scene where to create the mesh
  70718. * @return {BABYLON.Mesh} the default mesh
  70719. */
  70720. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  70721. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  70722. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  70723. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  70724. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  70725. mesh.material = material;
  70726. return mesh;
  70727. };
  70728. __decorate([
  70729. BABYLON.serializeAsVector3()
  70730. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  70731. __decorate([
  70732. BABYLON.serialize()
  70733. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  70734. __decorate([
  70735. BABYLON.serialize()
  70736. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  70737. __decorate([
  70738. BABYLON.serializeAsMeshReference()
  70739. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  70740. __decorate([
  70741. BABYLON.serialize()
  70742. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  70743. __decorate([
  70744. BABYLON.serialize()
  70745. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  70746. __decorate([
  70747. BABYLON.serialize()
  70748. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  70749. __decorate([
  70750. BABYLON.serialize()
  70751. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  70752. __decorate([
  70753. BABYLON.serialize()
  70754. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  70755. return VolumetricLightScatteringPostProcess;
  70756. }(BABYLON.PostProcess));
  70757. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  70758. })(BABYLON || (BABYLON = {}));
  70759. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  70760. //
  70761. // This post-process allows the modification of rendered colors by using
  70762. // a 'look-up table' (LUT). This effect is also called Color Grading.
  70763. //
  70764. // The object needs to be provided an url to a texture containing the color
  70765. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  70766. // Use an image editing software to tweak the LUT to match your needs.
  70767. //
  70768. // For an example of a color LUT, see here:
  70769. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  70770. // For explanations on color grading, see here:
  70771. // http://udn.epicgames.com/Three/ColorGrading.html
  70772. //
  70773. var BABYLON;
  70774. (function (BABYLON) {
  70775. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  70776. __extends(ColorCorrectionPostProcess, _super);
  70777. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  70778. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  70779. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  70780. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  70781. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  70782. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  70783. _this.onApply = function (effect) {
  70784. effect.setTexture("colorTable", _this._colorTableTexture);
  70785. };
  70786. return _this;
  70787. }
  70788. return ColorCorrectionPostProcess;
  70789. }(BABYLON.PostProcess));
  70790. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  70791. })(BABYLON || (BABYLON = {}));
  70792. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  70793. var BABYLON;
  70794. (function (BABYLON) {
  70795. var TonemappingOperator;
  70796. (function (TonemappingOperator) {
  70797. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  70798. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  70799. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  70800. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  70801. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  70802. ;
  70803. var TonemapPostProcess = /** @class */ (function (_super) {
  70804. __extends(TonemapPostProcess, _super);
  70805. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  70806. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  70807. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  70808. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  70809. _this._operator = _operator;
  70810. _this.exposureAdjustment = exposureAdjustment;
  70811. var defines = "#define ";
  70812. if (_this._operator === TonemappingOperator.Hable)
  70813. defines += "HABLE_TONEMAPPING";
  70814. else if (_this._operator === TonemappingOperator.Reinhard)
  70815. defines += "REINHARD_TONEMAPPING";
  70816. else if (_this._operator === TonemappingOperator.HejiDawson)
  70817. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  70818. else if (_this._operator === TonemappingOperator.Photographic)
  70819. defines += "PHOTOGRAPHIC_TONEMAPPING";
  70820. //sadly a second call to create the effect.
  70821. _this.updateEffect(defines);
  70822. _this.onApply = function (effect) {
  70823. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  70824. };
  70825. return _this;
  70826. }
  70827. return TonemapPostProcess;
  70828. }(BABYLON.PostProcess));
  70829. BABYLON.TonemapPostProcess = TonemapPostProcess;
  70830. })(BABYLON || (BABYLON = {}));
  70831. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  70832. var BABYLON;
  70833. (function (BABYLON) {
  70834. var DisplayPassPostProcess = /** @class */ (function (_super) {
  70835. __extends(DisplayPassPostProcess, _super);
  70836. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  70837. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  70838. }
  70839. return DisplayPassPostProcess;
  70840. }(BABYLON.PostProcess));
  70841. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  70842. })(BABYLON || (BABYLON = {}));
  70843. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  70844. var BABYLON;
  70845. (function (BABYLON) {
  70846. var HighlightsPostProcess = /** @class */ (function (_super) {
  70847. __extends(HighlightsPostProcess, _super);
  70848. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  70849. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  70850. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  70851. }
  70852. return HighlightsPostProcess;
  70853. }(BABYLON.PostProcess));
  70854. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  70855. })(BABYLON || (BABYLON = {}));
  70856. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  70857. var BABYLON;
  70858. (function (BABYLON) {
  70859. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  70860. __extends(ImageProcessingPostProcess, _super);
  70861. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  70862. if (camera === void 0) { camera = null; }
  70863. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  70864. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  70865. _this._fromLinearSpace = true;
  70866. /**
  70867. * Defines cache preventing GC.
  70868. */
  70869. _this._defines = {
  70870. IMAGEPROCESSING: false,
  70871. VIGNETTE: false,
  70872. VIGNETTEBLENDMODEMULTIPLY: false,
  70873. VIGNETTEBLENDMODEOPAQUE: false,
  70874. TONEMAPPING: false,
  70875. CONTRAST: false,
  70876. COLORCURVES: false,
  70877. COLORGRADING: false,
  70878. COLORGRADING3D: false,
  70879. FROMLINEARSPACE: false,
  70880. SAMPLER3DGREENDEPTH: false,
  70881. SAMPLER3DBGRMAP: false,
  70882. IMAGEPROCESSINGPOSTPROCESS: false,
  70883. EXPOSURE: false,
  70884. GRAIN: false,
  70885. };
  70886. // Setup the configuration as forced by the constructor. This would then not force the
  70887. // scene materials output in linear space and let untouched the default forward pass.
  70888. if (imageProcessingConfiguration) {
  70889. imageProcessingConfiguration.applyByPostProcess = true;
  70890. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  70891. // This will cause the shader to be compiled
  70892. _this.fromLinearSpace = false;
  70893. }
  70894. else {
  70895. _this._attachImageProcessingConfiguration(null, true);
  70896. _this.imageProcessingConfiguration.applyByPostProcess = true;
  70897. }
  70898. _this.onApply = function (effect) {
  70899. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  70900. };
  70901. return _this;
  70902. }
  70903. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  70904. /**
  70905. * Gets the image processing configuration used either in this material.
  70906. */
  70907. get: function () {
  70908. return this._imageProcessingConfiguration;
  70909. },
  70910. /**
  70911. * Sets the Default image processing configuration used either in the this material.
  70912. *
  70913. * If sets to null, the scene one is in use.
  70914. */
  70915. set: function (value) {
  70916. this._attachImageProcessingConfiguration(value);
  70917. },
  70918. enumerable: true,
  70919. configurable: true
  70920. });
  70921. /**
  70922. * Attaches a new image processing configuration to the PBR Material.
  70923. * @param configuration
  70924. */
  70925. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  70926. var _this = this;
  70927. if (doNotBuild === void 0) { doNotBuild = false; }
  70928. if (configuration === this._imageProcessingConfiguration) {
  70929. return;
  70930. }
  70931. // Detaches observer.
  70932. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  70933. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  70934. }
  70935. // Pick the scene configuration if needed.
  70936. if (!configuration) {
  70937. var scene = null;
  70938. var engine = this.getEngine();
  70939. var camera = this.getCamera();
  70940. if (camera) {
  70941. scene = camera.getScene();
  70942. }
  70943. else if (engine && engine.scenes) {
  70944. var scenes = engine.scenes;
  70945. scene = scenes[scenes.length - 1];
  70946. }
  70947. else {
  70948. scene = BABYLON.Engine.LastCreatedScene;
  70949. }
  70950. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  70951. }
  70952. else {
  70953. this._imageProcessingConfiguration = configuration;
  70954. }
  70955. // Attaches observer.
  70956. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  70957. _this._updateParameters();
  70958. });
  70959. // Ensure the effect will be rebuilt.
  70960. if (!doNotBuild) {
  70961. this._updateParameters();
  70962. }
  70963. };
  70964. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  70965. /**
  70966. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  70967. */
  70968. get: function () {
  70969. return this.imageProcessingConfiguration.colorCurves;
  70970. },
  70971. /**
  70972. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  70973. */
  70974. set: function (value) {
  70975. this.imageProcessingConfiguration.colorCurves = value;
  70976. },
  70977. enumerable: true,
  70978. configurable: true
  70979. });
  70980. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  70981. /**
  70982. * Gets wether the color curves effect is enabled.
  70983. */
  70984. get: function () {
  70985. return this.imageProcessingConfiguration.colorCurvesEnabled;
  70986. },
  70987. /**
  70988. * Sets wether the color curves effect is enabled.
  70989. */
  70990. set: function (value) {
  70991. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  70992. },
  70993. enumerable: true,
  70994. configurable: true
  70995. });
  70996. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  70997. /**
  70998. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  70999. */
  71000. get: function () {
  71001. return this.imageProcessingConfiguration.colorGradingTexture;
  71002. },
  71003. /**
  71004. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  71005. */
  71006. set: function (value) {
  71007. this.imageProcessingConfiguration.colorGradingTexture = value;
  71008. },
  71009. enumerable: true,
  71010. configurable: true
  71011. });
  71012. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  71013. /**
  71014. * Gets wether the color grading effect is enabled.
  71015. */
  71016. get: function () {
  71017. return this.imageProcessingConfiguration.colorGradingEnabled;
  71018. },
  71019. /**
  71020. * Gets wether the color grading effect is enabled.
  71021. */
  71022. set: function (value) {
  71023. this.imageProcessingConfiguration.colorGradingEnabled = value;
  71024. },
  71025. enumerable: true,
  71026. configurable: true
  71027. });
  71028. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  71029. /**
  71030. * Gets exposure used in the effect.
  71031. */
  71032. get: function () {
  71033. return this.imageProcessingConfiguration.exposure;
  71034. },
  71035. /**
  71036. * Sets exposure used in the effect.
  71037. */
  71038. set: function (value) {
  71039. this.imageProcessingConfiguration.exposure = value;
  71040. },
  71041. enumerable: true,
  71042. configurable: true
  71043. });
  71044. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  71045. /**
  71046. * Gets wether tonemapping is enabled or not.
  71047. */
  71048. get: function () {
  71049. return this._imageProcessingConfiguration.toneMappingEnabled;
  71050. },
  71051. /**
  71052. * Sets wether tonemapping is enabled or not
  71053. */
  71054. set: function (value) {
  71055. this._imageProcessingConfiguration.toneMappingEnabled = value;
  71056. },
  71057. enumerable: true,
  71058. configurable: true
  71059. });
  71060. ;
  71061. ;
  71062. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  71063. /**
  71064. * Gets contrast used in the effect.
  71065. */
  71066. get: function () {
  71067. return this.imageProcessingConfiguration.contrast;
  71068. },
  71069. /**
  71070. * Sets contrast used in the effect.
  71071. */
  71072. set: function (value) {
  71073. this.imageProcessingConfiguration.contrast = value;
  71074. },
  71075. enumerable: true,
  71076. configurable: true
  71077. });
  71078. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  71079. /**
  71080. * Gets Vignette stretch size.
  71081. */
  71082. get: function () {
  71083. return this.imageProcessingConfiguration.vignetteStretch;
  71084. },
  71085. /**
  71086. * Sets Vignette stretch size.
  71087. */
  71088. set: function (value) {
  71089. this.imageProcessingConfiguration.vignetteStretch = value;
  71090. },
  71091. enumerable: true,
  71092. configurable: true
  71093. });
  71094. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  71095. /**
  71096. * Gets Vignette centre X Offset.
  71097. */
  71098. get: function () {
  71099. return this.imageProcessingConfiguration.vignetteCentreX;
  71100. },
  71101. /**
  71102. * Sets Vignette centre X Offset.
  71103. */
  71104. set: function (value) {
  71105. this.imageProcessingConfiguration.vignetteCentreX = value;
  71106. },
  71107. enumerable: true,
  71108. configurable: true
  71109. });
  71110. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  71111. /**
  71112. * Gets Vignette centre Y Offset.
  71113. */
  71114. get: function () {
  71115. return this.imageProcessingConfiguration.vignetteCentreY;
  71116. },
  71117. /**
  71118. * Sets Vignette centre Y Offset.
  71119. */
  71120. set: function (value) {
  71121. this.imageProcessingConfiguration.vignetteCentreY = value;
  71122. },
  71123. enumerable: true,
  71124. configurable: true
  71125. });
  71126. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  71127. /**
  71128. * Gets Vignette weight or intensity of the vignette effect.
  71129. */
  71130. get: function () {
  71131. return this.imageProcessingConfiguration.vignetteWeight;
  71132. },
  71133. /**
  71134. * Sets Vignette weight or intensity of the vignette effect.
  71135. */
  71136. set: function (value) {
  71137. this.imageProcessingConfiguration.vignetteWeight = value;
  71138. },
  71139. enumerable: true,
  71140. configurable: true
  71141. });
  71142. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  71143. /**
  71144. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  71145. * if vignetteEnabled is set to true.
  71146. */
  71147. get: function () {
  71148. return this.imageProcessingConfiguration.vignetteColor;
  71149. },
  71150. /**
  71151. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  71152. * if vignetteEnabled is set to true.
  71153. */
  71154. set: function (value) {
  71155. this.imageProcessingConfiguration.vignetteColor = value;
  71156. },
  71157. enumerable: true,
  71158. configurable: true
  71159. });
  71160. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  71161. /**
  71162. * Gets Camera field of view used by the Vignette effect.
  71163. */
  71164. get: function () {
  71165. return this.imageProcessingConfiguration.vignetteCameraFov;
  71166. },
  71167. /**
  71168. * Sets Camera field of view used by the Vignette effect.
  71169. */
  71170. set: function (value) {
  71171. this.imageProcessingConfiguration.vignetteCameraFov = value;
  71172. },
  71173. enumerable: true,
  71174. configurable: true
  71175. });
  71176. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  71177. /**
  71178. * Gets the vignette blend mode allowing different kind of effect.
  71179. */
  71180. get: function () {
  71181. return this.imageProcessingConfiguration.vignetteBlendMode;
  71182. },
  71183. /**
  71184. * Sets the vignette blend mode allowing different kind of effect.
  71185. */
  71186. set: function (value) {
  71187. this.imageProcessingConfiguration.vignetteBlendMode = value;
  71188. },
  71189. enumerable: true,
  71190. configurable: true
  71191. });
  71192. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  71193. /**
  71194. * Gets wether the vignette effect is enabled.
  71195. */
  71196. get: function () {
  71197. return this.imageProcessingConfiguration.vignetteEnabled;
  71198. },
  71199. /**
  71200. * Sets wether the vignette effect is enabled.
  71201. */
  71202. set: function (value) {
  71203. this.imageProcessingConfiguration.vignetteEnabled = value;
  71204. },
  71205. enumerable: true,
  71206. configurable: true
  71207. });
  71208. Object.defineProperty(ImageProcessingPostProcess.prototype, "grainEnabled", {
  71209. /**
  71210. * Gets wether the grain effect is enabled.
  71211. */
  71212. get: function () {
  71213. return this.imageProcessingConfiguration.grainEnabled;
  71214. },
  71215. /**
  71216. * Sets wether the grain effect is enabled.
  71217. */
  71218. set: function (value) {
  71219. this.imageProcessingConfiguration.grainEnabled = value;
  71220. },
  71221. enumerable: true,
  71222. configurable: true
  71223. });
  71224. Object.defineProperty(ImageProcessingPostProcess.prototype, "grainIntensity", {
  71225. /**
  71226. * Gets the grain effect's intensity.
  71227. */
  71228. get: function () {
  71229. return this.imageProcessingConfiguration.grainIntensity;
  71230. },
  71231. /**
  71232. * Sets the grain effect's intensity.
  71233. */
  71234. set: function (value) {
  71235. this.imageProcessingConfiguration.grainIntensity = value;
  71236. },
  71237. enumerable: true,
  71238. configurable: true
  71239. });
  71240. Object.defineProperty(ImageProcessingPostProcess.prototype, "grainAnimated", {
  71241. /**
  71242. * Gets wether the grain effect is animated.
  71243. */
  71244. get: function () {
  71245. return this.imageProcessingConfiguration.grainAnimated;
  71246. },
  71247. /**
  71248. * Sets wether the grain effect is animated.
  71249. */
  71250. set: function (value) {
  71251. this.imageProcessingConfiguration.grainAnimated = value;
  71252. },
  71253. enumerable: true,
  71254. configurable: true
  71255. });
  71256. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  71257. /**
  71258. * Gets wether the input of the processing is in Gamma or Linear Space.
  71259. */
  71260. get: function () {
  71261. return this._fromLinearSpace;
  71262. },
  71263. /**
  71264. * Sets wether the input of the processing is in Gamma or Linear Space.
  71265. */
  71266. set: function (value) {
  71267. if (this._fromLinearSpace === value) {
  71268. return;
  71269. }
  71270. this._fromLinearSpace = value;
  71271. this._updateParameters();
  71272. },
  71273. enumerable: true,
  71274. configurable: true
  71275. });
  71276. ImageProcessingPostProcess.prototype.getClassName = function () {
  71277. return "ImageProcessingPostProcess";
  71278. };
  71279. ImageProcessingPostProcess.prototype._updateParameters = function () {
  71280. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  71281. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  71282. var defines = "";
  71283. for (var define in this._defines) {
  71284. if (this._defines[define]) {
  71285. defines += "#define " + define + ";\r\n";
  71286. }
  71287. }
  71288. var samplers = ["textureSampler"];
  71289. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  71290. var uniforms = ["scale"];
  71291. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  71292. this.updateEffect(defines, uniforms, samplers);
  71293. };
  71294. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  71295. _super.prototype.dispose.call(this, camera);
  71296. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  71297. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  71298. }
  71299. this.imageProcessingConfiguration.applyByPostProcess = false;
  71300. };
  71301. __decorate([
  71302. BABYLON.serialize()
  71303. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  71304. return ImageProcessingPostProcess;
  71305. }(BABYLON.PostProcess));
  71306. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  71307. })(BABYLON || (BABYLON = {}));
  71308. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  71309. var BABYLON;
  71310. (function (BABYLON) {
  71311. var Bone = /** @class */ (function (_super) {
  71312. __extends(Bone, _super);
  71313. function Bone(name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  71314. if (parentBone === void 0) { parentBone = null; }
  71315. if (localMatrix === void 0) { localMatrix = null; }
  71316. if (restPose === void 0) { restPose = null; }
  71317. if (baseMatrix === void 0) { baseMatrix = null; }
  71318. if (index === void 0) { index = null; }
  71319. var _this = _super.call(this, name, skeleton.getScene()) || this;
  71320. _this.name = name;
  71321. _this.children = new Array();
  71322. _this.animations = new Array();
  71323. // Set this value to map this bone to a different index in the transform matrices.
  71324. // Set this value to -1 to exclude the bone from the transform matrices.
  71325. _this._index = null;
  71326. _this._worldTransform = new BABYLON.Matrix();
  71327. _this._absoluteTransform = new BABYLON.Matrix();
  71328. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  71329. _this._scaleMatrix = BABYLON.Matrix.Identity();
  71330. _this._scaleVector = BABYLON.Vector3.One();
  71331. _this._negateScaleChildren = BABYLON.Vector3.One();
  71332. _this._scalingDeterminant = 1;
  71333. _this._skeleton = skeleton;
  71334. _this._localMatrix = localMatrix ? localMatrix : BABYLON.Matrix.Identity();
  71335. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  71336. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  71337. _this._index = index;
  71338. skeleton.bones.push(_this);
  71339. _this.setParent(parentBone, false);
  71340. _this._updateDifferenceMatrix();
  71341. return _this;
  71342. }
  71343. Object.defineProperty(Bone.prototype, "_matrix", {
  71344. get: function () {
  71345. return this._localMatrix;
  71346. },
  71347. set: function (val) {
  71348. if (this._localMatrix) {
  71349. this._localMatrix.copyFrom(val);
  71350. }
  71351. else {
  71352. this._localMatrix = val;
  71353. }
  71354. },
  71355. enumerable: true,
  71356. configurable: true
  71357. });
  71358. // Members
  71359. Bone.prototype.getSkeleton = function () {
  71360. return this._skeleton;
  71361. };
  71362. Bone.prototype.getParent = function () {
  71363. return this._parent;
  71364. };
  71365. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  71366. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  71367. if (this._parent === parent) {
  71368. return;
  71369. }
  71370. if (this._parent) {
  71371. var index = this._parent.children.indexOf(this);
  71372. if (index !== -1) {
  71373. this._parent.children.splice(index, 1);
  71374. }
  71375. }
  71376. this._parent = parent;
  71377. if (this._parent) {
  71378. this._parent.children.push(this);
  71379. }
  71380. if (updateDifferenceMatrix) {
  71381. this._updateDifferenceMatrix();
  71382. }
  71383. };
  71384. Bone.prototype.getLocalMatrix = function () {
  71385. return this._localMatrix;
  71386. };
  71387. Bone.prototype.getBaseMatrix = function () {
  71388. return this._baseMatrix;
  71389. };
  71390. Bone.prototype.getRestPose = function () {
  71391. return this._restPose;
  71392. };
  71393. Bone.prototype.returnToRest = function () {
  71394. this.updateMatrix(this._restPose.clone());
  71395. };
  71396. Bone.prototype.getWorldMatrix = function () {
  71397. return this._worldTransform;
  71398. };
  71399. Bone.prototype.getInvertedAbsoluteTransform = function () {
  71400. return this._invertedAbsoluteTransform;
  71401. };
  71402. Bone.prototype.getAbsoluteTransform = function () {
  71403. return this._absoluteTransform;
  71404. };
  71405. Object.defineProperty(Bone.prototype, "position", {
  71406. // Properties (matches AbstractMesh properties)
  71407. get: function () {
  71408. return this.getPosition();
  71409. },
  71410. set: function (newPosition) {
  71411. this.setPosition(newPosition);
  71412. },
  71413. enumerable: true,
  71414. configurable: true
  71415. });
  71416. Object.defineProperty(Bone.prototype, "rotation", {
  71417. get: function () {
  71418. return this.getRotation();
  71419. },
  71420. set: function (newRotation) {
  71421. this.setRotation(newRotation);
  71422. },
  71423. enumerable: true,
  71424. configurable: true
  71425. });
  71426. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  71427. get: function () {
  71428. return this.getRotationQuaternion();
  71429. },
  71430. set: function (newRotation) {
  71431. this.setRotationQuaternion(newRotation);
  71432. },
  71433. enumerable: true,
  71434. configurable: true
  71435. });
  71436. Object.defineProperty(Bone.prototype, "scaling", {
  71437. get: function () {
  71438. return this.getScale();
  71439. },
  71440. set: function (newScaling) {
  71441. this.setScale(newScaling.x, newScaling.y, newScaling.z);
  71442. },
  71443. enumerable: true,
  71444. configurable: true
  71445. });
  71446. Object.defineProperty(Bone.prototype, "animationPropertiesOverride", {
  71447. /**
  71448. * Gets the animation properties override
  71449. */
  71450. get: function () {
  71451. return this._skeleton.animationPropertiesOverride;
  71452. },
  71453. enumerable: true,
  71454. configurable: true
  71455. });
  71456. // Methods
  71457. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix) {
  71458. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  71459. this._baseMatrix = matrix.clone();
  71460. this._localMatrix = matrix.clone();
  71461. this._skeleton._markAsDirty();
  71462. if (updateDifferenceMatrix) {
  71463. this._updateDifferenceMatrix();
  71464. }
  71465. };
  71466. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  71467. if (!rootMatrix) {
  71468. rootMatrix = this._baseMatrix;
  71469. }
  71470. if (this._parent) {
  71471. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  71472. }
  71473. else {
  71474. this._absoluteTransform.copyFrom(rootMatrix);
  71475. }
  71476. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  71477. for (var index = 0; index < this.children.length; index++) {
  71478. this.children[index]._updateDifferenceMatrix();
  71479. }
  71480. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  71481. };
  71482. Bone.prototype.markAsDirty = function () {
  71483. this._currentRenderId++;
  71484. this._skeleton._markAsDirty();
  71485. };
  71486. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  71487. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  71488. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  71489. // all animation may be coming from a library skeleton, so may need to create animation
  71490. if (this.animations.length === 0) {
  71491. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  71492. this.animations[0].setKeys([]);
  71493. }
  71494. // get animation info / verify there is such a range from the source bone
  71495. var sourceRange = source.animations[0].getRange(rangeName);
  71496. if (!sourceRange) {
  71497. return false;
  71498. }
  71499. var from = sourceRange.from;
  71500. var to = sourceRange.to;
  71501. var sourceKeys = source.animations[0].getKeys();
  71502. // rescaling prep
  71503. var sourceBoneLength = source.length;
  71504. var sourceParent = source.getParent();
  71505. var parent = this.getParent();
  71506. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  71507. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  71508. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  71509. var destKeys = this.animations[0].getKeys();
  71510. // loop vars declaration
  71511. var orig;
  71512. var origTranslation;
  71513. var mat;
  71514. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  71515. orig = sourceKeys[key];
  71516. if (orig.frame >= from && orig.frame <= to) {
  71517. if (rescaleAsRequired) {
  71518. mat = orig.value.clone();
  71519. // scale based on parent ratio, when bone has parent
  71520. if (parentScalingReqd) {
  71521. origTranslation = mat.getTranslation();
  71522. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  71523. // scale based on skeleton dimension ratio when root bone, and value is passed
  71524. }
  71525. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  71526. origTranslation = mat.getTranslation();
  71527. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  71528. // use original when root bone, and no data for skelDimensionsRatio
  71529. }
  71530. else {
  71531. mat = orig.value;
  71532. }
  71533. }
  71534. else {
  71535. mat = orig.value;
  71536. }
  71537. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  71538. }
  71539. }
  71540. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  71541. return true;
  71542. };
  71543. /**
  71544. * Translate the bone in local or world space.
  71545. * @param vec The amount to translate the bone.
  71546. * @param space The space that the translation is in.
  71547. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  71548. */
  71549. Bone.prototype.translate = function (vec, space, mesh) {
  71550. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71551. var lm = this.getLocalMatrix();
  71552. if (space == BABYLON.Space.LOCAL) {
  71553. lm.m[12] += vec.x;
  71554. lm.m[13] += vec.y;
  71555. lm.m[14] += vec.z;
  71556. }
  71557. else {
  71558. var wm = null;
  71559. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  71560. if (mesh) {
  71561. wm = mesh.getWorldMatrix();
  71562. }
  71563. this._skeleton.computeAbsoluteTransforms();
  71564. var tmat = Bone._tmpMats[0];
  71565. var tvec = Bone._tmpVecs[0];
  71566. if (this._parent) {
  71567. if (mesh && wm) {
  71568. tmat.copyFrom(this._parent.getAbsoluteTransform());
  71569. tmat.multiplyToRef(wm, tmat);
  71570. }
  71571. else {
  71572. tmat.copyFrom(this._parent.getAbsoluteTransform());
  71573. }
  71574. }
  71575. tmat.m[12] = 0;
  71576. tmat.m[13] = 0;
  71577. tmat.m[14] = 0;
  71578. tmat.invert();
  71579. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  71580. lm.m[12] += tvec.x;
  71581. lm.m[13] += tvec.y;
  71582. lm.m[14] += tvec.z;
  71583. }
  71584. this.markAsDirty();
  71585. };
  71586. /**
  71587. * Set the postion of the bone in local or world space.
  71588. * @param position The position to set the bone.
  71589. * @param space The space that the position is in.
  71590. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  71591. */
  71592. Bone.prototype.setPosition = function (position, space, mesh) {
  71593. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71594. var lm = this.getLocalMatrix();
  71595. if (space == BABYLON.Space.LOCAL) {
  71596. lm.m[12] = position.x;
  71597. lm.m[13] = position.y;
  71598. lm.m[14] = position.z;
  71599. }
  71600. else {
  71601. var wm = null;
  71602. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  71603. if (mesh) {
  71604. wm = mesh.getWorldMatrix();
  71605. }
  71606. this._skeleton.computeAbsoluteTransforms();
  71607. var tmat = Bone._tmpMats[0];
  71608. var vec = Bone._tmpVecs[0];
  71609. if (this._parent) {
  71610. if (mesh && wm) {
  71611. tmat.copyFrom(this._parent.getAbsoluteTransform());
  71612. tmat.multiplyToRef(wm, tmat);
  71613. }
  71614. else {
  71615. tmat.copyFrom(this._parent.getAbsoluteTransform());
  71616. }
  71617. }
  71618. tmat.invert();
  71619. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  71620. lm.m[12] = vec.x;
  71621. lm.m[13] = vec.y;
  71622. lm.m[14] = vec.z;
  71623. }
  71624. this.markAsDirty();
  71625. };
  71626. /**
  71627. * Set the absolute postion of the bone (world space).
  71628. * @param position The position to set the bone.
  71629. * @param mesh The mesh that this bone is attached to.
  71630. */
  71631. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  71632. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  71633. };
  71634. /**
  71635. * Set the scale of the bone on the x, y and z axes.
  71636. * @param x The scale of the bone on the x axis.
  71637. * @param x The scale of the bone on the y axis.
  71638. * @param z The scale of the bone on the z axis.
  71639. * @param scaleChildren Set this to true if children of the bone should be scaled.
  71640. */
  71641. Bone.prototype.setScale = function (x, y, z, scaleChildren) {
  71642. if (scaleChildren === void 0) { scaleChildren = false; }
  71643. if (this.animations[0] && !this.animations[0].hasRunningRuntimeAnimations) {
  71644. if (!scaleChildren) {
  71645. this._negateScaleChildren.x = 1 / x;
  71646. this._negateScaleChildren.y = 1 / y;
  71647. this._negateScaleChildren.z = 1 / z;
  71648. }
  71649. this._syncScaleVector();
  71650. }
  71651. this.scale(x / this._scaleVector.x, y / this._scaleVector.y, z / this._scaleVector.z, scaleChildren);
  71652. };
  71653. /**
  71654. * Scale the bone on the x, y and z axes.
  71655. * @param x The amount to scale the bone on the x axis.
  71656. * @param x The amount to scale the bone on the y axis.
  71657. * @param z The amount to scale the bone on the z axis.
  71658. * @param scaleChildren Set this to true if children of the bone should be scaled.
  71659. */
  71660. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  71661. if (scaleChildren === void 0) { scaleChildren = false; }
  71662. var locMat = this.getLocalMatrix();
  71663. var origLocMat = Bone._tmpMats[0];
  71664. origLocMat.copyFrom(locMat);
  71665. var origLocMatInv = Bone._tmpMats[1];
  71666. origLocMatInv.copyFrom(origLocMat);
  71667. origLocMatInv.invert();
  71668. var scaleMat = Bone._tmpMats[2];
  71669. BABYLON.Matrix.FromValuesToRef(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1, scaleMat);
  71670. this._scaleMatrix.multiplyToRef(scaleMat, this._scaleMatrix);
  71671. this._scaleVector.x *= x;
  71672. this._scaleVector.y *= y;
  71673. this._scaleVector.z *= z;
  71674. locMat.multiplyToRef(origLocMatInv, locMat);
  71675. locMat.multiplyToRef(scaleMat, locMat);
  71676. locMat.multiplyToRef(origLocMat, locMat);
  71677. var parent = this.getParent();
  71678. if (parent) {
  71679. locMat.multiplyToRef(parent.getAbsoluteTransform(), this.getAbsoluteTransform());
  71680. }
  71681. else {
  71682. this.getAbsoluteTransform().copyFrom(locMat);
  71683. }
  71684. var len = this.children.length;
  71685. scaleMat.invert();
  71686. for (var i = 0; i < len; i++) {
  71687. var child = this.children[i];
  71688. var cm = child.getLocalMatrix();
  71689. cm.multiplyToRef(scaleMat, cm);
  71690. var lm = child.getLocalMatrix();
  71691. lm.m[12] *= x;
  71692. lm.m[13] *= y;
  71693. lm.m[14] *= z;
  71694. }
  71695. this.computeAbsoluteTransforms();
  71696. if (scaleChildren) {
  71697. for (var i = 0; i < len; i++) {
  71698. this.children[i].scale(x, y, z, scaleChildren);
  71699. }
  71700. }
  71701. this.markAsDirty();
  71702. };
  71703. /**
  71704. * Set the yaw, pitch, and roll of the bone in local or world space.
  71705. * @param yaw The rotation of the bone on the y axis.
  71706. * @param pitch The rotation of the bone on the x axis.
  71707. * @param roll The rotation of the bone on the z axis.
  71708. * @param space The space that the axes of rotation are in.
  71709. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  71710. */
  71711. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  71712. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71713. var rotMat = Bone._tmpMats[0];
  71714. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  71715. var rotMatInv = Bone._tmpMats[1];
  71716. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  71717. rotMatInv.multiplyToRef(rotMat, rotMat);
  71718. this._rotateWithMatrix(rotMat, space, mesh);
  71719. };
  71720. /**
  71721. * Rotate the bone on an axis in local or world space.
  71722. * @param axis The axis to rotate the bone on.
  71723. * @param amount The amount to rotate the bone.
  71724. * @param space The space that the axis is in.
  71725. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  71726. */
  71727. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  71728. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71729. var rmat = Bone._tmpMats[0];
  71730. rmat.m[12] = 0;
  71731. rmat.m[13] = 0;
  71732. rmat.m[14] = 0;
  71733. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  71734. this._rotateWithMatrix(rmat, space, mesh);
  71735. };
  71736. /**
  71737. * Set the rotation of the bone to a particular axis angle in local or world space.
  71738. * @param axis The axis to rotate the bone on.
  71739. * @param angle The angle that the bone should be rotated to.
  71740. * @param space The space that the axis is in.
  71741. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  71742. */
  71743. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  71744. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71745. var rotMat = Bone._tmpMats[0];
  71746. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  71747. var rotMatInv = Bone._tmpMats[1];
  71748. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  71749. rotMatInv.multiplyToRef(rotMat, rotMat);
  71750. this._rotateWithMatrix(rotMat, space, mesh);
  71751. };
  71752. /**
  71753. * Set the euler rotation of the bone in local of world space.
  71754. * @param rotation The euler rotation that the bone should be set to.
  71755. * @param space The space that the rotation is in.
  71756. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  71757. */
  71758. Bone.prototype.setRotation = function (rotation, space, mesh) {
  71759. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71760. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  71761. };
  71762. /**
  71763. * Set the quaternion rotation of the bone in local of world space.
  71764. * @param quat The quaternion rotation that the bone should be set to.
  71765. * @param space The space that the rotation is in.
  71766. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  71767. */
  71768. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  71769. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71770. var rotMatInv = Bone._tmpMats[0];
  71771. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  71772. var rotMat = Bone._tmpMats[1];
  71773. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  71774. rotMatInv.multiplyToRef(rotMat, rotMat);
  71775. this._rotateWithMatrix(rotMat, space, mesh);
  71776. };
  71777. /**
  71778. * Set the rotation matrix of the bone in local of world space.
  71779. * @param rotMat The rotation matrix that the bone should be set to.
  71780. * @param space The space that the rotation is in.
  71781. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  71782. */
  71783. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  71784. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71785. var rotMatInv = Bone._tmpMats[0];
  71786. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  71787. var rotMat2 = Bone._tmpMats[1];
  71788. rotMat2.copyFrom(rotMat);
  71789. rotMatInv.multiplyToRef(rotMat, rotMat2);
  71790. this._rotateWithMatrix(rotMat2, space, mesh);
  71791. };
  71792. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  71793. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71794. var lmat = this.getLocalMatrix();
  71795. var lx = lmat.m[12];
  71796. var ly = lmat.m[13];
  71797. var lz = lmat.m[14];
  71798. var parent = this.getParent();
  71799. var parentScale = Bone._tmpMats[3];
  71800. var parentScaleInv = Bone._tmpMats[4];
  71801. if (parent) {
  71802. if (space == BABYLON.Space.WORLD) {
  71803. if (mesh) {
  71804. parentScale.copyFrom(mesh.getWorldMatrix());
  71805. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  71806. }
  71807. else {
  71808. parentScale.copyFrom(parent.getAbsoluteTransform());
  71809. }
  71810. }
  71811. else {
  71812. parentScale = parent._scaleMatrix;
  71813. }
  71814. parentScaleInv.copyFrom(parentScale);
  71815. parentScaleInv.invert();
  71816. lmat.multiplyToRef(parentScale, lmat);
  71817. lmat.multiplyToRef(rmat, lmat);
  71818. lmat.multiplyToRef(parentScaleInv, lmat);
  71819. }
  71820. else {
  71821. if (space == BABYLON.Space.WORLD && mesh) {
  71822. parentScale.copyFrom(mesh.getWorldMatrix());
  71823. parentScaleInv.copyFrom(parentScale);
  71824. parentScaleInv.invert();
  71825. lmat.multiplyToRef(parentScale, lmat);
  71826. lmat.multiplyToRef(rmat, lmat);
  71827. lmat.multiplyToRef(parentScaleInv, lmat);
  71828. }
  71829. else {
  71830. lmat.multiplyToRef(rmat, lmat);
  71831. }
  71832. }
  71833. lmat.m[12] = lx;
  71834. lmat.m[13] = ly;
  71835. lmat.m[14] = lz;
  71836. this.computeAbsoluteTransforms();
  71837. this.markAsDirty();
  71838. };
  71839. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, space, mesh) {
  71840. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71841. if (space == BABYLON.Space.WORLD) {
  71842. var scaleMatrix = Bone._tmpMats[2];
  71843. scaleMatrix.copyFrom(this._scaleMatrix);
  71844. rotMatInv.copyFrom(this.getAbsoluteTransform());
  71845. if (mesh) {
  71846. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  71847. var meshScale = Bone._tmpMats[3];
  71848. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, meshScale);
  71849. scaleMatrix.multiplyToRef(meshScale, scaleMatrix);
  71850. }
  71851. rotMatInv.invert();
  71852. scaleMatrix.m[0] *= this._scalingDeterminant;
  71853. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  71854. }
  71855. else {
  71856. rotMatInv.copyFrom(this.getLocalMatrix());
  71857. rotMatInv.invert();
  71858. var scaleMatrix = Bone._tmpMats[2];
  71859. scaleMatrix.copyFrom(this._scaleMatrix);
  71860. if (this._parent) {
  71861. var pscaleMatrix = Bone._tmpMats[3];
  71862. pscaleMatrix.copyFrom(this._parent._scaleMatrix);
  71863. pscaleMatrix.invert();
  71864. pscaleMatrix.multiplyToRef(rotMatInv, rotMatInv);
  71865. }
  71866. else {
  71867. scaleMatrix.m[0] *= this._scalingDeterminant;
  71868. }
  71869. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  71870. }
  71871. };
  71872. /**
  71873. * Get the scale of the bone
  71874. * @returns the scale of the bone
  71875. */
  71876. Bone.prototype.getScale = function () {
  71877. return this._scaleVector.clone();
  71878. };
  71879. /**
  71880. * Copy the scale of the bone to a vector3.
  71881. * @param result The vector3 to copy the scale to
  71882. */
  71883. Bone.prototype.getScaleToRef = function (result) {
  71884. result.copyFrom(this._scaleVector);
  71885. };
  71886. /**
  71887. * Get the position of the bone in local or world space.
  71888. * @param space The space that the returned position is in.
  71889. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  71890. * @returns The position of the bone
  71891. */
  71892. Bone.prototype.getPosition = function (space, mesh) {
  71893. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71894. if (mesh === void 0) { mesh = null; }
  71895. var pos = BABYLON.Vector3.Zero();
  71896. this.getPositionToRef(space, mesh, pos);
  71897. return pos;
  71898. };
  71899. /**
  71900. * Copy the position of the bone to a vector3 in local or world space.
  71901. * @param space The space that the returned position is in.
  71902. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  71903. * @param result The vector3 to copy the position to.
  71904. */
  71905. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  71906. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71907. if (space == BABYLON.Space.LOCAL) {
  71908. var lm = this.getLocalMatrix();
  71909. result.x = lm.m[12];
  71910. result.y = lm.m[13];
  71911. result.z = lm.m[14];
  71912. }
  71913. else {
  71914. var wm = null;
  71915. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  71916. if (mesh) {
  71917. wm = mesh.getWorldMatrix();
  71918. }
  71919. this._skeleton.computeAbsoluteTransforms();
  71920. var tmat = Bone._tmpMats[0];
  71921. if (mesh && wm) {
  71922. tmat.copyFrom(this.getAbsoluteTransform());
  71923. tmat.multiplyToRef(wm, tmat);
  71924. }
  71925. else {
  71926. tmat = this.getAbsoluteTransform();
  71927. }
  71928. result.x = tmat.m[12];
  71929. result.y = tmat.m[13];
  71930. result.z = tmat.m[14];
  71931. }
  71932. };
  71933. /**
  71934. * Get the absolute position of the bone (world space).
  71935. * @param mesh The mesh that this bone is attached to.
  71936. * @returns The absolute position of the bone
  71937. */
  71938. Bone.prototype.getAbsolutePosition = function (mesh) {
  71939. if (mesh === void 0) { mesh = null; }
  71940. var pos = BABYLON.Vector3.Zero();
  71941. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  71942. return pos;
  71943. };
  71944. /**
  71945. * Copy the absolute position of the bone (world space) to the result param.
  71946. * @param mesh The mesh that this bone is attached to.
  71947. * @param result The vector3 to copy the absolute position to.
  71948. */
  71949. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  71950. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  71951. };
  71952. /**
  71953. * Compute the absolute transforms of this bone and its children.
  71954. */
  71955. Bone.prototype.computeAbsoluteTransforms = function () {
  71956. if (this._parent) {
  71957. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  71958. }
  71959. else {
  71960. this._absoluteTransform.copyFrom(this._localMatrix);
  71961. var poseMatrix = this._skeleton.getPoseMatrix();
  71962. if (poseMatrix) {
  71963. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  71964. }
  71965. }
  71966. var children = this.children;
  71967. var len = children.length;
  71968. for (var i = 0; i < len; i++) {
  71969. children[i].computeAbsoluteTransforms();
  71970. }
  71971. };
  71972. Bone.prototype._syncScaleVector = function () {
  71973. var lm = this.getLocalMatrix();
  71974. var xsq = (lm.m[0] * lm.m[0] + lm.m[1] * lm.m[1] + lm.m[2] * lm.m[2]);
  71975. var ysq = (lm.m[4] * lm.m[4] + lm.m[5] * lm.m[5] + lm.m[6] * lm.m[6]);
  71976. var zsq = (lm.m[8] * lm.m[8] + lm.m[9] * lm.m[9] + lm.m[10] * lm.m[10]);
  71977. var xs = lm.m[0] * lm.m[1] * lm.m[2] * lm.m[3] < 0 ? -1 : 1;
  71978. var ys = lm.m[4] * lm.m[5] * lm.m[6] * lm.m[7] < 0 ? -1 : 1;
  71979. var zs = lm.m[8] * lm.m[9] * lm.m[10] * lm.m[11] < 0 ? -1 : 1;
  71980. this._scaleVector.x = xs * Math.sqrt(xsq);
  71981. this._scaleVector.y = ys * Math.sqrt(ysq);
  71982. this._scaleVector.z = zs * Math.sqrt(zsq);
  71983. if (this._parent) {
  71984. this._scaleVector.x /= this._parent._negateScaleChildren.x;
  71985. this._scaleVector.y /= this._parent._negateScaleChildren.y;
  71986. this._scaleVector.z /= this._parent._negateScaleChildren.z;
  71987. }
  71988. 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);
  71989. };
  71990. /**
  71991. * Get the world direction from an axis that is in the local space of the bone.
  71992. * @param localAxis The local direction that is used to compute the world direction.
  71993. * @param mesh The mesh that this bone is attached to.
  71994. * @returns The world direction
  71995. */
  71996. Bone.prototype.getDirection = function (localAxis, mesh) {
  71997. if (mesh === void 0) { mesh = null; }
  71998. var result = BABYLON.Vector3.Zero();
  71999. this.getDirectionToRef(localAxis, mesh, result);
  72000. return result;
  72001. };
  72002. /**
  72003. * Copy the world direction to a vector3 from an axis that is in the local space of the bone.
  72004. * @param localAxis The local direction that is used to compute the world direction.
  72005. * @param mesh The mesh that this bone is attached to.
  72006. * @param result The vector3 that the world direction will be copied to.
  72007. */
  72008. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  72009. if (mesh === void 0) { mesh = null; }
  72010. var wm = null;
  72011. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  72012. if (mesh) {
  72013. wm = mesh.getWorldMatrix();
  72014. }
  72015. this._skeleton.computeAbsoluteTransforms();
  72016. var mat = Bone._tmpMats[0];
  72017. mat.copyFrom(this.getAbsoluteTransform());
  72018. if (mesh && wm) {
  72019. mat.multiplyToRef(wm, mat);
  72020. }
  72021. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  72022. result.normalize();
  72023. };
  72024. /**
  72025. * Get the euler rotation of the bone in local or world space.
  72026. * @param space The space that the rotation should be in.
  72027. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72028. * @returns The euler rotation
  72029. */
  72030. Bone.prototype.getRotation = function (space, mesh) {
  72031. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72032. if (mesh === void 0) { mesh = null; }
  72033. var result = BABYLON.Vector3.Zero();
  72034. this.getRotationToRef(space, mesh, result);
  72035. return result;
  72036. };
  72037. /**
  72038. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space.
  72039. * @param space The space that the rotation should be in.
  72040. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72041. * @param result The vector3 that the rotation should be copied to.
  72042. */
  72043. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  72044. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72045. if (mesh === void 0) { mesh = null; }
  72046. var quat = Bone._tmpQuat;
  72047. this.getRotationQuaternionToRef(space, mesh, quat);
  72048. quat.toEulerAnglesToRef(result);
  72049. };
  72050. /**
  72051. * Get the quaternion rotation of the bone in either local or world space.
  72052. * @param space The space that the rotation should be in.
  72053. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72054. * @returns The quaternion rotation
  72055. */
  72056. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  72057. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72058. if (mesh === void 0) { mesh = null; }
  72059. var result = BABYLON.Quaternion.Identity();
  72060. this.getRotationQuaternionToRef(space, mesh, result);
  72061. return result;
  72062. };
  72063. /**
  72064. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space.
  72065. * @param space The space that the rotation should be in.
  72066. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72067. * @param result The quaternion that the rotation should be copied to.
  72068. */
  72069. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  72070. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72071. if (mesh === void 0) { mesh = null; }
  72072. if (space == BABYLON.Space.LOCAL) {
  72073. this.getLocalMatrix().decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  72074. }
  72075. else {
  72076. var mat = Bone._tmpMats[0];
  72077. var amat = this.getAbsoluteTransform();
  72078. if (mesh) {
  72079. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  72080. }
  72081. else {
  72082. mat.copyFrom(amat);
  72083. }
  72084. mat.m[0] *= this._scalingDeterminant;
  72085. mat.m[1] *= this._scalingDeterminant;
  72086. mat.m[2] *= this._scalingDeterminant;
  72087. mat.decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  72088. }
  72089. };
  72090. /**
  72091. * Get the rotation matrix of the bone in local or world space.
  72092. * @param space The space that the rotation should be in.
  72093. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72094. * @returns The rotation matrix
  72095. */
  72096. Bone.prototype.getRotationMatrix = function (space, mesh) {
  72097. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72098. var result = BABYLON.Matrix.Identity();
  72099. this.getRotationMatrixToRef(space, mesh, result);
  72100. return result;
  72101. };
  72102. /**
  72103. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space.
  72104. * @param space The space that the rotation should be in.
  72105. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72106. * @param result The quaternion that the rotation should be copied to.
  72107. */
  72108. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  72109. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72110. if (space == BABYLON.Space.LOCAL) {
  72111. this.getLocalMatrix().getRotationMatrixToRef(result);
  72112. }
  72113. else {
  72114. var mat = Bone._tmpMats[0];
  72115. var amat = this.getAbsoluteTransform();
  72116. if (mesh) {
  72117. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  72118. }
  72119. else {
  72120. mat.copyFrom(amat);
  72121. }
  72122. mat.m[0] *= this._scalingDeterminant;
  72123. mat.m[1] *= this._scalingDeterminant;
  72124. mat.m[2] *= this._scalingDeterminant;
  72125. mat.getRotationMatrixToRef(result);
  72126. }
  72127. };
  72128. /**
  72129. * Get the world position of a point that is in the local space of the bone.
  72130. * @param position The local position
  72131. * @param mesh The mesh that this bone is attached to.
  72132. * @returns The world position
  72133. */
  72134. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  72135. if (mesh === void 0) { mesh = null; }
  72136. var result = BABYLON.Vector3.Zero();
  72137. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  72138. return result;
  72139. };
  72140. /**
  72141. * Get the world position of a point that is in the local space of the bone and copy it to the result param.
  72142. * @param position The local position
  72143. * @param mesh The mesh that this bone is attached to.
  72144. * @param result The vector3 that the world position should be copied to.
  72145. */
  72146. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  72147. if (mesh === void 0) { mesh = null; }
  72148. var wm = null;
  72149. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  72150. if (mesh) {
  72151. wm = mesh.getWorldMatrix();
  72152. }
  72153. this._skeleton.computeAbsoluteTransforms();
  72154. var tmat = Bone._tmpMats[0];
  72155. if (mesh && wm) {
  72156. tmat.copyFrom(this.getAbsoluteTransform());
  72157. tmat.multiplyToRef(wm, tmat);
  72158. }
  72159. else {
  72160. tmat = this.getAbsoluteTransform();
  72161. }
  72162. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  72163. };
  72164. /**
  72165. * Get the local position of a point that is in world space.
  72166. * @param position The world position
  72167. * @param mesh The mesh that this bone is attached to.
  72168. * @returns The local position
  72169. */
  72170. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  72171. if (mesh === void 0) { mesh = null; }
  72172. var result = BABYLON.Vector3.Zero();
  72173. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  72174. return result;
  72175. };
  72176. /**
  72177. * Get the local position of a point that is in world space and copy it to the result param.
  72178. * @param position The world position
  72179. * @param mesh The mesh that this bone is attached to.
  72180. * @param result The vector3 that the local position should be copied to.
  72181. */
  72182. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  72183. if (mesh === void 0) { mesh = null; }
  72184. var wm = null;
  72185. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  72186. if (mesh) {
  72187. wm = mesh.getWorldMatrix();
  72188. }
  72189. this._skeleton.computeAbsoluteTransforms();
  72190. var tmat = Bone._tmpMats[0];
  72191. tmat.copyFrom(this.getAbsoluteTransform());
  72192. if (mesh && wm) {
  72193. tmat.multiplyToRef(wm, tmat);
  72194. }
  72195. tmat.invert();
  72196. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  72197. };
  72198. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  72199. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  72200. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  72201. return Bone;
  72202. }(BABYLON.Node));
  72203. BABYLON.Bone = Bone;
  72204. })(BABYLON || (BABYLON = {}));
  72205. //# sourceMappingURL=babylon.bone.js.map
  72206. var BABYLON;
  72207. (function (BABYLON) {
  72208. var BoneIKController = /** @class */ (function () {
  72209. function BoneIKController(mesh, bone, options) {
  72210. this.targetPosition = BABYLON.Vector3.Zero();
  72211. this.poleTargetPosition = BABYLON.Vector3.Zero();
  72212. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  72213. this.poleAngle = 0;
  72214. this.slerpAmount = 1;
  72215. this._bone1Quat = BABYLON.Quaternion.Identity();
  72216. this._bone1Mat = BABYLON.Matrix.Identity();
  72217. this._bone2Ang = Math.PI;
  72218. this._maxAngle = Math.PI;
  72219. this._rightHandedSystem = false;
  72220. this._bendAxis = BABYLON.Vector3.Right();
  72221. this._slerping = false;
  72222. this._adjustRoll = 0;
  72223. this._bone2 = bone;
  72224. this._bone1 = bone.getParent();
  72225. if (!this._bone1) {
  72226. return;
  72227. }
  72228. this.mesh = mesh;
  72229. var bonePos = bone.getPosition();
  72230. if (bone.getAbsoluteTransform().determinant() > 0) {
  72231. this._rightHandedSystem = true;
  72232. this._bendAxis.x = 0;
  72233. this._bendAxis.y = 0;
  72234. this._bendAxis.z = -1;
  72235. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  72236. this._adjustRoll = Math.PI * .5;
  72237. this._bendAxis.z = 1;
  72238. }
  72239. }
  72240. if (this._bone1.length) {
  72241. var boneScale1 = this._bone1.getScale();
  72242. var boneScale2 = this._bone2.getScale();
  72243. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  72244. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  72245. }
  72246. else if (this._bone1.children[0]) {
  72247. mesh.computeWorldMatrix(true);
  72248. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  72249. var pos2 = this._bone2.getAbsolutePosition(mesh);
  72250. var pos3 = this._bone1.getAbsolutePosition(mesh);
  72251. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  72252. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  72253. }
  72254. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  72255. this.maxAngle = Math.PI;
  72256. if (options) {
  72257. if (options.targetMesh) {
  72258. this.targetMesh = options.targetMesh;
  72259. this.targetMesh.computeWorldMatrix(true);
  72260. }
  72261. if (options.poleTargetMesh) {
  72262. this.poleTargetMesh = options.poleTargetMesh;
  72263. this.poleTargetMesh.computeWorldMatrix(true);
  72264. }
  72265. else if (options.poleTargetBone) {
  72266. this.poleTargetBone = options.poleTargetBone;
  72267. }
  72268. else if (this._bone1.getParent()) {
  72269. this.poleTargetBone = this._bone1.getParent();
  72270. }
  72271. if (options.poleTargetLocalOffset) {
  72272. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  72273. }
  72274. if (options.poleAngle) {
  72275. this.poleAngle = options.poleAngle;
  72276. }
  72277. if (options.bendAxis) {
  72278. this._bendAxis.copyFrom(options.bendAxis);
  72279. }
  72280. if (options.maxAngle) {
  72281. this.maxAngle = options.maxAngle;
  72282. }
  72283. if (options.slerpAmount) {
  72284. this.slerpAmount = options.slerpAmount;
  72285. }
  72286. }
  72287. }
  72288. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  72289. get: function () {
  72290. return this._maxAngle;
  72291. },
  72292. set: function (value) {
  72293. this._setMaxAngle(value);
  72294. },
  72295. enumerable: true,
  72296. configurable: true
  72297. });
  72298. BoneIKController.prototype._setMaxAngle = function (ang) {
  72299. if (ang < 0) {
  72300. ang = 0;
  72301. }
  72302. if (ang > Math.PI || ang == undefined) {
  72303. ang = Math.PI;
  72304. }
  72305. this._maxAngle = ang;
  72306. var a = this._bone1Length;
  72307. var b = this._bone2Length;
  72308. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  72309. };
  72310. BoneIKController.prototype.update = function () {
  72311. var bone1 = this._bone1;
  72312. if (!bone1) {
  72313. return;
  72314. }
  72315. var target = this.targetPosition;
  72316. var poleTarget = this.poleTargetPosition;
  72317. var mat1 = BoneIKController._tmpMats[0];
  72318. var mat2 = BoneIKController._tmpMats[1];
  72319. if (this.targetMesh) {
  72320. target.copyFrom(this.targetMesh.getAbsolutePosition());
  72321. }
  72322. if (this.poleTargetBone) {
  72323. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  72324. }
  72325. else if (this.poleTargetMesh) {
  72326. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  72327. }
  72328. var bonePos = BoneIKController._tmpVecs[0];
  72329. var zaxis = BoneIKController._tmpVecs[1];
  72330. var xaxis = BoneIKController._tmpVecs[2];
  72331. var yaxis = BoneIKController._tmpVecs[3];
  72332. var upAxis = BoneIKController._tmpVecs[4];
  72333. var _tmpQuat = BoneIKController._tmpQuat;
  72334. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  72335. poleTarget.subtractToRef(bonePos, upAxis);
  72336. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  72337. upAxis.y = 1;
  72338. }
  72339. else {
  72340. upAxis.normalize();
  72341. }
  72342. target.subtractToRef(bonePos, yaxis);
  72343. yaxis.normalize();
  72344. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  72345. zaxis.normalize();
  72346. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  72347. xaxis.normalize();
  72348. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  72349. var a = this._bone1Length;
  72350. var b = this._bone2Length;
  72351. var c = BABYLON.Vector3.Distance(bonePos, target);
  72352. if (this._maxReach > 0) {
  72353. c = Math.min(this._maxReach, c);
  72354. }
  72355. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  72356. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  72357. if (acosa > 1) {
  72358. acosa = 1;
  72359. }
  72360. if (acosb > 1) {
  72361. acosb = 1;
  72362. }
  72363. if (acosa < -1) {
  72364. acosa = -1;
  72365. }
  72366. if (acosb < -1) {
  72367. acosb = -1;
  72368. }
  72369. var angA = Math.acos(acosa);
  72370. var angB = Math.acos(acosb);
  72371. var angC = -angA - angB;
  72372. if (this._rightHandedSystem) {
  72373. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  72374. mat2.multiplyToRef(mat1, mat1);
  72375. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  72376. mat2.multiplyToRef(mat1, mat1);
  72377. }
  72378. else {
  72379. var _tmpVec = BoneIKController._tmpVecs[5];
  72380. _tmpVec.copyFrom(this._bendAxis);
  72381. _tmpVec.x *= -1;
  72382. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  72383. mat2.multiplyToRef(mat1, mat1);
  72384. }
  72385. if (this.poleAngle) {
  72386. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  72387. mat1.multiplyToRef(mat2, mat1);
  72388. }
  72389. if (this._bone1) {
  72390. if (this.slerpAmount < 1) {
  72391. if (!this._slerping) {
  72392. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  72393. }
  72394. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  72395. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  72396. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  72397. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  72398. this._slerping = true;
  72399. }
  72400. else {
  72401. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  72402. this._bone1Mat.copyFrom(mat1);
  72403. this._slerping = false;
  72404. }
  72405. }
  72406. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  72407. this._bone2Ang = angC;
  72408. };
  72409. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  72410. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  72411. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  72412. return BoneIKController;
  72413. }());
  72414. BABYLON.BoneIKController = BoneIKController;
  72415. })(BABYLON || (BABYLON = {}));
  72416. //# sourceMappingURL=babylon.boneIKController.js.map
  72417. var BABYLON;
  72418. (function (BABYLON) {
  72419. var BoneLookController = /** @class */ (function () {
  72420. /**
  72421. * Create a BoneLookController
  72422. * @param mesh the mesh that the bone belongs to
  72423. * @param bone the bone that will be looking to the target
  72424. * @param target the target Vector3 to look at
  72425. * @param settings optional settings:
  72426. * - maxYaw: the maximum angle the bone will yaw to
  72427. * - minYaw: the minimum angle the bone will yaw to
  72428. * - maxPitch: the maximum angle the bone will pitch to
  72429. * - minPitch: the minimum angle the bone will yaw to
  72430. * - slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  72431. * - upAxis: the up axis of the coordinate system
  72432. * - upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  72433. * - yawAxis: set yawAxis if the bone does not yaw on the y axis
  72434. * - pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  72435. * - adjustYaw: used to make an adjustment to the yaw of the bone
  72436. * - adjustPitch: used to make an adjustment to the pitch of the bone
  72437. * - adjustRoll: used to make an adjustment to the roll of the bone
  72438. **/
  72439. function BoneLookController(mesh, bone, target, options) {
  72440. /**
  72441. * The up axis of the coordinate system that is used when the bone is rotated.
  72442. */
  72443. this.upAxis = BABYLON.Vector3.Up();
  72444. /**
  72445. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  72446. */
  72447. this.upAxisSpace = BABYLON.Space.LOCAL;
  72448. /**
  72449. * Used to make an adjustment to the yaw of the bone.
  72450. */
  72451. this.adjustYaw = 0;
  72452. /**
  72453. * Used to make an adjustment to the pitch of the bone.
  72454. */
  72455. this.adjustPitch = 0;
  72456. /**
  72457. * Used to make an adjustment to the roll of the bone.
  72458. */
  72459. this.adjustRoll = 0;
  72460. /**
  72461. * 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).
  72462. */
  72463. this.slerpAmount = 1;
  72464. this._boneQuat = BABYLON.Quaternion.Identity();
  72465. this._slerping = false;
  72466. this._firstFrameSkipped = false;
  72467. this._fowardAxis = BABYLON.Vector3.Forward();
  72468. this.mesh = mesh;
  72469. this.bone = bone;
  72470. this.target = target;
  72471. if (options) {
  72472. if (options.adjustYaw) {
  72473. this.adjustYaw = options.adjustYaw;
  72474. }
  72475. if (options.adjustPitch) {
  72476. this.adjustPitch = options.adjustPitch;
  72477. }
  72478. if (options.adjustRoll) {
  72479. this.adjustRoll = options.adjustRoll;
  72480. }
  72481. if (options.maxYaw != null) {
  72482. this.maxYaw = options.maxYaw;
  72483. }
  72484. else {
  72485. this.maxYaw = Math.PI;
  72486. }
  72487. if (options.minYaw != null) {
  72488. this.minYaw = options.minYaw;
  72489. }
  72490. else {
  72491. this.minYaw = -Math.PI;
  72492. }
  72493. if (options.maxPitch != null) {
  72494. this.maxPitch = options.maxPitch;
  72495. }
  72496. else {
  72497. this.maxPitch = Math.PI;
  72498. }
  72499. if (options.minPitch != null) {
  72500. this.minPitch = options.minPitch;
  72501. }
  72502. else {
  72503. this.minPitch = -Math.PI;
  72504. }
  72505. if (options.slerpAmount != null) {
  72506. this.slerpAmount = options.slerpAmount;
  72507. }
  72508. if (options.upAxis != null) {
  72509. this.upAxis = options.upAxis;
  72510. }
  72511. if (options.upAxisSpace != null) {
  72512. this.upAxisSpace = options.upAxisSpace;
  72513. }
  72514. if (options.yawAxis != null || options.pitchAxis != null) {
  72515. var newYawAxis = BABYLON.Axis.Y;
  72516. var newPitchAxis = BABYLON.Axis.X;
  72517. if (options.yawAxis != null) {
  72518. newYawAxis = options.yawAxis.clone();
  72519. newYawAxis.normalize();
  72520. }
  72521. if (options.pitchAxis != null) {
  72522. newPitchAxis = options.pitchAxis.clone();
  72523. newPitchAxis.normalize();
  72524. }
  72525. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  72526. this._transformYawPitch = BABYLON.Matrix.Identity();
  72527. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  72528. this._transformYawPitchInv = this._transformYawPitch.clone();
  72529. this._transformYawPitch.invert();
  72530. }
  72531. }
  72532. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  72533. this.upAxisSpace = BABYLON.Space.LOCAL;
  72534. }
  72535. }
  72536. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  72537. /**
  72538. * Get/set the minimum yaw angle that the bone can look to.
  72539. */
  72540. get: function () {
  72541. return this._minYaw;
  72542. },
  72543. set: function (value) {
  72544. this._minYaw = value;
  72545. this._minYawSin = Math.sin(value);
  72546. this._minYawCos = Math.cos(value);
  72547. if (this._maxYaw != null) {
  72548. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  72549. this._yawRange = this._maxYaw - this._minYaw;
  72550. }
  72551. },
  72552. enumerable: true,
  72553. configurable: true
  72554. });
  72555. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  72556. /**
  72557. * Get/set the maximum yaw angle that the bone can look to.
  72558. */
  72559. get: function () {
  72560. return this._maxYaw;
  72561. },
  72562. set: function (value) {
  72563. this._maxYaw = value;
  72564. this._maxYawSin = Math.sin(value);
  72565. this._maxYawCos = Math.cos(value);
  72566. if (this._minYaw != null) {
  72567. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  72568. this._yawRange = this._maxYaw - this._minYaw;
  72569. }
  72570. },
  72571. enumerable: true,
  72572. configurable: true
  72573. });
  72574. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  72575. /**
  72576. * Get/set the minimum pitch angle that the bone can look to.
  72577. */
  72578. get: function () {
  72579. return this._minPitch;
  72580. },
  72581. set: function (value) {
  72582. this._minPitch = value;
  72583. this._minPitchTan = Math.tan(value);
  72584. },
  72585. enumerable: true,
  72586. configurable: true
  72587. });
  72588. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  72589. /**
  72590. * Get/set the maximum pitch angle that the bone can look to.
  72591. */
  72592. get: function () {
  72593. return this._maxPitch;
  72594. },
  72595. set: function (value) {
  72596. this._maxPitch = value;
  72597. this._maxPitchTan = Math.tan(value);
  72598. },
  72599. enumerable: true,
  72600. configurable: true
  72601. });
  72602. /**
  72603. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender()).
  72604. */
  72605. BoneLookController.prototype.update = function () {
  72606. //skip the first frame when slerping so that the mesh rotation is correct
  72607. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  72608. this._firstFrameSkipped = true;
  72609. return;
  72610. }
  72611. var bone = this.bone;
  72612. var bonePos = BoneLookController._tmpVecs[0];
  72613. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  72614. var target = this.target;
  72615. var _tmpMat1 = BoneLookController._tmpMats[0];
  72616. var _tmpMat2 = BoneLookController._tmpMats[1];
  72617. var mesh = this.mesh;
  72618. var parentBone = bone.getParent();
  72619. var upAxis = BoneLookController._tmpVecs[1];
  72620. upAxis.copyFrom(this.upAxis);
  72621. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  72622. if (this._transformYawPitch) {
  72623. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  72624. }
  72625. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  72626. }
  72627. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  72628. mesh.getDirectionToRef(upAxis, upAxis);
  72629. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  72630. upAxis.normalize();
  72631. }
  72632. }
  72633. var checkYaw = false;
  72634. var checkPitch = false;
  72635. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  72636. checkYaw = true;
  72637. }
  72638. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  72639. checkPitch = true;
  72640. }
  72641. if (checkYaw || checkPitch) {
  72642. var spaceMat = BoneLookController._tmpMats[2];
  72643. var spaceMatInv = BoneLookController._tmpMats[3];
  72644. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  72645. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  72646. }
  72647. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  72648. spaceMat.copyFrom(mesh.getWorldMatrix());
  72649. }
  72650. else {
  72651. var forwardAxis = BoneLookController._tmpVecs[2];
  72652. forwardAxis.copyFrom(this._fowardAxis);
  72653. if (this._transformYawPitch) {
  72654. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  72655. }
  72656. if (parentBone) {
  72657. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  72658. }
  72659. else {
  72660. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  72661. }
  72662. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  72663. rightAxis.normalize();
  72664. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  72665. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  72666. }
  72667. spaceMat.invertToRef(spaceMatInv);
  72668. var xzlen = null;
  72669. if (checkPitch) {
  72670. var localTarget = BoneLookController._tmpVecs[3];
  72671. target.subtractToRef(bonePos, localTarget);
  72672. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  72673. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  72674. var pitch = Math.atan2(localTarget.y, xzlen);
  72675. var newPitch = pitch;
  72676. if (pitch > this._maxPitch) {
  72677. localTarget.y = this._maxPitchTan * xzlen;
  72678. newPitch = this._maxPitch;
  72679. }
  72680. else if (pitch < this._minPitch) {
  72681. localTarget.y = this._minPitchTan * xzlen;
  72682. newPitch = this._minPitch;
  72683. }
  72684. if (pitch != newPitch) {
  72685. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  72686. localTarget.addInPlace(bonePos);
  72687. target = localTarget;
  72688. }
  72689. }
  72690. if (checkYaw) {
  72691. var localTarget = BoneLookController._tmpVecs[4];
  72692. target.subtractToRef(bonePos, localTarget);
  72693. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  72694. var yaw = Math.atan2(localTarget.x, localTarget.z);
  72695. var newYaw = yaw;
  72696. if (yaw > this._maxYaw || yaw < this._minYaw) {
  72697. if (xzlen == null) {
  72698. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  72699. }
  72700. if (this._yawRange > Math.PI) {
  72701. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  72702. localTarget.z = this._maxYawCos * xzlen;
  72703. localTarget.x = this._maxYawSin * xzlen;
  72704. newYaw = this._maxYaw;
  72705. }
  72706. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  72707. localTarget.z = this._minYawCos * xzlen;
  72708. localTarget.x = this._minYawSin * xzlen;
  72709. newYaw = this._minYaw;
  72710. }
  72711. }
  72712. else {
  72713. if (yaw > this._maxYaw) {
  72714. localTarget.z = this._maxYawCos * xzlen;
  72715. localTarget.x = this._maxYawSin * xzlen;
  72716. newYaw = this._maxYaw;
  72717. }
  72718. else if (yaw < this._minYaw) {
  72719. localTarget.z = this._minYawCos * xzlen;
  72720. localTarget.x = this._minYawSin * xzlen;
  72721. newYaw = this._minYaw;
  72722. }
  72723. }
  72724. }
  72725. if (this._slerping && this._yawRange > Math.PI) {
  72726. //are we going to be crossing into the min/max region?
  72727. var boneFwd = BoneLookController._tmpVecs[8];
  72728. boneFwd.copyFrom(BABYLON.Axis.Z);
  72729. if (this._transformYawPitch) {
  72730. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  72731. }
  72732. var boneRotMat = BoneLookController._tmpMats[4];
  72733. this._boneQuat.toRotationMatrix(boneRotMat);
  72734. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  72735. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  72736. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  72737. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  72738. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  72739. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  72740. if (angBtwTar > angBtwMidYaw) {
  72741. if (xzlen == null) {
  72742. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  72743. }
  72744. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  72745. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  72746. if (angBtwMin < angBtwMax) {
  72747. newYaw = boneYaw + Math.PI * .75;
  72748. localTarget.z = Math.cos(newYaw) * xzlen;
  72749. localTarget.x = Math.sin(newYaw) * xzlen;
  72750. }
  72751. else {
  72752. newYaw = boneYaw - Math.PI * .75;
  72753. localTarget.z = Math.cos(newYaw) * xzlen;
  72754. localTarget.x = Math.sin(newYaw) * xzlen;
  72755. }
  72756. }
  72757. }
  72758. if (yaw != newYaw) {
  72759. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  72760. localTarget.addInPlace(bonePos);
  72761. target = localTarget;
  72762. }
  72763. }
  72764. }
  72765. var zaxis = BoneLookController._tmpVecs[5];
  72766. var xaxis = BoneLookController._tmpVecs[6];
  72767. var yaxis = BoneLookController._tmpVecs[7];
  72768. var _tmpQuat = BoneLookController._tmpQuat;
  72769. target.subtractToRef(bonePos, zaxis);
  72770. zaxis.normalize();
  72771. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  72772. xaxis.normalize();
  72773. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  72774. yaxis.normalize();
  72775. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  72776. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  72777. return;
  72778. }
  72779. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  72780. return;
  72781. }
  72782. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  72783. return;
  72784. }
  72785. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  72786. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  72787. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  72788. }
  72789. if (this.slerpAmount < 1) {
  72790. if (!this._slerping) {
  72791. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  72792. }
  72793. if (this._transformYawPitch) {
  72794. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  72795. }
  72796. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  72797. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  72798. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  72799. this._slerping = true;
  72800. }
  72801. else {
  72802. if (this._transformYawPitch) {
  72803. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  72804. }
  72805. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  72806. this._slerping = false;
  72807. }
  72808. };
  72809. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  72810. var angDiff = ang2 - ang1;
  72811. angDiff %= Math.PI * 2;
  72812. if (angDiff > Math.PI) {
  72813. angDiff -= Math.PI * 2;
  72814. }
  72815. else if (angDiff < -Math.PI) {
  72816. angDiff += Math.PI * 2;
  72817. }
  72818. return angDiff;
  72819. };
  72820. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  72821. ang1 %= (2 * Math.PI);
  72822. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  72823. ang2 %= (2 * Math.PI);
  72824. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  72825. var ab = 0;
  72826. if (ang1 < ang2) {
  72827. ab = ang2 - ang1;
  72828. }
  72829. else {
  72830. ab = ang1 - ang2;
  72831. }
  72832. if (ab > Math.PI) {
  72833. ab = Math.PI * 2 - ab;
  72834. }
  72835. return ab;
  72836. };
  72837. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  72838. ang %= (2 * Math.PI);
  72839. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  72840. ang1 %= (2 * Math.PI);
  72841. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  72842. ang2 %= (2 * Math.PI);
  72843. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  72844. if (ang1 < ang2) {
  72845. if (ang > ang1 && ang < ang2) {
  72846. return true;
  72847. }
  72848. }
  72849. else {
  72850. if (ang > ang2 && ang < ang1) {
  72851. return true;
  72852. }
  72853. }
  72854. return false;
  72855. };
  72856. 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()];
  72857. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  72858. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  72859. return BoneLookController;
  72860. }());
  72861. BABYLON.BoneLookController = BoneLookController;
  72862. })(BABYLON || (BABYLON = {}));
  72863. //# sourceMappingURL=babylon.boneLookController.js.map
  72864. var BABYLON;
  72865. (function (BABYLON) {
  72866. var Skeleton = /** @class */ (function () {
  72867. function Skeleton(name, id, scene) {
  72868. this.name = name;
  72869. this.id = id;
  72870. this.bones = new Array();
  72871. this.needInitialSkinMatrix = false;
  72872. this._isDirty = true;
  72873. this._meshesWithPoseMatrix = new Array();
  72874. this._identity = BABYLON.Matrix.Identity();
  72875. this._ranges = {};
  72876. this._lastAbsoluteTransformsUpdateId = -1;
  72877. /**
  72878. * Specifies if the skeleton should be serialized.
  72879. */
  72880. this.doNotSerialize = false;
  72881. // Events
  72882. /**
  72883. * An event triggered before computing the skeleton's matrices
  72884. * @type {BABYLON.Observable}
  72885. */
  72886. this.onBeforeComputeObservable = new BABYLON.Observable();
  72887. this.bones = [];
  72888. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  72889. scene.skeletons.push(this);
  72890. //make sure it will recalculate the matrix next time prepare is called.
  72891. this._isDirty = true;
  72892. }
  72893. // Members
  72894. Skeleton.prototype.getTransformMatrices = function (mesh) {
  72895. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  72896. return mesh._bonesTransformMatrices;
  72897. }
  72898. if (!this._transformMatrices) {
  72899. this.prepare();
  72900. }
  72901. return this._transformMatrices;
  72902. };
  72903. Skeleton.prototype.getScene = function () {
  72904. return this._scene;
  72905. };
  72906. // Methods
  72907. /**
  72908. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  72909. */
  72910. Skeleton.prototype.toString = function (fullDetails) {
  72911. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  72912. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  72913. if (fullDetails) {
  72914. ret += ", Ranges: {";
  72915. var first = true;
  72916. for (var name_1 in this._ranges) {
  72917. if (first) {
  72918. ret += ", ";
  72919. first = false;
  72920. }
  72921. ret += name_1;
  72922. }
  72923. ret += "}";
  72924. }
  72925. return ret;
  72926. };
  72927. /**
  72928. * Get bone's index searching by name
  72929. * @param {string} name is bone's name to search for
  72930. * @return {number} Indice of the bone. Returns -1 if not found
  72931. */
  72932. Skeleton.prototype.getBoneIndexByName = function (name) {
  72933. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  72934. if (this.bones[boneIndex].name === name) {
  72935. return boneIndex;
  72936. }
  72937. }
  72938. return -1;
  72939. };
  72940. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  72941. // check name not already in use
  72942. if (!this._ranges[name]) {
  72943. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  72944. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  72945. if (this.bones[i].animations[0]) {
  72946. this.bones[i].animations[0].createRange(name, from, to);
  72947. }
  72948. }
  72949. }
  72950. };
  72951. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  72952. if (deleteFrames === void 0) { deleteFrames = true; }
  72953. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  72954. if (this.bones[i].animations[0]) {
  72955. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  72956. }
  72957. }
  72958. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  72959. };
  72960. Skeleton.prototype.getAnimationRange = function (name) {
  72961. return this._ranges[name];
  72962. };
  72963. /**
  72964. * Returns as an Array, all AnimationRanges defined on this skeleton
  72965. */
  72966. Skeleton.prototype.getAnimationRanges = function () {
  72967. var animationRanges = [];
  72968. var name;
  72969. var i = 0;
  72970. for (name in this._ranges) {
  72971. animationRanges[i] = this._ranges[name];
  72972. i++;
  72973. }
  72974. return animationRanges;
  72975. };
  72976. /**
  72977. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  72978. */
  72979. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  72980. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  72981. if (this._ranges[name] || !source.getAnimationRange(name)) {
  72982. return false;
  72983. }
  72984. var ret = true;
  72985. var frameOffset = this._getHighestAnimationFrame() + 1;
  72986. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  72987. var boneDict = {};
  72988. var sourceBones = source.bones;
  72989. var nBones;
  72990. var i;
  72991. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  72992. boneDict[sourceBones[i].name] = sourceBones[i];
  72993. }
  72994. if (this.bones.length !== sourceBones.length) {
  72995. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  72996. ret = false;
  72997. }
  72998. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  72999. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  73000. var boneName = this.bones[i].name;
  73001. var sourceBone = boneDict[boneName];
  73002. if (sourceBone) {
  73003. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  73004. }
  73005. else {
  73006. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  73007. ret = false;
  73008. }
  73009. }
  73010. // do not call createAnimationRange(), since it also is done to bones, which was already done
  73011. var range = source.getAnimationRange(name);
  73012. if (range) {
  73013. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  73014. }
  73015. return ret;
  73016. };
  73017. Skeleton.prototype.returnToRest = function () {
  73018. for (var index = 0; index < this.bones.length; index++) {
  73019. this.bones[index].returnToRest();
  73020. }
  73021. };
  73022. Skeleton.prototype._getHighestAnimationFrame = function () {
  73023. var ret = 0;
  73024. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  73025. if (this.bones[i].animations[0]) {
  73026. var highest = this.bones[i].animations[0].getHighestFrame();
  73027. if (ret < highest) {
  73028. ret = highest;
  73029. }
  73030. }
  73031. }
  73032. return ret;
  73033. };
  73034. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  73035. var range = this.getAnimationRange(name);
  73036. if (!range) {
  73037. return null;
  73038. }
  73039. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  73040. };
  73041. Skeleton.prototype._markAsDirty = function () {
  73042. this._isDirty = true;
  73043. };
  73044. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  73045. this._meshesWithPoseMatrix.push(mesh);
  73046. };
  73047. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  73048. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  73049. if (index > -1) {
  73050. this._meshesWithPoseMatrix.splice(index, 1);
  73051. }
  73052. };
  73053. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  73054. this.onBeforeComputeObservable.notifyObservers(this);
  73055. for (var index = 0; index < this.bones.length; index++) {
  73056. var bone = this.bones[index];
  73057. var parentBone = bone.getParent();
  73058. if (parentBone) {
  73059. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  73060. }
  73061. else {
  73062. if (initialSkinMatrix) {
  73063. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  73064. }
  73065. else {
  73066. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  73067. }
  73068. }
  73069. if (bone._index !== -1) {
  73070. var mappedIndex = bone._index === null ? index : bone._index;
  73071. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  73072. }
  73073. }
  73074. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  73075. };
  73076. Skeleton.prototype.prepare = function () {
  73077. if (!this._isDirty) {
  73078. return;
  73079. }
  73080. if (this.needInitialSkinMatrix) {
  73081. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  73082. var mesh = this._meshesWithPoseMatrix[index];
  73083. var poseMatrix = mesh.getPoseMatrix();
  73084. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  73085. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  73086. }
  73087. if (this._synchronizedWithMesh !== mesh) {
  73088. this._synchronizedWithMesh = mesh;
  73089. // Prepare bones
  73090. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  73091. var bone = this.bones[boneIndex];
  73092. if (!bone.getParent()) {
  73093. var matrix = bone.getBaseMatrix();
  73094. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  73095. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  73096. }
  73097. }
  73098. }
  73099. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  73100. }
  73101. }
  73102. else {
  73103. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  73104. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  73105. }
  73106. this._computeTransformMatrices(this._transformMatrices, null);
  73107. }
  73108. this._isDirty = false;
  73109. this._scene._activeBones.addCount(this.bones.length, false);
  73110. };
  73111. Skeleton.prototype.getAnimatables = function () {
  73112. if (!this._animatables || this._animatables.length !== this.bones.length) {
  73113. this._animatables = [];
  73114. for (var index = 0; index < this.bones.length; index++) {
  73115. this._animatables.push(this.bones[index]);
  73116. }
  73117. }
  73118. return this._animatables;
  73119. };
  73120. Skeleton.prototype.clone = function (name, id) {
  73121. var result = new Skeleton(name, id || name, this._scene);
  73122. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  73123. for (var index = 0; index < this.bones.length; index++) {
  73124. var source = this.bones[index];
  73125. var parentBone = null;
  73126. var parent_1 = source.getParent();
  73127. if (parent_1) {
  73128. var parentIndex = this.bones.indexOf(parent_1);
  73129. parentBone = result.bones[parentIndex];
  73130. }
  73131. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  73132. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  73133. }
  73134. if (this._ranges) {
  73135. result._ranges = {};
  73136. for (var rangeName in this._ranges) {
  73137. var range = this._ranges[rangeName];
  73138. if (range) {
  73139. result._ranges[rangeName] = range.clone();
  73140. }
  73141. }
  73142. }
  73143. this._isDirty = true;
  73144. return result;
  73145. };
  73146. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  73147. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  73148. this.bones.forEach(function (bone) {
  73149. bone.animations.forEach(function (animation) {
  73150. animation.enableBlending = true;
  73151. animation.blendingSpeed = blendingSpeed;
  73152. });
  73153. });
  73154. };
  73155. Skeleton.prototype.dispose = function () {
  73156. this._meshesWithPoseMatrix = [];
  73157. // Animations
  73158. this.getScene().stopAnimation(this);
  73159. // Remove from scene
  73160. this.getScene().removeSkeleton(this);
  73161. };
  73162. Skeleton.prototype.serialize = function () {
  73163. var serializationObject = {};
  73164. serializationObject.name = this.name;
  73165. serializationObject.id = this.id;
  73166. serializationObject.dimensionsAtRest = this.dimensionsAtRest;
  73167. serializationObject.bones = [];
  73168. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  73169. for (var index = 0; index < this.bones.length; index++) {
  73170. var bone = this.bones[index];
  73171. var parent_2 = bone.getParent();
  73172. var serializedBone = {
  73173. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  73174. name: bone.name,
  73175. matrix: bone.getBaseMatrix().toArray(),
  73176. rest: bone.getRestPose().toArray()
  73177. };
  73178. serializationObject.bones.push(serializedBone);
  73179. if (bone.length) {
  73180. serializedBone.length = bone.length;
  73181. }
  73182. if (bone.animations && bone.animations.length > 0) {
  73183. serializedBone.animation = bone.animations[0].serialize();
  73184. }
  73185. serializationObject.ranges = [];
  73186. for (var name in this._ranges) {
  73187. var source = this._ranges[name];
  73188. if (!source) {
  73189. continue;
  73190. }
  73191. var range = {};
  73192. range.name = name;
  73193. range.from = source.from;
  73194. range.to = source.to;
  73195. serializationObject.ranges.push(range);
  73196. }
  73197. }
  73198. return serializationObject;
  73199. };
  73200. Skeleton.Parse = function (parsedSkeleton, scene) {
  73201. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  73202. if (parsedSkeleton.dimensionsAtRest) {
  73203. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  73204. }
  73205. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  73206. var index;
  73207. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  73208. var parsedBone = parsedSkeleton.bones[index];
  73209. var parentBone = null;
  73210. if (parsedBone.parentBoneIndex > -1) {
  73211. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  73212. }
  73213. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  73214. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  73215. if (parsedBone.length) {
  73216. bone.length = parsedBone.length;
  73217. }
  73218. if (parsedBone.animation) {
  73219. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  73220. }
  73221. }
  73222. // placed after bones, so createAnimationRange can cascade down
  73223. if (parsedSkeleton.ranges) {
  73224. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  73225. var data = parsedSkeleton.ranges[index];
  73226. skeleton.createAnimationRange(data.name, data.from, data.to);
  73227. }
  73228. }
  73229. return skeleton;
  73230. };
  73231. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  73232. if (forceUpdate === void 0) { forceUpdate = false; }
  73233. var renderId = this._scene.getRenderId();
  73234. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  73235. this.bones[0].computeAbsoluteTransforms();
  73236. this._lastAbsoluteTransformsUpdateId = renderId;
  73237. }
  73238. };
  73239. Skeleton.prototype.getPoseMatrix = function () {
  73240. var poseMatrix = null;
  73241. if (this._meshesWithPoseMatrix.length > 0) {
  73242. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  73243. }
  73244. return poseMatrix;
  73245. };
  73246. Skeleton.prototype.sortBones = function () {
  73247. var bones = new Array();
  73248. var visited = new Array(this.bones.length);
  73249. for (var index = 0; index < this.bones.length; index++) {
  73250. this._sortBones(index, bones, visited);
  73251. }
  73252. this.bones = bones;
  73253. };
  73254. Skeleton.prototype._sortBones = function (index, bones, visited) {
  73255. if (visited[index]) {
  73256. return;
  73257. }
  73258. visited[index] = true;
  73259. var bone = this.bones[index];
  73260. if (bone._index === undefined) {
  73261. bone._index = index;
  73262. }
  73263. var parentBone = bone.getParent();
  73264. if (parentBone) {
  73265. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  73266. }
  73267. bones.push(bone);
  73268. };
  73269. return Skeleton;
  73270. }());
  73271. BABYLON.Skeleton = Skeleton;
  73272. })(BABYLON || (BABYLON = {}));
  73273. //# sourceMappingURL=babylon.skeleton.js.map
  73274. var BABYLON;
  73275. (function (BABYLON) {
  73276. var SphericalPolynomial = /** @class */ (function () {
  73277. function SphericalPolynomial() {
  73278. this.x = BABYLON.Vector3.Zero();
  73279. this.y = BABYLON.Vector3.Zero();
  73280. this.z = BABYLON.Vector3.Zero();
  73281. this.xx = BABYLON.Vector3.Zero();
  73282. this.yy = BABYLON.Vector3.Zero();
  73283. this.zz = BABYLON.Vector3.Zero();
  73284. this.xy = BABYLON.Vector3.Zero();
  73285. this.yz = BABYLON.Vector3.Zero();
  73286. this.zx = BABYLON.Vector3.Zero();
  73287. }
  73288. SphericalPolynomial.prototype.addAmbient = function (color) {
  73289. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  73290. this.xx = this.xx.add(colorVector);
  73291. this.yy = this.yy.add(colorVector);
  73292. this.zz = this.zz.add(colorVector);
  73293. };
  73294. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  73295. var result = new SphericalPolynomial();
  73296. result.x = harmonics.L11.scale(1.02333);
  73297. result.y = harmonics.L1_1.scale(1.02333);
  73298. result.z = harmonics.L10.scale(1.02333);
  73299. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  73300. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  73301. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  73302. result.yz = harmonics.L2_1.scale(0.858086);
  73303. result.zx = harmonics.L21.scale(0.858086);
  73304. result.xy = harmonics.L2_2.scale(0.858086);
  73305. result.scale(1.0 / Math.PI);
  73306. return result;
  73307. };
  73308. SphericalPolynomial.prototype.scale = function (scale) {
  73309. this.x = this.x.scale(scale);
  73310. this.y = this.y.scale(scale);
  73311. this.z = this.z.scale(scale);
  73312. this.xx = this.xx.scale(scale);
  73313. this.yy = this.yy.scale(scale);
  73314. this.zz = this.zz.scale(scale);
  73315. this.yz = this.yz.scale(scale);
  73316. this.zx = this.zx.scale(scale);
  73317. this.xy = this.xy.scale(scale);
  73318. };
  73319. return SphericalPolynomial;
  73320. }());
  73321. BABYLON.SphericalPolynomial = SphericalPolynomial;
  73322. var SphericalHarmonics = /** @class */ (function () {
  73323. function SphericalHarmonics() {
  73324. this.L00 = BABYLON.Vector3.Zero();
  73325. this.L1_1 = BABYLON.Vector3.Zero();
  73326. this.L10 = BABYLON.Vector3.Zero();
  73327. this.L11 = BABYLON.Vector3.Zero();
  73328. this.L2_2 = BABYLON.Vector3.Zero();
  73329. this.L2_1 = BABYLON.Vector3.Zero();
  73330. this.L20 = BABYLON.Vector3.Zero();
  73331. this.L21 = BABYLON.Vector3.Zero();
  73332. this.L22 = BABYLON.Vector3.Zero();
  73333. }
  73334. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  73335. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  73336. var c = colorVector.scale(deltaSolidAngle);
  73337. this.L00 = this.L00.add(c.scale(0.282095));
  73338. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  73339. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  73340. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  73341. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  73342. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  73343. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  73344. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  73345. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  73346. };
  73347. SphericalHarmonics.prototype.scale = function (scale) {
  73348. this.L00 = this.L00.scale(scale);
  73349. this.L1_1 = this.L1_1.scale(scale);
  73350. this.L10 = this.L10.scale(scale);
  73351. this.L11 = this.L11.scale(scale);
  73352. this.L2_2 = this.L2_2.scale(scale);
  73353. this.L2_1 = this.L2_1.scale(scale);
  73354. this.L20 = this.L20.scale(scale);
  73355. this.L21 = this.L21.scale(scale);
  73356. this.L22 = this.L22.scale(scale);
  73357. };
  73358. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  73359. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  73360. //
  73361. // E_lm = A_l * L_lm
  73362. //
  73363. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  73364. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  73365. // the scaling factors are given in equation 9.
  73366. // Constant (Band 0)
  73367. this.L00 = this.L00.scale(3.141593);
  73368. // Linear (Band 1)
  73369. this.L1_1 = this.L1_1.scale(2.094395);
  73370. this.L10 = this.L10.scale(2.094395);
  73371. this.L11 = this.L11.scale(2.094395);
  73372. // Quadratic (Band 2)
  73373. this.L2_2 = this.L2_2.scale(0.785398);
  73374. this.L2_1 = this.L2_1.scale(0.785398);
  73375. this.L20 = this.L20.scale(0.785398);
  73376. this.L21 = this.L21.scale(0.785398);
  73377. this.L22 = this.L22.scale(0.785398);
  73378. };
  73379. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  73380. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  73381. // L = (1/pi) * E * rho
  73382. //
  73383. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  73384. this.scale(1.0 / Math.PI);
  73385. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  73386. // (The pixel shader must apply albedo after texture fetches, etc).
  73387. };
  73388. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  73389. var result = new SphericalHarmonics();
  73390. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  73391. result.L1_1 = polynomial.y.scale(0.977204);
  73392. result.L10 = polynomial.z.scale(0.977204);
  73393. result.L11 = polynomial.x.scale(0.977204);
  73394. result.L2_2 = polynomial.xy.scale(1.16538);
  73395. result.L2_1 = polynomial.yz.scale(1.16538);
  73396. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  73397. result.L21 = polynomial.zx.scale(1.16538);
  73398. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  73399. result.scale(Math.PI);
  73400. return result;
  73401. };
  73402. return SphericalHarmonics;
  73403. }());
  73404. BABYLON.SphericalHarmonics = SphericalHarmonics;
  73405. })(BABYLON || (BABYLON = {}));
  73406. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  73407. var BABYLON;
  73408. (function (BABYLON) {
  73409. var FileFaceOrientation = /** @class */ (function () {
  73410. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  73411. this.name = name;
  73412. this.worldAxisForNormal = worldAxisForNormal;
  73413. this.worldAxisForFileX = worldAxisForFileX;
  73414. this.worldAxisForFileY = worldAxisForFileY;
  73415. }
  73416. return FileFaceOrientation;
  73417. }());
  73418. ;
  73419. /**
  73420. * Helper class dealing with the extraction of spherical polynomial dataArray
  73421. * from a cube map.
  73422. */
  73423. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  73424. function CubeMapToSphericalPolynomialTools() {
  73425. }
  73426. /**
  73427. * Converts a texture to the according Spherical Polynomial data.
  73428. * This extracts the first 3 orders only as they are the only one used in the lighting.
  73429. *
  73430. * @param texture The texture to extract the information from.
  73431. * @return The Spherical Polynomial data.
  73432. */
  73433. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  73434. if (!texture.isCube) {
  73435. // Only supports cube Textures currently.
  73436. return null;
  73437. }
  73438. var size = texture.getSize().width;
  73439. var right = texture.readPixels(0);
  73440. var left = texture.readPixels(1);
  73441. var up;
  73442. var down;
  73443. if (texture.isRenderTarget) {
  73444. up = texture.readPixels(3);
  73445. down = texture.readPixels(2);
  73446. }
  73447. else {
  73448. up = texture.readPixels(2);
  73449. down = texture.readPixels(3);
  73450. }
  73451. var front = texture.readPixels(4);
  73452. var back = texture.readPixels(5);
  73453. var gammaSpace = texture.gammaSpace;
  73454. // Always read as RGBA.
  73455. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  73456. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  73457. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  73458. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  73459. }
  73460. var cubeInfo = {
  73461. size: size,
  73462. right: right,
  73463. left: left,
  73464. up: up,
  73465. down: down,
  73466. front: front,
  73467. back: back,
  73468. format: format,
  73469. type: type,
  73470. gammaSpace: gammaSpace,
  73471. };
  73472. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  73473. };
  73474. /**
  73475. * Converts a cubemap to the according Spherical Polynomial data.
  73476. * This extracts the first 3 orders only as they are the only one used in the lighting.
  73477. *
  73478. * @param cubeInfo The Cube map to extract the information from.
  73479. * @return The Spherical Polynomial data.
  73480. */
  73481. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  73482. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  73483. var totalSolidAngle = 0.0;
  73484. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  73485. var du = 2.0 / cubeInfo.size;
  73486. var dv = du;
  73487. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  73488. var minUV = du * 0.5 - 1.0;
  73489. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  73490. var fileFace = this.FileFaces[faceIndex];
  73491. var dataArray = cubeInfo[fileFace.name];
  73492. var v = minUV;
  73493. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  73494. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  73495. // Because SP is still linear, so summation is fine in that basis.
  73496. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  73497. for (var y = 0; y < cubeInfo.size; y++) {
  73498. var u = minUV;
  73499. for (var x = 0; x < cubeInfo.size; x++) {
  73500. // World direction (not normalised)
  73501. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  73502. worldDirection.normalize();
  73503. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  73504. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  73505. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  73506. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  73507. // Handle Integer types.
  73508. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  73509. r /= 255;
  73510. g /= 255;
  73511. b /= 255;
  73512. }
  73513. // Handle Gamma space textures.
  73514. if (cubeInfo.gammaSpace) {
  73515. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  73516. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  73517. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  73518. }
  73519. var color = new BABYLON.Color3(r, g, b);
  73520. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  73521. totalSolidAngle += deltaSolidAngle;
  73522. u += du;
  73523. }
  73524. v += dv;
  73525. }
  73526. }
  73527. // Solid angle for entire sphere is 4*pi
  73528. var sphereSolidAngle = 4.0 * Math.PI;
  73529. // Adjust the solid angle to allow for how many faces we processed.
  73530. var facesProcessed = 6.0;
  73531. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  73532. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  73533. // This is needed because the numerical integration over the cube uses a
  73534. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  73535. // and also to compensate for accumulative error due to float precision in the summation.
  73536. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  73537. sphericalHarmonics.scale(correctionFactor);
  73538. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  73539. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  73540. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  73541. };
  73542. CubeMapToSphericalPolynomialTools.FileFaces = [
  73543. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  73544. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  73545. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  73546. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  73547. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  73548. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  73549. ];
  73550. return CubeMapToSphericalPolynomialTools;
  73551. }());
  73552. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  73553. })(BABYLON || (BABYLON = {}));
  73554. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  73555. var BABYLON;
  73556. (function (BABYLON) {
  73557. /**
  73558. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  73559. */
  73560. var PanoramaToCubeMapTools = /** @class */ (function () {
  73561. function PanoramaToCubeMapTools() {
  73562. }
  73563. /**
  73564. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  73565. *
  73566. * @param float32Array The source data.
  73567. * @param inputWidth The width of the input panorama.
  73568. * @param inputhHeight The height of the input panorama.
  73569. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  73570. * @return The cubemap data
  73571. */
  73572. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  73573. if (!float32Array) {
  73574. throw "ConvertPanoramaToCubemap: input cannot be null";
  73575. }
  73576. if (float32Array.length != inputWidth * inputHeight * 3) {
  73577. throw "ConvertPanoramaToCubemap: input size is wrong";
  73578. }
  73579. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  73580. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  73581. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  73582. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  73583. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  73584. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  73585. return {
  73586. front: textureFront,
  73587. back: textureBack,
  73588. left: textureLeft,
  73589. right: textureRight,
  73590. up: textureUp,
  73591. down: textureDown,
  73592. size: size,
  73593. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  73594. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  73595. gammaSpace: false,
  73596. };
  73597. };
  73598. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  73599. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  73600. var textureArray = new Float32Array(buffer);
  73601. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  73602. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  73603. var dy = 1 / texSize;
  73604. var fy = 0;
  73605. for (var y = 0; y < texSize; y++) {
  73606. var xv1 = faceData[0];
  73607. var xv2 = faceData[2];
  73608. for (var x = 0; x < texSize; x++) {
  73609. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  73610. v.normalize();
  73611. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  73612. // 3 channels per pixels
  73613. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  73614. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  73615. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  73616. xv1 = xv1.add(rotDX1);
  73617. xv2 = xv2.add(rotDX2);
  73618. }
  73619. fy += dy;
  73620. }
  73621. return textureArray;
  73622. };
  73623. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  73624. var theta = Math.atan2(vDir.z, vDir.x);
  73625. var phi = Math.acos(vDir.y);
  73626. while (theta < -Math.PI)
  73627. theta += 2 * Math.PI;
  73628. while (theta > Math.PI)
  73629. theta -= 2 * Math.PI;
  73630. var dx = theta / Math.PI;
  73631. var dy = phi / Math.PI;
  73632. // recenter.
  73633. dx = dx * 0.5 + 0.5;
  73634. var px = Math.round(dx * inputWidth);
  73635. if (px < 0)
  73636. px = 0;
  73637. else if (px >= inputWidth)
  73638. px = inputWidth - 1;
  73639. var py = Math.round(dy * inputHeight);
  73640. if (py < 0)
  73641. py = 0;
  73642. else if (py >= inputHeight)
  73643. py = inputHeight - 1;
  73644. var inputY = (inputHeight - py - 1);
  73645. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  73646. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  73647. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  73648. return {
  73649. r: r,
  73650. g: g,
  73651. b: b
  73652. };
  73653. };
  73654. PanoramaToCubeMapTools.FACE_FRONT = [
  73655. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  73656. new BABYLON.Vector3(1.0, -1.0, -1.0),
  73657. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  73658. new BABYLON.Vector3(1.0, 1.0, -1.0)
  73659. ];
  73660. PanoramaToCubeMapTools.FACE_BACK = [
  73661. new BABYLON.Vector3(1.0, -1.0, 1.0),
  73662. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  73663. new BABYLON.Vector3(1.0, 1.0, 1.0),
  73664. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  73665. ];
  73666. PanoramaToCubeMapTools.FACE_RIGHT = [
  73667. new BABYLON.Vector3(1.0, -1.0, -1.0),
  73668. new BABYLON.Vector3(1.0, -1.0, 1.0),
  73669. new BABYLON.Vector3(1.0, 1.0, -1.0),
  73670. new BABYLON.Vector3(1.0, 1.0, 1.0)
  73671. ];
  73672. PanoramaToCubeMapTools.FACE_LEFT = [
  73673. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  73674. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  73675. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  73676. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  73677. ];
  73678. PanoramaToCubeMapTools.FACE_DOWN = [
  73679. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  73680. new BABYLON.Vector3(1.0, 1.0, -1.0),
  73681. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  73682. new BABYLON.Vector3(1.0, 1.0, 1.0)
  73683. ];
  73684. PanoramaToCubeMapTools.FACE_UP = [
  73685. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  73686. new BABYLON.Vector3(1.0, -1.0, 1.0),
  73687. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  73688. new BABYLON.Vector3(1.0, -1.0, -1.0)
  73689. ];
  73690. return PanoramaToCubeMapTools;
  73691. }());
  73692. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  73693. })(BABYLON || (BABYLON = {}));
  73694. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  73695. var BABYLON;
  73696. (function (BABYLON) {
  73697. ;
  73698. /**
  73699. * This groups tools to convert HDR texture to native colors array.
  73700. */
  73701. var HDRTools = /** @class */ (function () {
  73702. function HDRTools() {
  73703. }
  73704. HDRTools.Ldexp = function (mantissa, exponent) {
  73705. if (exponent > 1023) {
  73706. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  73707. }
  73708. if (exponent < -1074) {
  73709. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  73710. }
  73711. return mantissa * Math.pow(2, exponent);
  73712. };
  73713. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  73714. if (exponent > 0) {
  73715. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  73716. float32array[index + 0] = red * exponent;
  73717. float32array[index + 1] = green * exponent;
  73718. float32array[index + 2] = blue * exponent;
  73719. }
  73720. else {
  73721. float32array[index + 0] = 0;
  73722. float32array[index + 1] = 0;
  73723. float32array[index + 2] = 0;
  73724. }
  73725. };
  73726. HDRTools.readStringLine = function (uint8array, startIndex) {
  73727. var line = "";
  73728. var character = "";
  73729. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  73730. character = String.fromCharCode(uint8array[i]);
  73731. if (character == "\n") {
  73732. break;
  73733. }
  73734. line += character;
  73735. }
  73736. return line;
  73737. };
  73738. /**
  73739. * Reads header information from an RGBE texture stored in a native array.
  73740. * More information on this format are available here:
  73741. * https://en.wikipedia.org/wiki/RGBE_image_format
  73742. *
  73743. * @param uint8array The binary file stored in native array.
  73744. * @return The header information.
  73745. */
  73746. HDRTools.RGBE_ReadHeader = function (uint8array) {
  73747. var height = 0;
  73748. var width = 0;
  73749. var line = this.readStringLine(uint8array, 0);
  73750. if (line[0] != '#' || line[1] != '?') {
  73751. throw "Bad HDR Format.";
  73752. }
  73753. var endOfHeader = false;
  73754. var findFormat = false;
  73755. var lineIndex = 0;
  73756. do {
  73757. lineIndex += (line.length + 1);
  73758. line = this.readStringLine(uint8array, lineIndex);
  73759. if (line == "FORMAT=32-bit_rle_rgbe") {
  73760. findFormat = true;
  73761. }
  73762. else if (line.length == 0) {
  73763. endOfHeader = true;
  73764. }
  73765. } while (!endOfHeader);
  73766. if (!findFormat) {
  73767. throw "HDR Bad header format, unsupported FORMAT";
  73768. }
  73769. lineIndex += (line.length + 1);
  73770. line = this.readStringLine(uint8array, lineIndex);
  73771. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  73772. var match = sizeRegexp.exec(line);
  73773. // TODO. Support +Y and -X if needed.
  73774. if (!match || match.length < 3) {
  73775. throw "HDR Bad header format, no size";
  73776. }
  73777. width = parseInt(match[2]);
  73778. height = parseInt(match[1]);
  73779. if (width < 8 || width > 0x7fff) {
  73780. throw "HDR Bad header format, unsupported size";
  73781. }
  73782. lineIndex += (line.length + 1);
  73783. return {
  73784. height: height,
  73785. width: width,
  73786. dataPosition: lineIndex
  73787. };
  73788. };
  73789. /**
  73790. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  73791. * This RGBE texture needs to store the information as a panorama.
  73792. *
  73793. * More information on this format are available here:
  73794. * https://en.wikipedia.org/wiki/RGBE_image_format
  73795. *
  73796. * @param buffer The binary file stored in an array buffer.
  73797. * @param size The expected size of the extracted cubemap.
  73798. * @return The Cube Map information.
  73799. */
  73800. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  73801. var uint8array = new Uint8Array(buffer);
  73802. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  73803. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  73804. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  73805. return cubeMapData;
  73806. };
  73807. /**
  73808. * Returns the pixels data extracted from an RGBE texture.
  73809. * This pixels will be stored left to right up to down in the R G B order in one array.
  73810. *
  73811. * More information on this format are available here:
  73812. * https://en.wikipedia.org/wiki/RGBE_image_format
  73813. *
  73814. * @param uint8array The binary file stored in an array buffer.
  73815. * @param hdrInfo The header information of the file.
  73816. * @return The pixels data in RGB right to left up to down order.
  73817. */
  73818. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  73819. // Keep for multi format supports.
  73820. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  73821. };
  73822. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  73823. var num_scanlines = hdrInfo.height;
  73824. var scanline_width = hdrInfo.width;
  73825. var a, b, c, d, count;
  73826. var dataIndex = hdrInfo.dataPosition;
  73827. var index = 0, endIndex = 0, i = 0;
  73828. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  73829. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  73830. // 3 channels of 4 bytes per pixel in float.
  73831. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  73832. var resultArray = new Float32Array(resultBuffer);
  73833. // read in each successive scanline
  73834. while (num_scanlines > 0) {
  73835. a = uint8array[dataIndex++];
  73836. b = uint8array[dataIndex++];
  73837. c = uint8array[dataIndex++];
  73838. d = uint8array[dataIndex++];
  73839. if (a != 2 || b != 2 || (c & 0x80)) {
  73840. // this file is not run length encoded
  73841. throw "HDR Bad header format, not RLE";
  73842. }
  73843. if (((c << 8) | d) != scanline_width) {
  73844. throw "HDR Bad header format, wrong scan line width";
  73845. }
  73846. index = 0;
  73847. // read each of the four channels for the scanline into the buffer
  73848. for (i = 0; i < 4; i++) {
  73849. endIndex = (i + 1) * scanline_width;
  73850. while (index < endIndex) {
  73851. a = uint8array[dataIndex++];
  73852. b = uint8array[dataIndex++];
  73853. if (a > 128) {
  73854. // a run of the same value
  73855. count = a - 128;
  73856. if ((count == 0) || (count > endIndex - index)) {
  73857. throw "HDR Bad Format, bad scanline data (run)";
  73858. }
  73859. while (count-- > 0) {
  73860. scanLineArray[index++] = b;
  73861. }
  73862. }
  73863. else {
  73864. // a non-run
  73865. count = a;
  73866. if ((count == 0) || (count > endIndex - index)) {
  73867. throw "HDR Bad Format, bad scanline data (non-run)";
  73868. }
  73869. scanLineArray[index++] = b;
  73870. if (--count > 0) {
  73871. for (var j = 0; j < count; j++) {
  73872. scanLineArray[index++] = uint8array[dataIndex++];
  73873. }
  73874. }
  73875. }
  73876. }
  73877. }
  73878. // now convert data from buffer into floats
  73879. for (i = 0; i < scanline_width; i++) {
  73880. a = scanLineArray[i];
  73881. b = scanLineArray[i + scanline_width];
  73882. c = scanLineArray[i + 2 * scanline_width];
  73883. d = scanLineArray[i + 3 * scanline_width];
  73884. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  73885. }
  73886. num_scanlines--;
  73887. }
  73888. return resultArray;
  73889. };
  73890. return HDRTools;
  73891. }());
  73892. BABYLON.HDRTools = HDRTools;
  73893. })(BABYLON || (BABYLON = {}));
  73894. //# sourceMappingURL=babylon.hdr.js.map
  73895. var BABYLON;
  73896. (function (BABYLON) {
  73897. /**
  73898. * This represents a texture coming from an HDR input.
  73899. *
  73900. * The only supported format is currently panorama picture stored in RGBE format.
  73901. * Example of such files can be found on HDRLib: http://hdrlib.com/
  73902. */
  73903. var HDRCubeTexture = /** @class */ (function (_super) {
  73904. __extends(HDRCubeTexture, _super);
  73905. /**
  73906. * Instantiates an HDRTexture from the following parameters.
  73907. *
  73908. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  73909. * @param scene The scene the texture will be used in
  73910. * @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.
  73911. * @param noMipmap Forces to not generate the mipmap if true
  73912. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  73913. * @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)
  73914. * @param usePMREMGenerator Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  73915. */
  73916. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator, onLoad, onError) {
  73917. if (noMipmap === void 0) { noMipmap = false; }
  73918. if (generateHarmonics === void 0) { generateHarmonics = true; }
  73919. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  73920. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  73921. if (onLoad === void 0) { onLoad = null; }
  73922. if (onError === void 0) { onError = null; }
  73923. var _this = _super.call(this, scene) || this;
  73924. _this._useInGammaSpace = false;
  73925. _this._generateHarmonics = true;
  73926. _this._isBABYLONPreprocessed = false;
  73927. _this._onLoad = null;
  73928. _this._onError = null;
  73929. /**
  73930. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  73931. */
  73932. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  73933. /**
  73934. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  73935. * This is usefull at run time to apply the good shader.
  73936. */
  73937. _this.isPMREM = false;
  73938. _this._isBlocking = true;
  73939. /**
  73940. * Gets or sets the center of the bounding box associated with the cube texture
  73941. * It must define where the camera used to render the texture was set
  73942. */
  73943. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  73944. if (!url) {
  73945. return _this;
  73946. }
  73947. _this.name = url;
  73948. _this.url = url;
  73949. _this.hasAlpha = false;
  73950. _this.isCube = true;
  73951. _this._textureMatrix = BABYLON.Matrix.Identity();
  73952. _this._onLoad = onLoad;
  73953. _this._onError = onError;
  73954. _this.gammaSpace = false;
  73955. var caps = scene.getEngine().getCaps();
  73956. if (size) {
  73957. _this._isBABYLONPreprocessed = false;
  73958. _this._noMipmap = noMipmap;
  73959. _this._size = size;
  73960. _this._useInGammaSpace = useInGammaSpace;
  73961. _this._usePMREMGenerator = usePMREMGenerator &&
  73962. caps.textureLOD &&
  73963. caps.textureFloat &&
  73964. !_this._useInGammaSpace;
  73965. }
  73966. else {
  73967. _this._isBABYLONPreprocessed = true;
  73968. _this._noMipmap = false;
  73969. _this._useInGammaSpace = false;
  73970. _this._usePMREMGenerator = caps.textureLOD && caps.textureFloat &&
  73971. !_this._useInGammaSpace;
  73972. }
  73973. _this.isPMREM = _this._usePMREMGenerator;
  73974. _this._texture = _this._getFromCache(url, _this._noMipmap);
  73975. if (!_this._texture) {
  73976. if (!scene.useDelayedTextureLoading) {
  73977. _this.loadTexture();
  73978. }
  73979. else {
  73980. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  73981. }
  73982. }
  73983. return _this;
  73984. }
  73985. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  73986. /**
  73987. * Gets wether or not the texture is blocking during loading.
  73988. */
  73989. get: function () {
  73990. return this._isBlocking;
  73991. },
  73992. /**
  73993. * Sets wether or not the texture is blocking during loading.
  73994. */
  73995. set: function (value) {
  73996. this._isBlocking = value;
  73997. },
  73998. enumerable: true,
  73999. configurable: true
  74000. });
  74001. Object.defineProperty(HDRCubeTexture.prototype, "boundingBoxSize", {
  74002. get: function () {
  74003. return this._boundingBoxSize;
  74004. },
  74005. /**
  74006. * Gets or sets the size of the bounding box associated with the cube texture
  74007. * When defined, the cubemap will switch to local mode
  74008. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  74009. * @example https://www.babylonjs-playground.com/#RNASML
  74010. */
  74011. set: function (value) {
  74012. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  74013. return;
  74014. }
  74015. this._boundingBoxSize = value;
  74016. var scene = this.getScene();
  74017. if (scene) {
  74018. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  74019. }
  74020. },
  74021. enumerable: true,
  74022. configurable: true
  74023. });
  74024. /**
  74025. * Occurs when the file is a preprocessed .babylon.hdr file.
  74026. */
  74027. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  74028. var _this = this;
  74029. var mipLevels = 0;
  74030. var floatArrayView = null;
  74031. var scene = this.getScene();
  74032. var mipmapGenerator = (!this._useInGammaSpace && scene && scene.getEngine().getCaps().textureFloat) ? function (data) {
  74033. var mips = new Array();
  74034. if (!floatArrayView) {
  74035. return mips;
  74036. }
  74037. var startIndex = 30;
  74038. for (var level = 0; level < mipLevels; level++) {
  74039. mips.push([]);
  74040. // Fill each pixel of the mip level.
  74041. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  74042. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  74043. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  74044. mips[level].push(faceData);
  74045. startIndex += faceSize;
  74046. }
  74047. }
  74048. return mips;
  74049. } : null;
  74050. var callback = function (buffer) {
  74051. var scene = _this.getScene();
  74052. if (!scene) {
  74053. return null;
  74054. }
  74055. // Create Native Array Views
  74056. var intArrayView = new Int32Array(buffer);
  74057. floatArrayView = new Float32Array(buffer);
  74058. // Fill header.
  74059. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  74060. _this._size = intArrayView[1]; // CubeMap max mip face size.
  74061. // Update Texture Information.
  74062. if (!_this._texture) {
  74063. return null;
  74064. }
  74065. _this._texture.updateSize(_this._size, _this._size);
  74066. // Fill polynomial information.
  74067. var sphericalPolynomial = new BABYLON.SphericalPolynomial();
  74068. sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  74069. sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  74070. sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  74071. sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  74072. sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  74073. sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  74074. sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  74075. sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  74076. sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  74077. _this.sphericalPolynomial = sphericalPolynomial;
  74078. // Fill pixel data.
  74079. mipLevels = intArrayView[29]; // Number of mip levels.
  74080. var startIndex = 30;
  74081. var data = [];
  74082. var faceSize = Math.pow(_this._size, 2) * 3;
  74083. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  74084. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  74085. startIndex += faceSize;
  74086. }
  74087. var results = [];
  74088. var byteArray = null;
  74089. // Push each faces.
  74090. for (var k = 0; k < 6; k++) {
  74091. var dataFace = null;
  74092. // To be deprecated.
  74093. if (version === 1) {
  74094. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y...
  74095. dataFace = data[j];
  74096. }
  74097. // If special cases.
  74098. if (!mipmapGenerator && dataFace) {
  74099. if (!scene.getEngine().getCaps().textureFloat) {
  74100. // 3 channels of 1 bytes per pixel in bytes.
  74101. var byteBuffer = new ArrayBuffer(faceSize);
  74102. byteArray = new Uint8Array(byteBuffer);
  74103. }
  74104. for (var i = 0; i < _this._size * _this._size; i++) {
  74105. // Put in gamma space if requested.
  74106. if (_this._useInGammaSpace) {
  74107. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  74108. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  74109. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  74110. }
  74111. // Convert to int texture for fallback.
  74112. if (byteArray) {
  74113. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  74114. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  74115. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  74116. // May use luminance instead if the result is not accurate.
  74117. var max = Math.max(Math.max(r, g), b);
  74118. if (max > 255) {
  74119. var scale = 255 / max;
  74120. r *= scale;
  74121. g *= scale;
  74122. b *= scale;
  74123. }
  74124. byteArray[(i * 3) + 0] = r;
  74125. byteArray[(i * 3) + 1] = g;
  74126. byteArray[(i * 3) + 2] = b;
  74127. }
  74128. }
  74129. }
  74130. // Fill the array accordingly.
  74131. if (byteArray) {
  74132. results.push(byteArray);
  74133. }
  74134. else {
  74135. results.push(dataFace);
  74136. }
  74137. }
  74138. return results;
  74139. };
  74140. if (scene) {
  74141. 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);
  74142. }
  74143. };
  74144. /**
  74145. * Occurs when the file is raw .hdr file.
  74146. */
  74147. HDRCubeTexture.prototype.loadHDRTexture = function () {
  74148. var _this = this;
  74149. var callback = function (buffer) {
  74150. var scene = _this.getScene();
  74151. if (!scene) {
  74152. return null;
  74153. }
  74154. // Extract the raw linear data.
  74155. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  74156. // Generate harmonics if needed.
  74157. if (_this._generateHarmonics) {
  74158. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  74159. _this.sphericalPolynomial = sphericalPolynomial;
  74160. }
  74161. var results = [];
  74162. var byteArray = null;
  74163. // Push each faces.
  74164. for (var j = 0; j < 6; j++) {
  74165. // Create uintarray fallback.
  74166. if (!scene.getEngine().getCaps().textureFloat) {
  74167. // 3 channels of 1 bytes per pixel in bytes.
  74168. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  74169. byteArray = new Uint8Array(byteBuffer);
  74170. }
  74171. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  74172. // If special cases.
  74173. if (_this._useInGammaSpace || byteArray) {
  74174. for (var i = 0; i < _this._size * _this._size; i++) {
  74175. // Put in gamma space if requested.
  74176. if (_this._useInGammaSpace) {
  74177. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  74178. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  74179. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  74180. }
  74181. // Convert to int texture for fallback.
  74182. if (byteArray) {
  74183. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  74184. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  74185. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  74186. // May use luminance instead if the result is not accurate.
  74187. var max = Math.max(Math.max(r, g), b);
  74188. if (max > 255) {
  74189. var scale = 255 / max;
  74190. r *= scale;
  74191. g *= scale;
  74192. b *= scale;
  74193. }
  74194. byteArray[(i * 3) + 0] = r;
  74195. byteArray[(i * 3) + 1] = g;
  74196. byteArray[(i * 3) + 2] = b;
  74197. }
  74198. }
  74199. }
  74200. if (byteArray) {
  74201. results.push(byteArray);
  74202. }
  74203. else {
  74204. results.push(dataFace);
  74205. }
  74206. }
  74207. return results;
  74208. };
  74209. var mipmapGenerator = null;
  74210. // TODO. Implement In code PMREM Generator following the LYS toolset generation.
  74211. // if (!this._noMipmap &&
  74212. // this._usePMREMGenerator) {
  74213. // mipmapGenerator = (data: ArrayBufferView[]) => {
  74214. // // Custom setup of the generator matching with the PBR shader values.
  74215. // var generator = new BABYLON.PMREMGenerator(data,
  74216. // this._size,
  74217. // this._size,
  74218. // 0,
  74219. // 3,
  74220. // this.getScene().getEngine().getCaps().textureFloat,
  74221. // 2048,
  74222. // 0.25,
  74223. // false,
  74224. // true);
  74225. // return generator.filterCubeMap();
  74226. // };
  74227. // }
  74228. var scene = this.getScene();
  74229. if (scene) {
  74230. 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);
  74231. }
  74232. };
  74233. /**
  74234. * Starts the loading process of the texture.
  74235. */
  74236. HDRCubeTexture.prototype.loadTexture = function () {
  74237. if (this._isBABYLONPreprocessed) {
  74238. this.loadBabylonTexture();
  74239. }
  74240. else {
  74241. this.loadHDRTexture();
  74242. }
  74243. };
  74244. HDRCubeTexture.prototype.clone = function () {
  74245. var scene = this.getScene();
  74246. if (!scene) {
  74247. return this;
  74248. }
  74249. var size = (this._isBABYLONPreprocessed ? null : this._size);
  74250. var newTexture = new HDRCubeTexture(this.url, scene, size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  74251. // Base texture
  74252. newTexture.level = this.level;
  74253. newTexture.wrapU = this.wrapU;
  74254. newTexture.wrapV = this.wrapV;
  74255. newTexture.coordinatesIndex = this.coordinatesIndex;
  74256. newTexture.coordinatesMode = this.coordinatesMode;
  74257. return newTexture;
  74258. };
  74259. // Methods
  74260. HDRCubeTexture.prototype.delayLoad = function () {
  74261. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  74262. return;
  74263. }
  74264. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  74265. this._texture = this._getFromCache(this.url, this._noMipmap);
  74266. if (!this._texture) {
  74267. this.loadTexture();
  74268. }
  74269. };
  74270. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  74271. return this._textureMatrix;
  74272. };
  74273. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  74274. this._textureMatrix = value;
  74275. };
  74276. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  74277. var texture = null;
  74278. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  74279. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  74280. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  74281. texture.name = parsedTexture.name;
  74282. texture.hasAlpha = parsedTexture.hasAlpha;
  74283. texture.level = parsedTexture.level;
  74284. texture.coordinatesMode = parsedTexture.coordinatesMode;
  74285. texture.isBlocking = parsedTexture.isBlocking;
  74286. }
  74287. if (texture) {
  74288. if (parsedTexture.boundingBoxPosition) {
  74289. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  74290. }
  74291. if (parsedTexture.boundingBoxSize) {
  74292. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  74293. }
  74294. }
  74295. return texture;
  74296. };
  74297. HDRCubeTexture.prototype.serialize = function () {
  74298. if (!this.name) {
  74299. return null;
  74300. }
  74301. var serializationObject = {};
  74302. serializationObject.name = this.name;
  74303. serializationObject.hasAlpha = this.hasAlpha;
  74304. serializationObject.isCube = true;
  74305. serializationObject.level = this.level;
  74306. serializationObject.size = this._size;
  74307. serializationObject.coordinatesMode = this.coordinatesMode;
  74308. serializationObject.useInGammaSpace = this._useInGammaSpace;
  74309. serializationObject.generateHarmonics = this._generateHarmonics;
  74310. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  74311. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  74312. serializationObject.customType = "BABYLON.HDRCubeTexture";
  74313. serializationObject.noMipmap = this._noMipmap;
  74314. serializationObject.isBlocking = this._isBlocking;
  74315. return serializationObject;
  74316. };
  74317. /**
  74318. * Saves as a file the data contained in the texture in a binary format.
  74319. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  74320. * as the spherical used in the lighting.
  74321. * @param url The HDR file url.
  74322. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  74323. * @param onError Method called if any error happens during download.
  74324. * @return The packed binary data.
  74325. */
  74326. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  74327. if (onError === void 0) { onError = null; }
  74328. var callback = function (buffer) {
  74329. var data = new Blob([buffer], { type: 'application/octet-stream' });
  74330. // Returns a URL you can use as a href.
  74331. var objUrl = window.URL.createObjectURL(data);
  74332. // Simulates a link to it and click to dowload.
  74333. var a = document.createElement("a");
  74334. document.body.appendChild(a);
  74335. a.style.display = "none";
  74336. a.href = objUrl;
  74337. a.download = "envmap.babylon.hdr";
  74338. a.click();
  74339. };
  74340. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  74341. };
  74342. /**
  74343. * Serializes the data contained in the texture in a binary format.
  74344. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  74345. * as the spherical used in the lighting.
  74346. * @param url The HDR file url.
  74347. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  74348. * @param onError Method called if any error happens during download.
  74349. * @return The packed binary data.
  74350. */
  74351. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  74352. if (onError === void 0) { onError = null; }
  74353. // Needs the url tho create the texture.
  74354. if (!url) {
  74355. return;
  74356. }
  74357. // Check Power of two size.
  74358. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  74359. return;
  74360. }
  74361. // Coming Back in 3.x.
  74362. BABYLON.Tools.Error("Generation of Babylon HDR is coming back in 3.2.");
  74363. };
  74364. HDRCubeTexture._facesMapping = [
  74365. "right",
  74366. "left",
  74367. "up",
  74368. "down",
  74369. "front",
  74370. "back"
  74371. ];
  74372. return HDRCubeTexture;
  74373. }(BABYLON.BaseTexture));
  74374. BABYLON.HDRCubeTexture = HDRCubeTexture;
  74375. })(BABYLON || (BABYLON = {}));
  74376. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  74377. // All the credit goes to this project and the guy who's behind it https://github.com/mapbox/earcut
  74378. // Huge respect for a such great lib.
  74379. // Earcut license:
  74380. // Copyright (c) 2016, Mapbox
  74381. //
  74382. // Permission to use, copy, modify, and/or distribute this software for any purpose
  74383. // with or without fee is hereby granted, provided that the above copyright notice
  74384. // and this permission notice appear in all copies.
  74385. //
  74386. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  74387. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  74388. // FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  74389. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  74390. // OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  74391. // TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
  74392. // THIS SOFTWARE.
  74393. var Earcut;
  74394. (function (Earcut) {
  74395. /**
  74396. * The fastest and smallest JavaScript polygon triangulation library for your WebGL apps
  74397. * @param data is a flat array of vertice coordinates like [x0, y0, x1, y1, x2, y2, ...].
  74398. * @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).
  74399. * @param dim is the number of coordinates per vertice in the input array (2 by default).
  74400. */
  74401. function earcut(data, holeIndices, dim) {
  74402. dim = dim || 2;
  74403. var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = new Array();
  74404. if (!outerNode)
  74405. return triangles;
  74406. var minX = 0, minY = 0, maxX, maxY, x, y, size = 0;
  74407. if (hasHoles)
  74408. outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  74409. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  74410. if (data.length > 80 * dim) {
  74411. minX = maxX = data[0];
  74412. minY = maxY = data[1];
  74413. for (var i = dim; i < outerLen; i += dim) {
  74414. x = data[i];
  74415. y = data[i + 1];
  74416. if (x < minX)
  74417. minX = x;
  74418. if (y < minY)
  74419. minY = y;
  74420. if (x > maxX)
  74421. maxX = x;
  74422. if (y > maxY)
  74423. maxY = y;
  74424. }
  74425. // minX, minY and size are later used to transform coords into integers for z-order calculation
  74426. size = Math.max(maxX - minX, maxY - minY);
  74427. }
  74428. earcutLinked(outerNode, triangles, dim, minX, minY, size, 0);
  74429. return triangles;
  74430. }
  74431. Earcut.earcut = earcut;
  74432. var Node = /** @class */ (function () {
  74433. function Node(i, x, y) {
  74434. this.i = i;
  74435. this.x = x;
  74436. this.y = y;
  74437. this.prev = null;
  74438. this.next = null;
  74439. this.z = null;
  74440. this.prevZ = null;
  74441. this.nextZ = null;
  74442. this.steiner = false;
  74443. }
  74444. return Node;
  74445. }());
  74446. // create a circular doubly linked list from polygon points in the specified winding order
  74447. function linkedList(data, start, end, dim, clockwise) {
  74448. var i, last = null;
  74449. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  74450. for (i = start; i < end; i += dim)
  74451. last = insertNode(i, data[i], data[i + 1], last);
  74452. }
  74453. else {
  74454. for (i = end - dim; i >= start; i -= dim)
  74455. last = insertNode(i, data[i], data[i + 1], last);
  74456. }
  74457. if (last && equals(last, last.next)) {
  74458. removeNode(last);
  74459. last = last.next;
  74460. }
  74461. return last;
  74462. }
  74463. // eliminate colinear or duplicate points
  74464. function filterPoints(start, end) {
  74465. if (!start)
  74466. return start;
  74467. if (!end)
  74468. end = start;
  74469. var p = start, again;
  74470. do {
  74471. again = false;
  74472. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  74473. removeNode(p);
  74474. p = end = p.prev;
  74475. if (p === p.next)
  74476. return undefined;
  74477. again = true;
  74478. }
  74479. else {
  74480. p = p.next;
  74481. }
  74482. } while (again || p !== end);
  74483. return end;
  74484. }
  74485. // main ear slicing loop which triangulates a polygon (given as a linked list)
  74486. function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
  74487. if (!ear)
  74488. return;
  74489. // interlink polygon nodes in z-order
  74490. if (!pass && size)
  74491. indexCurve(ear, minX, minY, size);
  74492. var stop = ear, prev, next;
  74493. // iterate through ears, slicing them one by one
  74494. while (ear.prev !== ear.next) {
  74495. prev = ear.prev;
  74496. next = ear.next;
  74497. if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
  74498. // cut off the triangle
  74499. triangles.push(prev.i / dim);
  74500. triangles.push(ear.i / dim);
  74501. triangles.push(next.i / dim);
  74502. removeNode(ear);
  74503. // skipping the next vertice leads to less sliver triangles
  74504. ear = next.next;
  74505. stop = next.next;
  74506. continue;
  74507. }
  74508. ear = next;
  74509. // if we looped through the whole remaining polygon and can't find any more ears
  74510. if (ear === stop) {
  74511. // try filtering points and slicing again
  74512. if (!pass) {
  74513. earcutLinked(filterPoints(ear, undefined), triangles, dim, minX, minY, size, 1);
  74514. // if this didn't work, try curing all small self-intersections locally
  74515. }
  74516. else if (pass === 1) {
  74517. ear = cureLocalIntersections(ear, triangles, dim);
  74518. earcutLinked(ear, triangles, dim, minX, minY, size, 2);
  74519. // as a last resort, try splitting the remaining polygon into two
  74520. }
  74521. else if (pass === 2) {
  74522. splitEarcut(ear, triangles, dim, minX, minY, size);
  74523. }
  74524. break;
  74525. }
  74526. }
  74527. }
  74528. // check whether a polygon node forms a valid ear with adjacent nodes
  74529. function isEar(ear) {
  74530. var a = ear.prev, b = ear, c = ear.next;
  74531. if (area(a, b, c) >= 0)
  74532. return false; // reflex, can't be an ear
  74533. // now make sure we don't have other points inside the potential ear
  74534. var p = ear.next.next;
  74535. while (p !== ear.prev) {
  74536. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  74537. area(p.prev, p, p.next) >= 0)
  74538. return false;
  74539. p = p.next;
  74540. }
  74541. return true;
  74542. }
  74543. function isEarHashed(ear, minX, minY, size) {
  74544. var a = ear.prev, b = ear, c = ear.next;
  74545. if (area(a, b, c) >= 0)
  74546. return false; // reflex, can't be an ear
  74547. // triangle bbox; min & max are calculated like this for speed
  74548. 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);
  74549. // z-order range for the current triangle bbox;
  74550. var minZ = zOrder(minTX, minTY, minX, minY, size), maxZ = zOrder(maxTX, maxTY, minX, minY, size);
  74551. // first look for points inside the triangle in increasing z-order
  74552. var p = ear.nextZ;
  74553. while (p && p.z <= maxZ) {
  74554. if (p !== ear.prev &&
  74555. p !== ear.next &&
  74556. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  74557. area(p.prev, p, p.next) >= 0)
  74558. return false;
  74559. p = p.nextZ;
  74560. }
  74561. // then look for points in decreasing z-order
  74562. p = ear.prevZ;
  74563. while (p && p.z >= minZ) {
  74564. if (p !== ear.prev &&
  74565. p !== ear.next &&
  74566. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  74567. area(p.prev, p, p.next) >= 0)
  74568. return false;
  74569. p = p.prevZ;
  74570. }
  74571. return true;
  74572. }
  74573. // go through all polygon nodes and cure small local self-intersections
  74574. function cureLocalIntersections(start, triangles, dim) {
  74575. var p = start;
  74576. do {
  74577. var a = p.prev, b = p.next.next;
  74578. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  74579. triangles.push(a.i / dim);
  74580. triangles.push(p.i / dim);
  74581. triangles.push(b.i / dim);
  74582. // remove two nodes involved
  74583. removeNode(p);
  74584. removeNode(p.next);
  74585. p = start = b;
  74586. }
  74587. p = p.next;
  74588. } while (p !== start);
  74589. return p;
  74590. }
  74591. // try splitting polygon into two and triangulate them independently
  74592. function splitEarcut(start, triangles, dim, minX, minY, size) {
  74593. // look for a valid diagonal that divides the polygon into two
  74594. var a = start;
  74595. do {
  74596. var b = a.next.next;
  74597. while (b !== a.prev) {
  74598. if (a.i !== b.i && isValidDiagonal(a, b)) {
  74599. // split the polygon in two by the diagonal
  74600. var c = splitPolygon(a, b);
  74601. // filter colinear points around the cuts
  74602. a = filterPoints(a, a.next);
  74603. c = filterPoints(c, c.next);
  74604. // run earcut on each half
  74605. earcutLinked(a, triangles, dim, minX, minY, size, undefined);
  74606. earcutLinked(c, triangles, dim, minX, minY, size, undefined);
  74607. return;
  74608. }
  74609. b = b.next;
  74610. }
  74611. a = a.next;
  74612. } while (a !== start);
  74613. }
  74614. // link every hole into the outer loop, producing a single-ring polygon without holes
  74615. function eliminateHoles(data, holeIndices, outerNode, dim) {
  74616. var queue = [], i, len, start, end, list;
  74617. for (i = 0, len = holeIndices.length; i < len; i++) {
  74618. start = holeIndices[i] * dim;
  74619. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  74620. list = linkedList(data, start, end, dim, false);
  74621. if (list === list.next)
  74622. list.steiner = true;
  74623. queue.push(getLeftmost(list));
  74624. }
  74625. queue.sort(compareX);
  74626. // process holes from left to right
  74627. for (i = 0; i < queue.length; i++) {
  74628. eliminateHole(queue[i], outerNode);
  74629. outerNode = filterPoints(outerNode, outerNode.next);
  74630. }
  74631. return outerNode;
  74632. }
  74633. function compareX(a, b) {
  74634. return a.x - b.x;
  74635. }
  74636. // find a bridge between vertices that connects hole with an outer ring and and link it
  74637. function eliminateHole(hole, outerNode) {
  74638. outerNode = findHoleBridge(hole, outerNode);
  74639. if (outerNode) {
  74640. var b = splitPolygon(outerNode, hole);
  74641. filterPoints(b, b.next);
  74642. }
  74643. }
  74644. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  74645. function findHoleBridge(hole, outerNode) {
  74646. var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m;
  74647. // find a segment intersected by a ray from the hole's leftmost point to the left;
  74648. // segment's endpoint with lesser x will be potential connection point
  74649. do {
  74650. if (hy <= p.y && hy >= p.next.y) {
  74651. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  74652. if (x <= hx && x > qx) {
  74653. qx = x;
  74654. if (x === hx) {
  74655. if (hy === p.y)
  74656. return p;
  74657. if (hy === p.next.y)
  74658. return p.next;
  74659. }
  74660. m = p.x < p.next.x ? p : p.next;
  74661. }
  74662. }
  74663. p = p.next;
  74664. } while (p !== outerNode);
  74665. if (!m)
  74666. return null;
  74667. if (hx === qx)
  74668. return m.prev; // hole touches outer segment; pick lower endpoint
  74669. // look for points inside the triangle of hole point, segment intersection and endpoint;
  74670. // if there are no points found, we have a valid connection;
  74671. // otherwise choose the point of the minimum angle with the ray as connection point
  74672. var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan;
  74673. p = m.next;
  74674. while (p !== stop) {
  74675. if (hx >= p.x &&
  74676. p.x >= mx &&
  74677. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  74678. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  74679. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
  74680. m = p;
  74681. tanMin = tan;
  74682. }
  74683. }
  74684. p = p.next;
  74685. }
  74686. return m;
  74687. }
  74688. // interlink polygon nodes in z-order
  74689. function indexCurve(start, minX, minY, size) {
  74690. var p = start;
  74691. do {
  74692. if (p.z === null)
  74693. p.z = zOrder(p.x, p.y, minX, minY, size);
  74694. p.prevZ = p.prev;
  74695. p.nextZ = p.next;
  74696. p = p.next;
  74697. } while (p !== start);
  74698. p.prevZ.nextZ = null;
  74699. p.prevZ = null;
  74700. sortLinked(p);
  74701. }
  74702. // Simon Tatham's linked list merge sort algorithm
  74703. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  74704. function sortLinked(list) {
  74705. var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
  74706. do {
  74707. p = list;
  74708. list = null;
  74709. tail = null;
  74710. numMerges = 0;
  74711. while (p) {
  74712. numMerges++;
  74713. q = p;
  74714. pSize = 0;
  74715. for (i = 0; i < inSize; i++) {
  74716. pSize++;
  74717. q = q.nextZ;
  74718. if (!q)
  74719. break;
  74720. }
  74721. qSize = inSize;
  74722. while (pSize > 0 || (qSize > 0 && q)) {
  74723. if (pSize === 0) {
  74724. e = q;
  74725. q = q.nextZ;
  74726. qSize--;
  74727. }
  74728. else if (qSize === 0 || !q) {
  74729. e = p;
  74730. p = p.nextZ;
  74731. pSize--;
  74732. }
  74733. else if (p.z <= q.z) {
  74734. e = p;
  74735. p = p.nextZ;
  74736. pSize--;
  74737. }
  74738. else {
  74739. e = q;
  74740. q = q.nextZ;
  74741. qSize--;
  74742. }
  74743. if (tail)
  74744. tail.nextZ = e;
  74745. else
  74746. list = e;
  74747. e.prevZ = tail;
  74748. tail = e;
  74749. }
  74750. p = q;
  74751. }
  74752. tail.nextZ = null;
  74753. inSize *= 2;
  74754. } while (numMerges > 1);
  74755. return list;
  74756. }
  74757. // z-order of a point given coords and size of the data bounding box
  74758. function zOrder(x, y, minX, minY, size) {
  74759. // coords are transformed into non-negative 15-bit integer range
  74760. x = 32767 * (x - minX) / size;
  74761. y = 32767 * (y - minY) / size;
  74762. x = (x | (x << 8)) & 0x00FF00FF;
  74763. x = (x | (x << 4)) & 0x0F0F0F0F;
  74764. x = (x | (x << 2)) & 0x33333333;
  74765. x = (x | (x << 1)) & 0x55555555;
  74766. y = (y | (y << 8)) & 0x00FF00FF;
  74767. y = (y | (y << 4)) & 0x0F0F0F0F;
  74768. y = (y | (y << 2)) & 0x33333333;
  74769. y = (y | (y << 1)) & 0x55555555;
  74770. return x | (y << 1);
  74771. }
  74772. // find the leftmost node of a polygon ring
  74773. function getLeftmost(start) {
  74774. var p = start, leftmost = start;
  74775. do {
  74776. if (p.x < leftmost.x)
  74777. leftmost = p;
  74778. p = p.next;
  74779. } while (p !== start);
  74780. return leftmost;
  74781. }
  74782. // check if a point lies within a convex triangle
  74783. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  74784. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  74785. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  74786. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  74787. }
  74788. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  74789. function isValidDiagonal(a, b) {
  74790. return a.next.i !== b.i &&
  74791. a.prev.i !== b.i &&
  74792. !intersectsPolygon(a, b) &&
  74793. locallyInside(a, b) &&
  74794. locallyInside(b, a) &&
  74795. middleInside(a, b);
  74796. }
  74797. // signed area of a triangle
  74798. function area(p, q, r) {
  74799. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  74800. }
  74801. // check if two points are equal
  74802. function equals(p1, p2) {
  74803. return p1.x === p2.x && p1.y === p2.y;
  74804. }
  74805. // check if two segments intersect
  74806. function intersects(p1, q1, p2, q2) {
  74807. if ((equals(p1, q1) && equals(p2, q2)) ||
  74808. (equals(p1, q2) && equals(p2, q1)))
  74809. return true;
  74810. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
  74811. area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  74812. }
  74813. // check if a polygon diagonal intersects any polygon segments
  74814. function intersectsPolygon(a, b) {
  74815. var p = a;
  74816. do {
  74817. if (p.i !== a.i &&
  74818. p.next.i !== a.i &&
  74819. p.i !== b.i &&
  74820. p.next.i !== b.i &&
  74821. intersects(p, p.next, a, b))
  74822. return true;
  74823. p = p.next;
  74824. } while (p !== a);
  74825. return false;
  74826. }
  74827. // check if a polygon diagonal is locally inside the polygon
  74828. function locallyInside(a, b) {
  74829. return area(a.prev, a, a.next) < 0
  74830. ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0
  74831. : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  74832. }
  74833. // check if the middle point of a polygon diagonal is inside the polygon
  74834. function middleInside(a, b) {
  74835. var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2;
  74836. do {
  74837. if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  74838. inside = !inside;
  74839. p = p.next;
  74840. } while (p !== a);
  74841. return inside;
  74842. }
  74843. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  74844. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  74845. function splitPolygon(a, b) {
  74846. 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;
  74847. a.next = b;
  74848. b.prev = a;
  74849. a2.next = an;
  74850. an.prev = a2;
  74851. b2.next = a2;
  74852. a2.prev = b2;
  74853. bp.next = b2;
  74854. b2.prev = bp;
  74855. return b2;
  74856. }
  74857. // create a node and optionally link it with previous one (in a circular doubly linked list)
  74858. function insertNode(i, x, y, last) {
  74859. var p = new Node(i, x, y);
  74860. if (!last) {
  74861. p.prev = p;
  74862. p.next = p;
  74863. }
  74864. else {
  74865. p.next = last.next;
  74866. p.prev = last;
  74867. last.next.prev = p;
  74868. last.next = p;
  74869. }
  74870. return p;
  74871. }
  74872. function removeNode(p) {
  74873. p.next.prev = p.prev;
  74874. p.prev.next = p.next;
  74875. if (p.prevZ)
  74876. p.prevZ.nextZ = p.nextZ;
  74877. if (p.nextZ)
  74878. p.nextZ.prevZ = p.prevZ;
  74879. }
  74880. /**
  74881. * return a percentage difference between the polygon area and its triangulation area;
  74882. * used to verify correctness of triangulation
  74883. */
  74884. function deviation(data, holeIndices, dim, triangles) {
  74885. var hasHoles = holeIndices && holeIndices.length;
  74886. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  74887. var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
  74888. if (hasHoles) {
  74889. for (var i = 0, len = holeIndices.length; i < len; i++) {
  74890. var start = holeIndices[i] * dim;
  74891. var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  74892. polygonArea -= Math.abs(signedArea(data, start, end, dim));
  74893. }
  74894. }
  74895. var trianglesArea = 0;
  74896. for (i = 0; i < triangles.length; i += 3) {
  74897. var a = triangles[i] * dim;
  74898. var b = triangles[i + 1] * dim;
  74899. var c = triangles[i + 2] * dim;
  74900. trianglesArea += Math.abs((data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
  74901. (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
  74902. }
  74903. return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea);
  74904. }
  74905. Earcut.deviation = deviation;
  74906. ;
  74907. function signedArea(data, start, end, dim) {
  74908. var sum = 0;
  74909. for (var i = start, j = end - dim; i < end; i += dim) {
  74910. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  74911. j = i;
  74912. }
  74913. return sum;
  74914. }
  74915. /**
  74916. * turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  74917. */
  74918. function flatten(data) {
  74919. var dim = data[0][0].length, result = { vertices: new Array(), holes: new Array(), dimensions: dim }, holeIndex = 0;
  74920. for (var i = 0; i < data.length; i++) {
  74921. for (var j = 0; j < data[i].length; j++) {
  74922. for (var d = 0; d < dim; d++)
  74923. result.vertices.push(data[i][j][d]);
  74924. }
  74925. if (i > 0) {
  74926. holeIndex += data[i - 1].length;
  74927. result.holes.push(holeIndex);
  74928. }
  74929. }
  74930. return result;
  74931. }
  74932. Earcut.flatten = flatten;
  74933. ;
  74934. })(Earcut || (Earcut = {}));
  74935. //# sourceMappingURL=babylon.earcut.js.map
  74936. var BABYLON;
  74937. (function (BABYLON) {
  74938. var IndexedVector2 = /** @class */ (function (_super) {
  74939. __extends(IndexedVector2, _super);
  74940. function IndexedVector2(original, index) {
  74941. var _this = _super.call(this, original.x, original.y) || this;
  74942. _this.index = index;
  74943. return _this;
  74944. }
  74945. return IndexedVector2;
  74946. }(BABYLON.Vector2));
  74947. var PolygonPoints = /** @class */ (function () {
  74948. function PolygonPoints() {
  74949. this.elements = new Array();
  74950. }
  74951. PolygonPoints.prototype.add = function (originalPoints) {
  74952. var _this = this;
  74953. var result = new Array();
  74954. originalPoints.forEach(function (point) {
  74955. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  74956. var newPoint = new IndexedVector2(point, _this.elements.length);
  74957. result.push(newPoint);
  74958. _this.elements.push(newPoint);
  74959. }
  74960. });
  74961. return result;
  74962. };
  74963. PolygonPoints.prototype.computeBounds = function () {
  74964. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  74965. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  74966. this.elements.forEach(function (point) {
  74967. // x
  74968. if (point.x < lmin.x) {
  74969. lmin.x = point.x;
  74970. }
  74971. else if (point.x > lmax.x) {
  74972. lmax.x = point.x;
  74973. }
  74974. // y
  74975. if (point.y < lmin.y) {
  74976. lmin.y = point.y;
  74977. }
  74978. else if (point.y > lmax.y) {
  74979. lmax.y = point.y;
  74980. }
  74981. });
  74982. return {
  74983. min: lmin,
  74984. max: lmax,
  74985. width: lmax.x - lmin.x,
  74986. height: lmax.y - lmin.y
  74987. };
  74988. };
  74989. return PolygonPoints;
  74990. }());
  74991. var Polygon = /** @class */ (function () {
  74992. function Polygon() {
  74993. }
  74994. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  74995. return [
  74996. new BABYLON.Vector2(xmin, ymin),
  74997. new BABYLON.Vector2(xmax, ymin),
  74998. new BABYLON.Vector2(xmax, ymax),
  74999. new BABYLON.Vector2(xmin, ymax)
  75000. ];
  75001. };
  75002. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  75003. if (cx === void 0) { cx = 0; }
  75004. if (cy === void 0) { cy = 0; }
  75005. if (numberOfSides === void 0) { numberOfSides = 32; }
  75006. var result = new Array();
  75007. var angle = 0;
  75008. var increment = (Math.PI * 2) / numberOfSides;
  75009. for (var i = 0; i < numberOfSides; i++) {
  75010. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  75011. angle -= increment;
  75012. }
  75013. return result;
  75014. };
  75015. Polygon.Parse = function (input) {
  75016. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  75017. var i, result = [];
  75018. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  75019. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  75020. }
  75021. return result;
  75022. };
  75023. Polygon.StartingAt = function (x, y) {
  75024. return BABYLON.Path2.StartingAt(x, y);
  75025. };
  75026. return Polygon;
  75027. }());
  75028. BABYLON.Polygon = Polygon;
  75029. var PolygonMeshBuilder = /** @class */ (function () {
  75030. function PolygonMeshBuilder(name, contours, scene) {
  75031. this._points = new PolygonPoints();
  75032. this._outlinepoints = new PolygonPoints();
  75033. this._holes = new Array();
  75034. this._epoints = new Array();
  75035. this._eholes = new Array();
  75036. this._name = name;
  75037. this._scene = scene;
  75038. var points;
  75039. if (contours instanceof BABYLON.Path2) {
  75040. points = contours.getPoints();
  75041. }
  75042. else {
  75043. points = contours;
  75044. }
  75045. this._addToepoint(points);
  75046. this._points.add(points);
  75047. this._outlinepoints.add(points);
  75048. }
  75049. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  75050. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  75051. var p = points_1[_i];
  75052. this._epoints.push(p.x, p.y);
  75053. }
  75054. };
  75055. PolygonMeshBuilder.prototype.addHole = function (hole) {
  75056. this._points.add(hole);
  75057. var holepoints = new PolygonPoints();
  75058. holepoints.add(hole);
  75059. this._holes.push(holepoints);
  75060. this._eholes.push(this._epoints.length / 2);
  75061. this._addToepoint(hole);
  75062. return this;
  75063. };
  75064. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  75065. var _this = this;
  75066. if (updatable === void 0) { updatable = false; }
  75067. if (depth === void 0) { depth = 0; }
  75068. var result = new BABYLON.Mesh(this._name, this._scene);
  75069. var normals = new Array();
  75070. var positions = new Array();
  75071. var uvs = new Array();
  75072. var bounds = this._points.computeBounds();
  75073. this._points.elements.forEach(function (p) {
  75074. normals.push(0, 1.0, 0);
  75075. positions.push(p.x, 0, p.y);
  75076. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  75077. });
  75078. var indices = new Array();
  75079. var res = Earcut.earcut(this._epoints, this._eholes, 2);
  75080. for (var i = 0; i < res.length; i++) {
  75081. indices.push(res[i]);
  75082. }
  75083. if (depth > 0) {
  75084. var positionscount = (positions.length / 3); //get the current pointcount
  75085. this._points.elements.forEach(function (p) {
  75086. normals.push(0, -1.0, 0);
  75087. positions.push(p.x, -depth, p.y);
  75088. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  75089. });
  75090. var totalCount = indices.length;
  75091. for (var i = 0; i < totalCount; i += 3) {
  75092. var i0 = indices[i + 0];
  75093. var i1 = indices[i + 1];
  75094. var i2 = indices[i + 2];
  75095. indices.push(i2 + positionscount);
  75096. indices.push(i1 + positionscount);
  75097. indices.push(i0 + positionscount);
  75098. }
  75099. //Add the sides
  75100. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  75101. this._holes.forEach(function (hole) {
  75102. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  75103. });
  75104. }
  75105. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  75106. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  75107. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  75108. result.setIndices(indices);
  75109. return result;
  75110. };
  75111. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  75112. var StartIndex = positions.length / 3;
  75113. var ulength = 0;
  75114. for (var i = 0; i < points.elements.length; i++) {
  75115. var p = points.elements[i];
  75116. var p1;
  75117. if ((i + 1) > points.elements.length - 1) {
  75118. p1 = points.elements[0];
  75119. }
  75120. else {
  75121. p1 = points.elements[i + 1];
  75122. }
  75123. positions.push(p.x, 0, p.y);
  75124. positions.push(p.x, -depth, p.y);
  75125. positions.push(p1.x, 0, p1.y);
  75126. positions.push(p1.x, -depth, p1.y);
  75127. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  75128. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  75129. var v3 = v2.subtract(v1);
  75130. var v4 = new BABYLON.Vector3(0, 1, 0);
  75131. var vn = BABYLON.Vector3.Cross(v3, v4);
  75132. vn = vn.normalize();
  75133. uvs.push(ulength / bounds.width, 0);
  75134. uvs.push(ulength / bounds.width, 1);
  75135. ulength += v3.length();
  75136. uvs.push((ulength / bounds.width), 0);
  75137. uvs.push((ulength / bounds.width), 1);
  75138. if (!flip) {
  75139. normals.push(-vn.x, -vn.y, -vn.z);
  75140. normals.push(-vn.x, -vn.y, -vn.z);
  75141. normals.push(-vn.x, -vn.y, -vn.z);
  75142. normals.push(-vn.x, -vn.y, -vn.z);
  75143. indices.push(StartIndex);
  75144. indices.push(StartIndex + 1);
  75145. indices.push(StartIndex + 2);
  75146. indices.push(StartIndex + 1);
  75147. indices.push(StartIndex + 3);
  75148. indices.push(StartIndex + 2);
  75149. }
  75150. else {
  75151. normals.push(vn.x, vn.y, vn.z);
  75152. normals.push(vn.x, vn.y, vn.z);
  75153. normals.push(vn.x, vn.y, vn.z);
  75154. normals.push(vn.x, vn.y, vn.z);
  75155. indices.push(StartIndex);
  75156. indices.push(StartIndex + 2);
  75157. indices.push(StartIndex + 1);
  75158. indices.push(StartIndex + 1);
  75159. indices.push(StartIndex + 2);
  75160. indices.push(StartIndex + 3);
  75161. }
  75162. StartIndex += 4;
  75163. }
  75164. ;
  75165. };
  75166. return PolygonMeshBuilder;
  75167. }());
  75168. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  75169. })(BABYLON || (BABYLON = {}));
  75170. //# sourceMappingURL=babylon.polygonMesh.js.map
  75171. var BABYLON;
  75172. (function (BABYLON) {
  75173. // Unique ID when we import meshes from Babylon to CSG
  75174. var currentCSGMeshId = 0;
  75175. // # class Vertex
  75176. // Represents a vertex of a polygon. Use your own vertex class instead of this
  75177. // one to provide additional features like texture coordinates and vertex
  75178. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  75179. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  75180. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  75181. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  75182. // is not used anywhere else.
  75183. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  75184. var Vertex = /** @class */ (function () {
  75185. function Vertex(pos, normal, uv) {
  75186. this.pos = pos;
  75187. this.normal = normal;
  75188. this.uv = uv;
  75189. }
  75190. Vertex.prototype.clone = function () {
  75191. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  75192. };
  75193. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  75194. // orientation of a polygon is flipped.
  75195. Vertex.prototype.flip = function () {
  75196. this.normal = this.normal.scale(-1);
  75197. };
  75198. // Create a new vertex between this vertex and `other` by linearly
  75199. // interpolating all properties using a parameter of `t`. Subclasses should
  75200. // override this to interpolate additional properties.
  75201. Vertex.prototype.interpolate = function (other, t) {
  75202. 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));
  75203. };
  75204. return Vertex;
  75205. }());
  75206. // # class Plane
  75207. // Represents a plane in 3D space.
  75208. var Plane = /** @class */ (function () {
  75209. function Plane(normal, w) {
  75210. this.normal = normal;
  75211. this.w = w;
  75212. }
  75213. Plane.FromPoints = function (a, b, c) {
  75214. var v0 = c.subtract(a);
  75215. var v1 = b.subtract(a);
  75216. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  75217. return null;
  75218. }
  75219. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  75220. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  75221. };
  75222. Plane.prototype.clone = function () {
  75223. return new Plane(this.normal.clone(), this.w);
  75224. };
  75225. Plane.prototype.flip = function () {
  75226. this.normal.scaleInPlace(-1);
  75227. this.w = -this.w;
  75228. };
  75229. // Split `polygon` by this plane if needed, then put the polygon or polygon
  75230. // fragments in the appropriate lists. Coplanar polygons go into either
  75231. // `coplanarFront` or `coplanarBack` depending on their orientation with
  75232. // respect to this plane. Polygons in front or in back of this plane go into
  75233. // either `front` or `back`.
  75234. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  75235. var COPLANAR = 0;
  75236. var FRONT = 1;
  75237. var BACK = 2;
  75238. var SPANNING = 3;
  75239. // Classify each point as well as the entire polygon into one of the above
  75240. // four classes.
  75241. var polygonType = 0;
  75242. var types = [];
  75243. var i;
  75244. var t;
  75245. for (i = 0; i < polygon.vertices.length; i++) {
  75246. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  75247. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  75248. polygonType |= type;
  75249. types.push(type);
  75250. }
  75251. // Put the polygon in the correct list, splitting it when necessary.
  75252. switch (polygonType) {
  75253. case COPLANAR:
  75254. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  75255. break;
  75256. case FRONT:
  75257. front.push(polygon);
  75258. break;
  75259. case BACK:
  75260. back.push(polygon);
  75261. break;
  75262. case SPANNING:
  75263. var f = [], b = [];
  75264. for (i = 0; i < polygon.vertices.length; i++) {
  75265. var j = (i + 1) % polygon.vertices.length;
  75266. var ti = types[i], tj = types[j];
  75267. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  75268. if (ti !== BACK)
  75269. f.push(vi);
  75270. if (ti !== FRONT)
  75271. b.push(ti !== BACK ? vi.clone() : vi);
  75272. if ((ti | tj) === SPANNING) {
  75273. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  75274. var v = vi.interpolate(vj, t);
  75275. f.push(v);
  75276. b.push(v.clone());
  75277. }
  75278. }
  75279. var poly;
  75280. if (f.length >= 3) {
  75281. poly = new Polygon(f, polygon.shared);
  75282. if (poly.plane)
  75283. front.push(poly);
  75284. }
  75285. if (b.length >= 3) {
  75286. poly = new Polygon(b, polygon.shared);
  75287. if (poly.plane)
  75288. back.push(poly);
  75289. }
  75290. break;
  75291. }
  75292. };
  75293. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  75294. // point is on the plane.
  75295. Plane.EPSILON = 1e-5;
  75296. return Plane;
  75297. }());
  75298. // # class Polygon
  75299. // Represents a convex polygon. The vertices used to initialize a polygon must
  75300. // be coplanar and form a convex loop.
  75301. //
  75302. // Each convex polygon has a `shared` property, which is shared between all
  75303. // polygons that are clones of each other or were split from the same polygon.
  75304. // This can be used to define per-polygon properties (such as surface color).
  75305. var Polygon = /** @class */ (function () {
  75306. function Polygon(vertices, shared) {
  75307. this.vertices = vertices;
  75308. this.shared = shared;
  75309. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  75310. }
  75311. Polygon.prototype.clone = function () {
  75312. var vertices = this.vertices.map(function (v) { return v.clone(); });
  75313. return new Polygon(vertices, this.shared);
  75314. };
  75315. Polygon.prototype.flip = function () {
  75316. this.vertices.reverse().map(function (v) { v.flip(); });
  75317. this.plane.flip();
  75318. };
  75319. return Polygon;
  75320. }());
  75321. // # class Node
  75322. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  75323. // by picking a polygon to split along. That polygon (and all other coplanar
  75324. // polygons) are added directly to that node and the other polygons are added to
  75325. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  75326. // no distinction between internal and leaf nodes.
  75327. var Node = /** @class */ (function () {
  75328. function Node(polygons) {
  75329. this.plane = null;
  75330. this.front = null;
  75331. this.back = null;
  75332. this.polygons = new Array();
  75333. if (polygons) {
  75334. this.build(polygons);
  75335. }
  75336. }
  75337. Node.prototype.clone = function () {
  75338. var node = new Node();
  75339. node.plane = this.plane && this.plane.clone();
  75340. node.front = this.front && this.front.clone();
  75341. node.back = this.back && this.back.clone();
  75342. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  75343. return node;
  75344. };
  75345. // Convert solid space to empty space and empty space to solid space.
  75346. Node.prototype.invert = function () {
  75347. for (var i = 0; i < this.polygons.length; i++) {
  75348. this.polygons[i].flip();
  75349. }
  75350. if (this.plane) {
  75351. this.plane.flip();
  75352. }
  75353. if (this.front) {
  75354. this.front.invert();
  75355. }
  75356. if (this.back) {
  75357. this.back.invert();
  75358. }
  75359. var temp = this.front;
  75360. this.front = this.back;
  75361. this.back = temp;
  75362. };
  75363. // Recursively remove all polygons in `polygons` that are inside this BSP
  75364. // tree.
  75365. Node.prototype.clipPolygons = function (polygons) {
  75366. if (!this.plane)
  75367. return polygons.slice();
  75368. var front = new Array(), back = new Array();
  75369. for (var i = 0; i < polygons.length; i++) {
  75370. this.plane.splitPolygon(polygons[i], front, back, front, back);
  75371. }
  75372. if (this.front) {
  75373. front = this.front.clipPolygons(front);
  75374. }
  75375. if (this.back) {
  75376. back = this.back.clipPolygons(back);
  75377. }
  75378. else {
  75379. back = [];
  75380. }
  75381. return front.concat(back);
  75382. };
  75383. // Remove all polygons in this BSP tree that are inside the other BSP tree
  75384. // `bsp`.
  75385. Node.prototype.clipTo = function (bsp) {
  75386. this.polygons = bsp.clipPolygons(this.polygons);
  75387. if (this.front)
  75388. this.front.clipTo(bsp);
  75389. if (this.back)
  75390. this.back.clipTo(bsp);
  75391. };
  75392. // Return a list of all polygons in this BSP tree.
  75393. Node.prototype.allPolygons = function () {
  75394. var polygons = this.polygons.slice();
  75395. if (this.front)
  75396. polygons = polygons.concat(this.front.allPolygons());
  75397. if (this.back)
  75398. polygons = polygons.concat(this.back.allPolygons());
  75399. return polygons;
  75400. };
  75401. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  75402. // new polygons are filtered down to the bottom of the tree and become new
  75403. // nodes there. Each set of polygons is partitioned using the first polygon
  75404. // (no heuristic is used to pick a good split).
  75405. Node.prototype.build = function (polygons) {
  75406. if (!polygons.length)
  75407. return;
  75408. if (!this.plane)
  75409. this.plane = polygons[0].plane.clone();
  75410. var front = new Array(), back = new Array();
  75411. for (var i = 0; i < polygons.length; i++) {
  75412. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  75413. }
  75414. if (front.length) {
  75415. if (!this.front)
  75416. this.front = new Node();
  75417. this.front.build(front);
  75418. }
  75419. if (back.length) {
  75420. if (!this.back)
  75421. this.back = new Node();
  75422. this.back.build(back);
  75423. }
  75424. };
  75425. return Node;
  75426. }());
  75427. var CSG = /** @class */ (function () {
  75428. function CSG() {
  75429. this.polygons = new Array();
  75430. }
  75431. // Convert BABYLON.Mesh to BABYLON.CSG
  75432. CSG.FromMesh = function (mesh) {
  75433. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  75434. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  75435. if (mesh instanceof BABYLON.Mesh) {
  75436. mesh.computeWorldMatrix(true);
  75437. matrix = mesh.getWorldMatrix();
  75438. meshPosition = mesh.position.clone();
  75439. meshRotation = mesh.rotation.clone();
  75440. if (mesh.rotationQuaternion) {
  75441. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  75442. }
  75443. meshScaling = mesh.scaling.clone();
  75444. }
  75445. else {
  75446. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  75447. }
  75448. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  75449. var subMeshes = mesh.subMeshes;
  75450. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  75451. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  75452. vertices = [];
  75453. for (var j = 0; j < 3; j++) {
  75454. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  75455. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  75456. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  75457. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  75458. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  75459. vertex = new Vertex(position, normal, uv);
  75460. vertices.push(vertex);
  75461. }
  75462. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  75463. // To handle the case of degenerated triangle
  75464. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  75465. if (polygon.plane)
  75466. polygons.push(polygon);
  75467. }
  75468. }
  75469. var csg = CSG.FromPolygons(polygons);
  75470. csg.matrix = matrix;
  75471. csg.position = meshPosition;
  75472. csg.rotation = meshRotation;
  75473. csg.scaling = meshScaling;
  75474. csg.rotationQuaternion = meshRotationQuaternion;
  75475. currentCSGMeshId++;
  75476. return csg;
  75477. };
  75478. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  75479. CSG.FromPolygons = function (polygons) {
  75480. var csg = new CSG();
  75481. csg.polygons = polygons;
  75482. return csg;
  75483. };
  75484. CSG.prototype.clone = function () {
  75485. var csg = new CSG();
  75486. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  75487. csg.copyTransformAttributes(this);
  75488. return csg;
  75489. };
  75490. CSG.prototype.union = function (csg) {
  75491. var a = new Node(this.clone().polygons);
  75492. var b = new Node(csg.clone().polygons);
  75493. a.clipTo(b);
  75494. b.clipTo(a);
  75495. b.invert();
  75496. b.clipTo(a);
  75497. b.invert();
  75498. a.build(b.allPolygons());
  75499. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  75500. };
  75501. CSG.prototype.unionInPlace = function (csg) {
  75502. var a = new Node(this.polygons);
  75503. var b = new Node(csg.polygons);
  75504. a.clipTo(b);
  75505. b.clipTo(a);
  75506. b.invert();
  75507. b.clipTo(a);
  75508. b.invert();
  75509. a.build(b.allPolygons());
  75510. this.polygons = a.allPolygons();
  75511. };
  75512. CSG.prototype.subtract = function (csg) {
  75513. var a = new Node(this.clone().polygons);
  75514. var b = new Node(csg.clone().polygons);
  75515. a.invert();
  75516. a.clipTo(b);
  75517. b.clipTo(a);
  75518. b.invert();
  75519. b.clipTo(a);
  75520. b.invert();
  75521. a.build(b.allPolygons());
  75522. a.invert();
  75523. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  75524. };
  75525. CSG.prototype.subtractInPlace = function (csg) {
  75526. var a = new Node(this.polygons);
  75527. var b = new Node(csg.polygons);
  75528. a.invert();
  75529. a.clipTo(b);
  75530. b.clipTo(a);
  75531. b.invert();
  75532. b.clipTo(a);
  75533. b.invert();
  75534. a.build(b.allPolygons());
  75535. a.invert();
  75536. this.polygons = a.allPolygons();
  75537. };
  75538. CSG.prototype.intersect = function (csg) {
  75539. var a = new Node(this.clone().polygons);
  75540. var b = new Node(csg.clone().polygons);
  75541. a.invert();
  75542. b.clipTo(a);
  75543. b.invert();
  75544. a.clipTo(b);
  75545. b.clipTo(a);
  75546. a.build(b.allPolygons());
  75547. a.invert();
  75548. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  75549. };
  75550. CSG.prototype.intersectInPlace = function (csg) {
  75551. var a = new Node(this.polygons);
  75552. var b = new Node(csg.polygons);
  75553. a.invert();
  75554. b.clipTo(a);
  75555. b.invert();
  75556. a.clipTo(b);
  75557. b.clipTo(a);
  75558. a.build(b.allPolygons());
  75559. a.invert();
  75560. this.polygons = a.allPolygons();
  75561. };
  75562. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  75563. // not modified.
  75564. CSG.prototype.inverse = function () {
  75565. var csg = this.clone();
  75566. csg.inverseInPlace();
  75567. return csg;
  75568. };
  75569. CSG.prototype.inverseInPlace = function () {
  75570. this.polygons.map(function (p) { p.flip(); });
  75571. };
  75572. // This is used to keep meshes transformations so they can be restored
  75573. // when we build back a Babylon Mesh
  75574. // NB : All CSG operations are performed in world coordinates
  75575. CSG.prototype.copyTransformAttributes = function (csg) {
  75576. this.matrix = csg.matrix;
  75577. this.position = csg.position;
  75578. this.rotation = csg.rotation;
  75579. this.scaling = csg.scaling;
  75580. this.rotationQuaternion = csg.rotationQuaternion;
  75581. return this;
  75582. };
  75583. // Build Raw mesh from CSG
  75584. // Coordinates here are in world space
  75585. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  75586. var matrix = this.matrix.clone();
  75587. matrix.invert();
  75588. 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;
  75589. if (keepSubMeshes) {
  75590. // Sort Polygons, since subMeshes are indices range
  75591. polygons.sort(function (a, b) {
  75592. if (a.shared.meshId === b.shared.meshId) {
  75593. return a.shared.subMeshId - b.shared.subMeshId;
  75594. }
  75595. else {
  75596. return a.shared.meshId - b.shared.meshId;
  75597. }
  75598. });
  75599. }
  75600. for (var i = 0, il = polygons.length; i < il; i++) {
  75601. polygon = polygons[i];
  75602. // Building SubMeshes
  75603. if (!subMesh_dict[polygon.shared.meshId]) {
  75604. subMesh_dict[polygon.shared.meshId] = {};
  75605. }
  75606. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  75607. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  75608. indexStart: +Infinity,
  75609. indexEnd: -Infinity,
  75610. materialIndex: polygon.shared.materialIndex
  75611. };
  75612. }
  75613. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  75614. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  75615. polygonIndices[0] = 0;
  75616. polygonIndices[1] = j - 1;
  75617. polygonIndices[2] = j;
  75618. for (var k = 0; k < 3; k++) {
  75619. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  75620. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  75621. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  75622. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  75623. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  75624. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  75625. // Check if 2 points can be merged
  75626. if (!(typeof vertex_idx !== 'undefined' &&
  75627. normals[vertex_idx * 3] === localNormal.x &&
  75628. normals[vertex_idx * 3 + 1] === localNormal.y &&
  75629. normals[vertex_idx * 3 + 2] === localNormal.z &&
  75630. uvs[vertex_idx * 2] === uv.x &&
  75631. uvs[vertex_idx * 2 + 1] === uv.y)) {
  75632. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  75633. uvs.push(uv.x, uv.y);
  75634. normals.push(normal.x, normal.y, normal.z);
  75635. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  75636. }
  75637. indices.push(vertex_idx);
  75638. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  75639. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  75640. currentIndex++;
  75641. }
  75642. }
  75643. }
  75644. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  75645. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  75646. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  75647. mesh.setIndices(indices, null);
  75648. if (keepSubMeshes) {
  75649. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  75650. var materialIndexOffset = 0, materialMaxIndex;
  75651. mesh.subMeshes = new Array();
  75652. for (var m in subMesh_dict) {
  75653. materialMaxIndex = -1;
  75654. for (var sm in subMesh_dict[m]) {
  75655. subMesh_obj = subMesh_dict[m][sm];
  75656. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  75657. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  75658. }
  75659. materialIndexOffset += ++materialMaxIndex;
  75660. }
  75661. }
  75662. return mesh;
  75663. };
  75664. // Build Mesh from CSG taking material and transforms into account
  75665. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  75666. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  75667. mesh.material = material;
  75668. mesh.position.copyFrom(this.position);
  75669. mesh.rotation.copyFrom(this.rotation);
  75670. if (this.rotationQuaternion) {
  75671. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  75672. }
  75673. mesh.scaling.copyFrom(this.scaling);
  75674. mesh.computeWorldMatrix(true);
  75675. return mesh;
  75676. };
  75677. return CSG;
  75678. }());
  75679. BABYLON.CSG = CSG;
  75680. })(BABYLON || (BABYLON = {}));
  75681. //# sourceMappingURL=babylon.csg.js.map
  75682. var BABYLON;
  75683. (function (BABYLON) {
  75684. var LensFlare = /** @class */ (function () {
  75685. function LensFlare(size, position, color, imgUrl, system) {
  75686. this.size = size;
  75687. this.position = position;
  75688. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  75689. this.color = color || new BABYLON.Color3(1, 1, 1);
  75690. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  75691. this._system = system;
  75692. system.lensFlares.push(this);
  75693. }
  75694. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  75695. return new LensFlare(size, position, color, imgUrl, system);
  75696. };
  75697. LensFlare.prototype.dispose = function () {
  75698. if (this.texture) {
  75699. this.texture.dispose();
  75700. }
  75701. // Remove from scene
  75702. var index = this._system.lensFlares.indexOf(this);
  75703. this._system.lensFlares.splice(index, 1);
  75704. };
  75705. ;
  75706. return LensFlare;
  75707. }());
  75708. BABYLON.LensFlare = LensFlare;
  75709. })(BABYLON || (BABYLON = {}));
  75710. //# sourceMappingURL=babylon.lensFlare.js.map
  75711. var BABYLON;
  75712. (function (BABYLON) {
  75713. var LensFlareSystem = /** @class */ (function () {
  75714. function LensFlareSystem(name, emitter, scene) {
  75715. this.name = name;
  75716. this.lensFlares = new Array();
  75717. this.borderLimit = 300;
  75718. this.viewportBorder = 0;
  75719. this.layerMask = 0x0FFFFFFF;
  75720. this._vertexBuffers = {};
  75721. this._isEnabled = true;
  75722. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  75723. this._emitter = emitter;
  75724. this.id = name;
  75725. scene.lensFlareSystems.push(this);
  75726. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  75727. var engine = scene.getEngine();
  75728. // VBO
  75729. var vertices = [];
  75730. vertices.push(1, 1);
  75731. vertices.push(-1, 1);
  75732. vertices.push(-1, -1);
  75733. vertices.push(1, -1);
  75734. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  75735. // Indices
  75736. var indices = [];
  75737. indices.push(0);
  75738. indices.push(1);
  75739. indices.push(2);
  75740. indices.push(0);
  75741. indices.push(2);
  75742. indices.push(3);
  75743. this._indexBuffer = engine.createIndexBuffer(indices);
  75744. // Effects
  75745. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  75746. }
  75747. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  75748. get: function () {
  75749. return this._isEnabled;
  75750. },
  75751. set: function (value) {
  75752. this._isEnabled = value;
  75753. },
  75754. enumerable: true,
  75755. configurable: true
  75756. });
  75757. LensFlareSystem.prototype.getScene = function () {
  75758. return this._scene;
  75759. };
  75760. LensFlareSystem.prototype.getEmitter = function () {
  75761. return this._emitter;
  75762. };
  75763. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  75764. this._emitter = newEmitter;
  75765. };
  75766. LensFlareSystem.prototype.getEmitterPosition = function () {
  75767. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  75768. };
  75769. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  75770. var position = this.getEmitterPosition();
  75771. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  75772. this._positionX = position.x;
  75773. this._positionY = position.y;
  75774. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  75775. if (this.viewportBorder > 0) {
  75776. globalViewport.x -= this.viewportBorder;
  75777. globalViewport.y -= this.viewportBorder;
  75778. globalViewport.width += this.viewportBorder * 2;
  75779. globalViewport.height += this.viewportBorder * 2;
  75780. position.x += this.viewportBorder;
  75781. position.y += this.viewportBorder;
  75782. this._positionX += this.viewportBorder;
  75783. this._positionY += this.viewportBorder;
  75784. }
  75785. if (position.z > 0) {
  75786. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  75787. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  75788. return true;
  75789. }
  75790. return true;
  75791. }
  75792. return false;
  75793. };
  75794. LensFlareSystem.prototype._isVisible = function () {
  75795. if (!this._isEnabled || !this._scene.activeCamera) {
  75796. return false;
  75797. }
  75798. var emitterPosition = this.getEmitterPosition();
  75799. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  75800. var distance = direction.length();
  75801. direction.normalize();
  75802. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  75803. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  75804. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  75805. };
  75806. LensFlareSystem.prototype.render = function () {
  75807. if (!this._effect.isReady() || !this._scene.activeCamera)
  75808. return false;
  75809. var engine = this._scene.getEngine();
  75810. var viewport = this._scene.activeCamera.viewport;
  75811. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  75812. // Position
  75813. if (!this.computeEffectivePosition(globalViewport)) {
  75814. return false;
  75815. }
  75816. // Visibility
  75817. if (!this._isVisible()) {
  75818. return false;
  75819. }
  75820. // Intensity
  75821. var awayX;
  75822. var awayY;
  75823. if (this._positionX < this.borderLimit + globalViewport.x) {
  75824. awayX = this.borderLimit + globalViewport.x - this._positionX;
  75825. }
  75826. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  75827. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  75828. }
  75829. else {
  75830. awayX = 0;
  75831. }
  75832. if (this._positionY < this.borderLimit + globalViewport.y) {
  75833. awayY = this.borderLimit + globalViewport.y - this._positionY;
  75834. }
  75835. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  75836. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  75837. }
  75838. else {
  75839. awayY = 0;
  75840. }
  75841. var away = (awayX > awayY) ? awayX : awayY;
  75842. away -= this.viewportBorder;
  75843. if (away > this.borderLimit) {
  75844. away = this.borderLimit;
  75845. }
  75846. var intensity = 1.0 - (away / this.borderLimit);
  75847. if (intensity < 0) {
  75848. return false;
  75849. }
  75850. if (intensity > 1.0) {
  75851. intensity = 1.0;
  75852. }
  75853. if (this.viewportBorder > 0) {
  75854. globalViewport.x += this.viewportBorder;
  75855. globalViewport.y += this.viewportBorder;
  75856. globalViewport.width -= this.viewportBorder * 2;
  75857. globalViewport.height -= this.viewportBorder * 2;
  75858. this._positionX -= this.viewportBorder;
  75859. this._positionY -= this.viewportBorder;
  75860. }
  75861. // Position
  75862. var centerX = globalViewport.x + globalViewport.width / 2;
  75863. var centerY = globalViewport.y + globalViewport.height / 2;
  75864. var distX = centerX - this._positionX;
  75865. var distY = centerY - this._positionY;
  75866. // Effects
  75867. engine.enableEffect(this._effect);
  75868. engine.setState(false);
  75869. engine.setDepthBuffer(false);
  75870. // VBOs
  75871. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  75872. // Flares
  75873. for (var index = 0; index < this.lensFlares.length; index++) {
  75874. var flare = this.lensFlares[index];
  75875. engine.setAlphaMode(flare.alphaMode);
  75876. var x = centerX - (distX * flare.position);
  75877. var y = centerY - (distY * flare.position);
  75878. var cw = flare.size;
  75879. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  75880. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  75881. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  75882. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  75883. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  75884. // Texture
  75885. this._effect.setTexture("textureSampler", flare.texture);
  75886. // Color
  75887. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  75888. // Draw order
  75889. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  75890. }
  75891. engine.setDepthBuffer(true);
  75892. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  75893. return true;
  75894. };
  75895. LensFlareSystem.prototype.dispose = function () {
  75896. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  75897. if (vertexBuffer) {
  75898. vertexBuffer.dispose();
  75899. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  75900. }
  75901. if (this._indexBuffer) {
  75902. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  75903. this._indexBuffer = null;
  75904. }
  75905. while (this.lensFlares.length) {
  75906. this.lensFlares[0].dispose();
  75907. }
  75908. // Remove from scene
  75909. var index = this._scene.lensFlareSystems.indexOf(this);
  75910. this._scene.lensFlareSystems.splice(index, 1);
  75911. };
  75912. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  75913. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  75914. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  75915. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  75916. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  75917. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  75918. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  75919. var parsedFlare = parsedLensFlareSystem.flares[index];
  75920. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  75921. }
  75922. return lensFlareSystem;
  75923. };
  75924. LensFlareSystem.prototype.serialize = function () {
  75925. var serializationObject = {};
  75926. serializationObject.id = this.id;
  75927. serializationObject.name = this.name;
  75928. serializationObject.emitterId = this.getEmitter().id;
  75929. serializationObject.borderLimit = this.borderLimit;
  75930. serializationObject.flares = [];
  75931. for (var index = 0; index < this.lensFlares.length; index++) {
  75932. var flare = this.lensFlares[index];
  75933. serializationObject.flares.push({
  75934. size: flare.size,
  75935. position: flare.position,
  75936. color: flare.color.asArray(),
  75937. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  75938. });
  75939. }
  75940. return serializationObject;
  75941. };
  75942. return LensFlareSystem;
  75943. }());
  75944. BABYLON.LensFlareSystem = LensFlareSystem;
  75945. })(BABYLON || (BABYLON = {}));
  75946. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  75947. var BABYLON;
  75948. (function (BABYLON) {
  75949. /**
  75950. * This is a holder class for the physics joint created by the physics plugin.
  75951. * It holds a set of functions to control the underlying joint.
  75952. */
  75953. var PhysicsJoint = /** @class */ (function () {
  75954. function PhysicsJoint(type, jointData) {
  75955. this.type = type;
  75956. this.jointData = jointData;
  75957. jointData.nativeParams = jointData.nativeParams || {};
  75958. }
  75959. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  75960. get: function () {
  75961. return this._physicsJoint;
  75962. },
  75963. set: function (newJoint) {
  75964. if (this._physicsJoint) {
  75965. //remove from the wolrd
  75966. }
  75967. this._physicsJoint = newJoint;
  75968. },
  75969. enumerable: true,
  75970. configurable: true
  75971. });
  75972. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  75973. set: function (physicsPlugin) {
  75974. this._physicsPlugin = physicsPlugin;
  75975. },
  75976. enumerable: true,
  75977. configurable: true
  75978. });
  75979. /**
  75980. * Execute a function that is physics-plugin specific.
  75981. * @param {Function} func the function that will be executed.
  75982. * It accepts two parameters: the physics world and the physics joint.
  75983. */
  75984. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  75985. func(this._physicsPlugin.world, this._physicsJoint);
  75986. };
  75987. //TODO check if the native joints are the same
  75988. //Joint Types
  75989. PhysicsJoint.DistanceJoint = 0;
  75990. PhysicsJoint.HingeJoint = 1;
  75991. PhysicsJoint.BallAndSocketJoint = 2;
  75992. PhysicsJoint.WheelJoint = 3;
  75993. PhysicsJoint.SliderJoint = 4;
  75994. //OIMO
  75995. PhysicsJoint.PrismaticJoint = 5;
  75996. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  75997. PhysicsJoint.UniversalJoint = 6;
  75998. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  75999. //Cannon
  76000. //Similar to a Ball-Joint. Different in params
  76001. PhysicsJoint.PointToPointJoint = 8;
  76002. //Cannon only at the moment
  76003. PhysicsJoint.SpringJoint = 9;
  76004. PhysicsJoint.LockJoint = 10;
  76005. return PhysicsJoint;
  76006. }());
  76007. BABYLON.PhysicsJoint = PhysicsJoint;
  76008. /**
  76009. * A class representing a physics distance joint.
  76010. */
  76011. var DistanceJoint = /** @class */ (function (_super) {
  76012. __extends(DistanceJoint, _super);
  76013. function DistanceJoint(jointData) {
  76014. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  76015. }
  76016. /**
  76017. * Update the predefined distance.
  76018. */
  76019. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  76020. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  76021. };
  76022. return DistanceJoint;
  76023. }(PhysicsJoint));
  76024. BABYLON.DistanceJoint = DistanceJoint;
  76025. var MotorEnabledJoint = /** @class */ (function (_super) {
  76026. __extends(MotorEnabledJoint, _super);
  76027. function MotorEnabledJoint(type, jointData) {
  76028. return _super.call(this, type, jointData) || this;
  76029. }
  76030. /**
  76031. * Set the motor values.
  76032. * Attention, this function is plugin specific. Engines won't react 100% the same.
  76033. * @param {number} force the force to apply
  76034. * @param {number} maxForce max force for this motor.
  76035. */
  76036. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  76037. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  76038. };
  76039. /**
  76040. * Set the motor's limits.
  76041. * Attention, this function is plugin specific. Engines won't react 100% the same.
  76042. */
  76043. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  76044. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  76045. };
  76046. return MotorEnabledJoint;
  76047. }(PhysicsJoint));
  76048. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  76049. /**
  76050. * This class represents a single hinge physics joint
  76051. */
  76052. var HingeJoint = /** @class */ (function (_super) {
  76053. __extends(HingeJoint, _super);
  76054. function HingeJoint(jointData) {
  76055. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  76056. }
  76057. /**
  76058. * Set the motor values.
  76059. * Attention, this function is plugin specific. Engines won't react 100% the same.
  76060. * @param {number} force the force to apply
  76061. * @param {number} maxForce max force for this motor.
  76062. */
  76063. HingeJoint.prototype.setMotor = function (force, maxForce) {
  76064. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  76065. };
  76066. /**
  76067. * Set the motor's limits.
  76068. * Attention, this function is plugin specific. Engines won't react 100% the same.
  76069. */
  76070. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  76071. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  76072. };
  76073. return HingeJoint;
  76074. }(MotorEnabledJoint));
  76075. BABYLON.HingeJoint = HingeJoint;
  76076. /**
  76077. * This class represents a dual hinge physics joint (same as wheel joint)
  76078. */
  76079. var Hinge2Joint = /** @class */ (function (_super) {
  76080. __extends(Hinge2Joint, _super);
  76081. function Hinge2Joint(jointData) {
  76082. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  76083. }
  76084. /**
  76085. * Set the motor values.
  76086. * Attention, this function is plugin specific. Engines won't react 100% the same.
  76087. * @param {number} force the force to apply
  76088. * @param {number} maxForce max force for this motor.
  76089. * @param {motorIndex} the motor's index, 0 or 1.
  76090. */
  76091. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  76092. if (motorIndex === void 0) { motorIndex = 0; }
  76093. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  76094. };
  76095. /**
  76096. * Set the motor limits.
  76097. * Attention, this function is plugin specific. Engines won't react 100% the same.
  76098. * @param {number} upperLimit the upper limit
  76099. * @param {number} lowerLimit lower limit
  76100. * @param {motorIndex} the motor's index, 0 or 1.
  76101. */
  76102. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  76103. if (motorIndex === void 0) { motorIndex = 0; }
  76104. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  76105. };
  76106. return Hinge2Joint;
  76107. }(MotorEnabledJoint));
  76108. BABYLON.Hinge2Joint = Hinge2Joint;
  76109. })(BABYLON || (BABYLON = {}));
  76110. //# sourceMappingURL=babylon.physicsJoint.js.map
  76111. var BABYLON;
  76112. (function (BABYLON) {
  76113. var PhysicsImpostor = /** @class */ (function () {
  76114. function PhysicsImpostor(object, type, _options, _scene) {
  76115. if (_options === void 0) { _options = { mass: 0 }; }
  76116. var _this = this;
  76117. this.object = object;
  76118. this.type = type;
  76119. this._options = _options;
  76120. this._scene = _scene;
  76121. this._bodyUpdateRequired = false;
  76122. this._onBeforePhysicsStepCallbacks = new Array();
  76123. this._onAfterPhysicsStepCallbacks = new Array();
  76124. this._onPhysicsCollideCallbacks = [];
  76125. this._deltaPosition = BABYLON.Vector3.Zero();
  76126. this._isDisposed = false;
  76127. //temp variables for parent rotation calculations
  76128. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  76129. this._tmpQuat = new BABYLON.Quaternion();
  76130. this._tmpQuat2 = new BABYLON.Quaternion();
  76131. /**
  76132. * this function is executed by the physics engine.
  76133. */
  76134. this.beforeStep = function () {
  76135. if (!_this._physicsEngine) {
  76136. return;
  76137. }
  76138. _this.object.translate(_this._deltaPosition, -1);
  76139. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  76140. _this.object.computeWorldMatrix(false);
  76141. if (_this.object.parent && _this.object.rotationQuaternion) {
  76142. _this.getParentsRotation();
  76143. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  76144. }
  76145. else {
  76146. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  76147. }
  76148. if (!_this._options.disableBidirectionalTransformation) {
  76149. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  76150. }
  76151. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  76152. func(_this);
  76153. });
  76154. };
  76155. /**
  76156. * this function is executed by the physics engine.
  76157. */
  76158. this.afterStep = function () {
  76159. if (!_this._physicsEngine) {
  76160. return;
  76161. }
  76162. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  76163. func(_this);
  76164. });
  76165. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  76166. // object has now its world rotation. needs to be converted to local.
  76167. if (_this.object.parent && _this.object.rotationQuaternion) {
  76168. _this.getParentsRotation();
  76169. _this._tmpQuat.conjugateInPlace();
  76170. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  76171. }
  76172. // take the position set and make it the absolute position of this object.
  76173. _this.object.setAbsolutePosition(_this.object.position);
  76174. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  76175. _this.object.translate(_this._deltaPosition, 1);
  76176. };
  76177. /**
  76178. * Legacy collision detection event support
  76179. */
  76180. this.onCollideEvent = null;
  76181. //event and body object due to cannon's event-based architecture.
  76182. this.onCollide = function (e) {
  76183. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  76184. return;
  76185. }
  76186. if (!_this._physicsEngine) {
  76187. return;
  76188. }
  76189. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  76190. if (otherImpostor) {
  76191. // Legacy collision detection event support
  76192. if (_this.onCollideEvent) {
  76193. _this.onCollideEvent(_this, otherImpostor);
  76194. }
  76195. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  76196. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  76197. }).forEach(function (obj) {
  76198. obj.callback(_this, otherImpostor);
  76199. });
  76200. }
  76201. };
  76202. //sanity check!
  76203. if (!this.object) {
  76204. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  76205. return;
  76206. }
  76207. //legacy support for old syntax.
  76208. if (!this._scene && object.getScene) {
  76209. this._scene = object.getScene();
  76210. }
  76211. if (!this._scene) {
  76212. return;
  76213. }
  76214. this._physicsEngine = this._scene.getPhysicsEngine();
  76215. if (!this._physicsEngine) {
  76216. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  76217. }
  76218. else {
  76219. //set the object's quaternion, if not set
  76220. if (!this.object.rotationQuaternion) {
  76221. if (this.object.rotation) {
  76222. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  76223. }
  76224. else {
  76225. this.object.rotationQuaternion = new BABYLON.Quaternion();
  76226. }
  76227. }
  76228. //default options params
  76229. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  76230. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  76231. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  76232. this._joints = [];
  76233. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  76234. if (!this.object.parent || this._options.ignoreParent) {
  76235. this._init();
  76236. }
  76237. else if (this.object.parent.physicsImpostor) {
  76238. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  76239. }
  76240. }
  76241. }
  76242. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  76243. get: function () {
  76244. return this._isDisposed;
  76245. },
  76246. enumerable: true,
  76247. configurable: true
  76248. });
  76249. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  76250. get: function () {
  76251. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  76252. },
  76253. set: function (value) {
  76254. this.setMass(value);
  76255. },
  76256. enumerable: true,
  76257. configurable: true
  76258. });
  76259. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  76260. get: function () {
  76261. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  76262. },
  76263. set: function (value) {
  76264. if (!this._physicsEngine) {
  76265. return;
  76266. }
  76267. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  76268. },
  76269. enumerable: true,
  76270. configurable: true
  76271. });
  76272. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  76273. get: function () {
  76274. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  76275. },
  76276. set: function (value) {
  76277. if (!this._physicsEngine) {
  76278. return;
  76279. }
  76280. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  76281. },
  76282. enumerable: true,
  76283. configurable: true
  76284. });
  76285. /**
  76286. * This function will completly initialize this impostor.
  76287. * It will create a new body - but only if this mesh has no parent.
  76288. * If it has, this impostor will not be used other than to define the impostor
  76289. * of the child mesh.
  76290. */
  76291. PhysicsImpostor.prototype._init = function () {
  76292. if (!this._physicsEngine) {
  76293. return;
  76294. }
  76295. this._physicsEngine.removeImpostor(this);
  76296. this.physicsBody = null;
  76297. this._parent = this._parent || this._getPhysicsParent();
  76298. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  76299. this._physicsEngine.addImpostor(this);
  76300. }
  76301. };
  76302. PhysicsImpostor.prototype._getPhysicsParent = function () {
  76303. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  76304. var parentMesh = this.object.parent;
  76305. return parentMesh.physicsImpostor;
  76306. }
  76307. return null;
  76308. };
  76309. /**
  76310. * Should a new body be generated.
  76311. */
  76312. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  76313. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  76314. };
  76315. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  76316. this.forceUpdate();
  76317. };
  76318. /**
  76319. * Force a regeneration of this or the parent's impostor's body.
  76320. * Use under cautious - This will remove all joints already implemented.
  76321. */
  76322. PhysicsImpostor.prototype.forceUpdate = function () {
  76323. this._init();
  76324. if (this.parent && !this._options.ignoreParent) {
  76325. this.parent.forceUpdate();
  76326. }
  76327. };
  76328. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  76329. /*public get mesh(): AbstractMesh {
  76330. return this._mesh;
  76331. }*/
  76332. /**
  76333. * Gets the body that holds this impostor. Either its own, or its parent.
  76334. */
  76335. get: function () {
  76336. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  76337. },
  76338. /**
  76339. * Set the physics body. Used mainly by the physics engine/plugin
  76340. */
  76341. set: function (physicsBody) {
  76342. if (this._physicsBody && this._physicsEngine) {
  76343. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  76344. }
  76345. this._physicsBody = physicsBody;
  76346. this.resetUpdateFlags();
  76347. },
  76348. enumerable: true,
  76349. configurable: true
  76350. });
  76351. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  76352. get: function () {
  76353. return !this._options.ignoreParent && this._parent ? this._parent : null;
  76354. },
  76355. set: function (value) {
  76356. this._parent = value;
  76357. },
  76358. enumerable: true,
  76359. configurable: true
  76360. });
  76361. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  76362. this._bodyUpdateRequired = false;
  76363. };
  76364. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  76365. if (this.object.getBoundingInfo) {
  76366. var q = this.object.rotationQuaternion;
  76367. //reset rotation
  76368. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  76369. //calculate the world matrix with no rotation
  76370. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  76371. var boundingInfo = this.object.getBoundingInfo();
  76372. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  76373. //bring back the rotation
  76374. this.object.rotationQuaternion = q;
  76375. //calculate the world matrix with the new rotation
  76376. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  76377. return size;
  76378. }
  76379. else {
  76380. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  76381. }
  76382. };
  76383. PhysicsImpostor.prototype.getObjectCenter = function () {
  76384. if (this.object.getBoundingInfo) {
  76385. var boundingInfo = this.object.getBoundingInfo();
  76386. return boundingInfo.boundingBox.centerWorld;
  76387. }
  76388. else {
  76389. return this.object.position;
  76390. }
  76391. };
  76392. /**
  76393. * Get a specific parametes from the options parameter.
  76394. */
  76395. PhysicsImpostor.prototype.getParam = function (paramName) {
  76396. return this._options[paramName];
  76397. };
  76398. /**
  76399. * Sets a specific parameter in the options given to the physics plugin
  76400. */
  76401. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  76402. this._options[paramName] = value;
  76403. this._bodyUpdateRequired = true;
  76404. };
  76405. /**
  76406. * Specifically change the body's mass option. Won't recreate the physics body object
  76407. */
  76408. PhysicsImpostor.prototype.setMass = function (mass) {
  76409. if (this.getParam("mass") !== mass) {
  76410. this.setParam("mass", mass);
  76411. }
  76412. if (this._physicsEngine) {
  76413. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  76414. }
  76415. };
  76416. PhysicsImpostor.prototype.getLinearVelocity = function () {
  76417. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  76418. };
  76419. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  76420. if (this._physicsEngine) {
  76421. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  76422. }
  76423. };
  76424. PhysicsImpostor.prototype.getAngularVelocity = function () {
  76425. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  76426. };
  76427. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  76428. if (this._physicsEngine) {
  76429. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  76430. }
  76431. };
  76432. /**
  76433. * Execute a function with the physics plugin native code.
  76434. * Provide a function the will have two variables - the world object and the physics body object.
  76435. */
  76436. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  76437. if (this._physicsEngine) {
  76438. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  76439. }
  76440. };
  76441. /**
  76442. * Register a function that will be executed before the physics world is stepping forward.
  76443. */
  76444. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  76445. this._onBeforePhysicsStepCallbacks.push(func);
  76446. };
  76447. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  76448. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  76449. if (index > -1) {
  76450. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  76451. }
  76452. else {
  76453. BABYLON.Tools.Warn("Function to remove was not found");
  76454. }
  76455. };
  76456. /**
  76457. * Register a function that will be executed after the physics step
  76458. */
  76459. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  76460. this._onAfterPhysicsStepCallbacks.push(func);
  76461. };
  76462. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  76463. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  76464. if (index > -1) {
  76465. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  76466. }
  76467. else {
  76468. BABYLON.Tools.Warn("Function to remove was not found");
  76469. }
  76470. };
  76471. /**
  76472. * register a function that will be executed when this impostor collides against a different body.
  76473. */
  76474. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  76475. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  76476. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  76477. };
  76478. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  76479. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  76480. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  76481. if (index > -1) {
  76482. this._onPhysicsCollideCallbacks.splice(index, 1);
  76483. }
  76484. else {
  76485. BABYLON.Tools.Warn("Function to remove was not found");
  76486. }
  76487. };
  76488. PhysicsImpostor.prototype.getParentsRotation = function () {
  76489. var parent = this.object.parent;
  76490. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  76491. while (parent) {
  76492. if (parent.rotationQuaternion) {
  76493. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  76494. }
  76495. else {
  76496. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  76497. }
  76498. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  76499. parent = parent.parent;
  76500. }
  76501. return this._tmpQuat;
  76502. };
  76503. /**
  76504. * Apply a force
  76505. */
  76506. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  76507. if (this._physicsEngine) {
  76508. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  76509. }
  76510. return this;
  76511. };
  76512. /**
  76513. * Apply an impulse
  76514. */
  76515. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  76516. if (this._physicsEngine) {
  76517. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  76518. }
  76519. return this;
  76520. };
  76521. /**
  76522. * A help function to create a joint.
  76523. */
  76524. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  76525. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  76526. this.addJoint(otherImpostor, joint);
  76527. return this;
  76528. };
  76529. /**
  76530. * Add a joint to this impostor with a different impostor.
  76531. */
  76532. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  76533. this._joints.push({
  76534. otherImpostor: otherImpostor,
  76535. joint: joint
  76536. });
  76537. if (this._physicsEngine) {
  76538. this._physicsEngine.addJoint(this, otherImpostor, joint);
  76539. }
  76540. return this;
  76541. };
  76542. /**
  76543. * Will keep this body still, in a sleep mode.
  76544. */
  76545. PhysicsImpostor.prototype.sleep = function () {
  76546. if (this._physicsEngine) {
  76547. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  76548. }
  76549. return this;
  76550. };
  76551. /**
  76552. * Wake the body up.
  76553. */
  76554. PhysicsImpostor.prototype.wakeUp = function () {
  76555. if (this._physicsEngine) {
  76556. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  76557. }
  76558. return this;
  76559. };
  76560. PhysicsImpostor.prototype.clone = function (newObject) {
  76561. if (!newObject)
  76562. return null;
  76563. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  76564. };
  76565. PhysicsImpostor.prototype.dispose = function () {
  76566. var _this = this;
  76567. //no dispose if no physics engine is available.
  76568. if (!this._physicsEngine) {
  76569. return;
  76570. }
  76571. this._joints.forEach(function (j) {
  76572. if (_this._physicsEngine) {
  76573. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  76574. }
  76575. });
  76576. //dispose the physics body
  76577. this._physicsEngine.removeImpostor(this);
  76578. if (this.parent) {
  76579. this.parent.forceUpdate();
  76580. }
  76581. else {
  76582. /*this._object.getChildMeshes().forEach(function(mesh) {
  76583. if (mesh.physicsImpostor) {
  76584. if (disposeChildren) {
  76585. mesh.physicsImpostor.dispose();
  76586. mesh.physicsImpostor = null;
  76587. }
  76588. }
  76589. })*/
  76590. }
  76591. this._isDisposed = true;
  76592. };
  76593. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  76594. this._deltaPosition.copyFrom(position);
  76595. };
  76596. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  76597. if (!this._deltaRotation) {
  76598. this._deltaRotation = new BABYLON.Quaternion();
  76599. }
  76600. this._deltaRotation.copyFrom(rotation);
  76601. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  76602. };
  76603. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  76604. if (this._physicsEngine) {
  76605. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  76606. }
  76607. return this;
  76608. };
  76609. PhysicsImpostor.prototype.getRadius = function () {
  76610. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  76611. };
  76612. /**
  76613. * Sync a bone with this impostor
  76614. * @param bone The bone to sync to the impostor.
  76615. * @param boneMesh The mesh that the bone is influencing.
  76616. * @param jointPivot The pivot of the joint / bone in local space.
  76617. * @param distToJoint Optional distance from the impostor to the joint.
  76618. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  76619. */
  76620. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  76621. var tempVec = PhysicsImpostor._tmpVecs[0];
  76622. var mesh = this.object;
  76623. if (mesh.rotationQuaternion) {
  76624. if (adjustRotation) {
  76625. var tempQuat = PhysicsImpostor._tmpQuat;
  76626. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  76627. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  76628. }
  76629. else {
  76630. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  76631. }
  76632. }
  76633. tempVec.x = 0;
  76634. tempVec.y = 0;
  76635. tempVec.z = 0;
  76636. if (jointPivot) {
  76637. tempVec.x = jointPivot.x;
  76638. tempVec.y = jointPivot.y;
  76639. tempVec.z = jointPivot.z;
  76640. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  76641. if (distToJoint === undefined || distToJoint === null) {
  76642. distToJoint = jointPivot.length();
  76643. }
  76644. tempVec.x *= distToJoint;
  76645. tempVec.y *= distToJoint;
  76646. tempVec.z *= distToJoint;
  76647. }
  76648. if (bone.getParent()) {
  76649. tempVec.addInPlace(mesh.getAbsolutePosition());
  76650. bone.setAbsolutePosition(tempVec, boneMesh);
  76651. }
  76652. else {
  76653. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  76654. boneMesh.position.x -= tempVec.x;
  76655. boneMesh.position.y -= tempVec.y;
  76656. boneMesh.position.z -= tempVec.z;
  76657. }
  76658. };
  76659. /**
  76660. * Sync impostor to a bone
  76661. * @param bone The bone that the impostor will be synced to.
  76662. * @param boneMesh The mesh that the bone is influencing.
  76663. * @param jointPivot The pivot of the joint / bone in local space.
  76664. * @param distToJoint Optional distance from the impostor to the joint.
  76665. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  76666. * @param boneAxis Optional vector3 axis the bone is aligned with
  76667. */
  76668. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  76669. var mesh = this.object;
  76670. if (mesh.rotationQuaternion) {
  76671. if (adjustRotation) {
  76672. var tempQuat = PhysicsImpostor._tmpQuat;
  76673. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  76674. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  76675. }
  76676. else {
  76677. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  76678. }
  76679. }
  76680. var pos = PhysicsImpostor._tmpVecs[0];
  76681. var boneDir = PhysicsImpostor._tmpVecs[1];
  76682. if (!boneAxis) {
  76683. boneAxis = PhysicsImpostor._tmpVecs[2];
  76684. boneAxis.x = 0;
  76685. boneAxis.y = 1;
  76686. boneAxis.z = 0;
  76687. }
  76688. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  76689. bone.getAbsolutePositionToRef(boneMesh, pos);
  76690. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  76691. distToJoint = jointPivot.length();
  76692. }
  76693. if (distToJoint !== undefined && distToJoint !== null) {
  76694. pos.x += boneDir.x * distToJoint;
  76695. pos.y += boneDir.y * distToJoint;
  76696. pos.z += boneDir.z * distToJoint;
  76697. }
  76698. mesh.setAbsolutePosition(pos);
  76699. };
  76700. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  76701. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  76702. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  76703. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  76704. //Impostor types
  76705. PhysicsImpostor.NoImpostor = 0;
  76706. PhysicsImpostor.SphereImpostor = 1;
  76707. PhysicsImpostor.BoxImpostor = 2;
  76708. PhysicsImpostor.PlaneImpostor = 3;
  76709. PhysicsImpostor.MeshImpostor = 4;
  76710. PhysicsImpostor.CylinderImpostor = 7;
  76711. PhysicsImpostor.ParticleImpostor = 8;
  76712. PhysicsImpostor.HeightmapImpostor = 9;
  76713. return PhysicsImpostor;
  76714. }());
  76715. BABYLON.PhysicsImpostor = PhysicsImpostor;
  76716. })(BABYLON || (BABYLON = {}));
  76717. //# sourceMappingURL=babylon.physicsImpostor.js.map
  76718. var BABYLON;
  76719. (function (BABYLON) {
  76720. var PhysicsEngine = /** @class */ (function () {
  76721. function PhysicsEngine(gravity, _physicsPlugin) {
  76722. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  76723. this._physicsPlugin = _physicsPlugin;
  76724. //new methods and parameters
  76725. this._impostors = [];
  76726. this._joints = [];
  76727. if (!this._physicsPlugin.isSupported()) {
  76728. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  76729. + "Please make sure it is included.");
  76730. }
  76731. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  76732. this.setGravity(gravity);
  76733. this.setTimeStep();
  76734. }
  76735. PhysicsEngine.prototype.setGravity = function (gravity) {
  76736. this.gravity = gravity;
  76737. this._physicsPlugin.setGravity(this.gravity);
  76738. };
  76739. /**
  76740. * Set the time step of the physics engine.
  76741. * default is 1/60.
  76742. * To slow it down, enter 1/600 for example.
  76743. * To speed it up, 1/30
  76744. * @param {number} newTimeStep the new timestep to apply to this world.
  76745. */
  76746. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  76747. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  76748. this._physicsPlugin.setTimeStep(newTimeStep);
  76749. };
  76750. /**
  76751. * Get the time step of the physics engine.
  76752. */
  76753. PhysicsEngine.prototype.getTimeStep = function () {
  76754. return this._physicsPlugin.getTimeStep();
  76755. };
  76756. PhysicsEngine.prototype.dispose = function () {
  76757. this._impostors.forEach(function (impostor) {
  76758. impostor.dispose();
  76759. });
  76760. this._physicsPlugin.dispose();
  76761. };
  76762. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  76763. return this._physicsPlugin.name;
  76764. };
  76765. /**
  76766. * Adding a new impostor for the impostor tracking.
  76767. * This will be done by the impostor itself.
  76768. * @param {PhysicsImpostor} impostor the impostor to add
  76769. */
  76770. PhysicsEngine.prototype.addImpostor = function (impostor) {
  76771. impostor.uniqueId = this._impostors.push(impostor);
  76772. //if no parent, generate the body
  76773. if (!impostor.parent) {
  76774. this._physicsPlugin.generatePhysicsBody(impostor);
  76775. }
  76776. };
  76777. /**
  76778. * Remove an impostor from the engine.
  76779. * This impostor and its mesh will not longer be updated by the physics engine.
  76780. * @param {PhysicsImpostor} impostor the impostor to remove
  76781. */
  76782. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  76783. var index = this._impostors.indexOf(impostor);
  76784. if (index > -1) {
  76785. var removed = this._impostors.splice(index, 1);
  76786. //Is it needed?
  76787. if (removed.length) {
  76788. //this will also remove it from the world.
  76789. removed[0].physicsBody = null;
  76790. }
  76791. }
  76792. };
  76793. /**
  76794. * Add a joint to the physics engine
  76795. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  76796. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  76797. * @param {PhysicsJoint} the joint that will connect both impostors.
  76798. */
  76799. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  76800. var impostorJoint = {
  76801. mainImpostor: mainImpostor,
  76802. connectedImpostor: connectedImpostor,
  76803. joint: joint
  76804. };
  76805. joint.physicsPlugin = this._physicsPlugin;
  76806. this._joints.push(impostorJoint);
  76807. this._physicsPlugin.generateJoint(impostorJoint);
  76808. };
  76809. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  76810. var matchingJoints = this._joints.filter(function (impostorJoint) {
  76811. return (impostorJoint.connectedImpostor === connectedImpostor
  76812. && impostorJoint.joint === joint
  76813. && impostorJoint.mainImpostor === mainImpostor);
  76814. });
  76815. if (matchingJoints.length) {
  76816. this._physicsPlugin.removeJoint(matchingJoints[0]);
  76817. //TODO remove it from the list as well
  76818. }
  76819. };
  76820. /**
  76821. * Called by the scene. no need to call it.
  76822. */
  76823. PhysicsEngine.prototype._step = function (delta) {
  76824. var _this = this;
  76825. //check if any mesh has no body / requires an update
  76826. this._impostors.forEach(function (impostor) {
  76827. if (impostor.isBodyInitRequired()) {
  76828. _this._physicsPlugin.generatePhysicsBody(impostor);
  76829. }
  76830. });
  76831. if (delta > 0.1) {
  76832. delta = 0.1;
  76833. }
  76834. else if (delta <= 0) {
  76835. delta = 1.0 / 60.0;
  76836. }
  76837. this._physicsPlugin.executeStep(delta, this._impostors);
  76838. };
  76839. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  76840. return this._physicsPlugin;
  76841. };
  76842. PhysicsEngine.prototype.getImpostors = function () {
  76843. return this._impostors;
  76844. };
  76845. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  76846. for (var i = 0; i < this._impostors.length; ++i) {
  76847. if (this._impostors[i].object === object) {
  76848. return this._impostors[i];
  76849. }
  76850. }
  76851. return null;
  76852. };
  76853. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  76854. for (var i = 0; i < this._impostors.length; ++i) {
  76855. if (this._impostors[i].physicsBody === body) {
  76856. return this._impostors[i];
  76857. }
  76858. }
  76859. return null;
  76860. };
  76861. // Statics
  76862. PhysicsEngine.Epsilon = 0.001;
  76863. return PhysicsEngine;
  76864. }());
  76865. BABYLON.PhysicsEngine = PhysicsEngine;
  76866. })(BABYLON || (BABYLON = {}));
  76867. //# sourceMappingURL=babylon.physicsEngine.js.map
  76868. var BABYLON;
  76869. (function (BABYLON) {
  76870. var PhysicsHelper = /** @class */ (function () {
  76871. function PhysicsHelper(scene) {
  76872. this._scene = scene;
  76873. this._physicsEngine = this._scene.getPhysicsEngine();
  76874. if (!this._physicsEngine) {
  76875. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  76876. }
  76877. }
  76878. /**
  76879. * @param {Vector3} origin the origin of the explosion
  76880. * @param {number} radius the explosion radius
  76881. * @param {number} strength the explosion strength
  76882. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  76883. */
  76884. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  76885. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  76886. if (!this._physicsEngine) {
  76887. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  76888. return null;
  76889. }
  76890. var impostors = this._physicsEngine.getImpostors();
  76891. if (impostors.length === 0) {
  76892. return null;
  76893. }
  76894. var event = new PhysicsRadialExplosionEvent(this._scene);
  76895. impostors.forEach(function (impostor) {
  76896. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  76897. if (!impostorForceAndContactPoint) {
  76898. return;
  76899. }
  76900. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  76901. });
  76902. event.dispose(false);
  76903. return event;
  76904. };
  76905. /**
  76906. * @param {Vector3} origin the origin of the explosion
  76907. * @param {number} radius the explosion radius
  76908. * @param {number} strength the explosion strength
  76909. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  76910. */
  76911. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  76912. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  76913. if (!this._physicsEngine) {
  76914. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  76915. return null;
  76916. }
  76917. var impostors = this._physicsEngine.getImpostors();
  76918. if (impostors.length === 0) {
  76919. return null;
  76920. }
  76921. var event = new PhysicsRadialExplosionEvent(this._scene);
  76922. impostors.forEach(function (impostor) {
  76923. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  76924. if (!impostorForceAndContactPoint) {
  76925. return;
  76926. }
  76927. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  76928. });
  76929. event.dispose(false);
  76930. return event;
  76931. };
  76932. /**
  76933. * @param {Vector3} origin the origin of the explosion
  76934. * @param {number} radius the explosion radius
  76935. * @param {number} strength the explosion strength
  76936. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  76937. */
  76938. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  76939. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  76940. if (!this._physicsEngine) {
  76941. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  76942. return null;
  76943. }
  76944. var impostors = this._physicsEngine.getImpostors();
  76945. if (impostors.length === 0) {
  76946. return null;
  76947. }
  76948. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  76949. event.dispose(false);
  76950. return event;
  76951. };
  76952. /**
  76953. * @param {Vector3} origin the origin of the updraft
  76954. * @param {number} radius the radius of the updraft
  76955. * @param {number} strength the strength of the updraft
  76956. * @param {number} height the height of the updraft
  76957. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  76958. */
  76959. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  76960. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  76961. if (!this._physicsEngine) {
  76962. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  76963. return null;
  76964. }
  76965. if (this._physicsEngine.getImpostors().length === 0) {
  76966. return null;
  76967. }
  76968. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  76969. event.dispose(false);
  76970. return event;
  76971. };
  76972. /**
  76973. * @param {Vector3} origin the of the vortex
  76974. * @param {number} radius the radius of the vortex
  76975. * @param {number} strength the strength of the vortex
  76976. * @param {number} height the height of the vortex
  76977. */
  76978. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  76979. if (!this._physicsEngine) {
  76980. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  76981. return null;
  76982. }
  76983. if (this._physicsEngine.getImpostors().length === 0) {
  76984. return null;
  76985. }
  76986. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  76987. event.dispose(false);
  76988. return event;
  76989. };
  76990. return PhysicsHelper;
  76991. }());
  76992. BABYLON.PhysicsHelper = PhysicsHelper;
  76993. /***** Radial explosion *****/
  76994. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  76995. function PhysicsRadialExplosionEvent(scene) {
  76996. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  76997. this._rays = [];
  76998. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  76999. this._scene = scene;
  77000. }
  77001. /**
  77002. * Returns the data related to the radial explosion event (sphere & rays).
  77003. * @returns {PhysicsRadialExplosionEventData}
  77004. */
  77005. PhysicsRadialExplosionEvent.prototype.getData = function () {
  77006. this._dataFetched = true;
  77007. return {
  77008. sphere: this._sphere,
  77009. rays: this._rays,
  77010. };
  77011. };
  77012. /**
  77013. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  77014. * @param impostor
  77015. * @param {Vector3} origin the origin of the explosion
  77016. * @param {number} radius the explosion radius
  77017. * @param {number} strength the explosion strength
  77018. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  77019. * @returns {Nullable<PhysicsForceAndContactPoint>}
  77020. */
  77021. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  77022. if (impostor.mass === 0) {
  77023. return null;
  77024. }
  77025. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  77026. return null;
  77027. }
  77028. if (impostor.object.getClassName() !== 'Mesh') {
  77029. return null;
  77030. }
  77031. var impostorObject = impostor.object;
  77032. var impostorObjectCenter = impostor.getObjectCenter();
  77033. var direction = impostorObjectCenter.subtract(origin);
  77034. var ray = new BABYLON.Ray(origin, direction, radius);
  77035. this._rays.push(ray);
  77036. var hit = ray.intersectsMesh(impostorObject);
  77037. var contactPoint = hit.pickedPoint;
  77038. if (!contactPoint) {
  77039. return null;
  77040. }
  77041. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  77042. if (distanceFromOrigin > radius) {
  77043. return null;
  77044. }
  77045. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  77046. ? strength
  77047. : strength * (1 - (distanceFromOrigin / radius));
  77048. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  77049. return { force: force, contactPoint: contactPoint };
  77050. };
  77051. /**
  77052. * Disposes the sphere.
  77053. * @param {bolean} force
  77054. */
  77055. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  77056. var _this = this;
  77057. if (force === void 0) { force = true; }
  77058. if (force) {
  77059. this._sphere.dispose();
  77060. }
  77061. else {
  77062. setTimeout(function () {
  77063. if (!_this._dataFetched) {
  77064. _this._sphere.dispose();
  77065. }
  77066. }, 0);
  77067. }
  77068. };
  77069. /*** Helpers ***/
  77070. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  77071. if (!this._sphere) {
  77072. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  77073. this._sphere.isVisible = false;
  77074. }
  77075. };
  77076. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  77077. var impostorObject = impostor.object;
  77078. this._prepareSphere();
  77079. this._sphere.position = origin;
  77080. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  77081. this._sphere._updateBoundingInfo();
  77082. this._sphere.computeWorldMatrix(true);
  77083. return this._sphere.intersectsMesh(impostorObject, true);
  77084. };
  77085. return PhysicsRadialExplosionEvent;
  77086. }());
  77087. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  77088. /***** Gravitational Field *****/
  77089. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  77090. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  77091. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  77092. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  77093. this._physicsHelper = physicsHelper;
  77094. this._scene = scene;
  77095. this._origin = origin;
  77096. this._radius = radius;
  77097. this._strength = strength;
  77098. this._falloff = falloff;
  77099. this._tickCallback = this._tick.bind(this);
  77100. }
  77101. /**
  77102. * Returns the data related to the gravitational field event (sphere).
  77103. * @returns {PhysicsGravitationalFieldEventData}
  77104. */
  77105. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  77106. this._dataFetched = true;
  77107. return {
  77108. sphere: this._sphere,
  77109. };
  77110. };
  77111. /**
  77112. * Enables the gravitational field.
  77113. */
  77114. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  77115. this._tickCallback.call(this);
  77116. this._scene.registerBeforeRender(this._tickCallback);
  77117. };
  77118. /**
  77119. * Disables the gravitational field.
  77120. */
  77121. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  77122. this._scene.unregisterBeforeRender(this._tickCallback);
  77123. };
  77124. /**
  77125. * Disposes the sphere.
  77126. * @param {bolean} force
  77127. */
  77128. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  77129. var _this = this;
  77130. if (force === void 0) { force = true; }
  77131. if (force) {
  77132. this._sphere.dispose();
  77133. }
  77134. else {
  77135. setTimeout(function () {
  77136. if (!_this._dataFetched) {
  77137. _this._sphere.dispose();
  77138. }
  77139. }, 0);
  77140. }
  77141. };
  77142. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  77143. // Since the params won't change, we fetch the event only once
  77144. if (this._sphere) {
  77145. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  77146. }
  77147. else {
  77148. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  77149. if (radialExplosionEvent) {
  77150. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  77151. }
  77152. }
  77153. };
  77154. return PhysicsGravitationalFieldEvent;
  77155. }());
  77156. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  77157. /***** Updraft *****/
  77158. var PhysicsUpdraftEvent = /** @class */ (function () {
  77159. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  77160. this._scene = _scene;
  77161. this._origin = _origin;
  77162. this._radius = _radius;
  77163. this._strength = _strength;
  77164. this._height = _height;
  77165. this._updraftMode = _updraftMode;
  77166. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  77167. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  77168. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  77169. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  77170. this._physicsEngine = this._scene.getPhysicsEngine();
  77171. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  77172. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  77173. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  77174. this._originDirection = this._origin.subtract(this._originTop).normalize();
  77175. }
  77176. this._tickCallback = this._tick.bind(this);
  77177. }
  77178. /**
  77179. * Returns the data related to the updraft event (cylinder).
  77180. * @returns {PhysicsUpdraftEventData}
  77181. */
  77182. PhysicsUpdraftEvent.prototype.getData = function () {
  77183. this._dataFetched = true;
  77184. return {
  77185. cylinder: this._cylinder,
  77186. };
  77187. };
  77188. /**
  77189. * Enables the updraft.
  77190. */
  77191. PhysicsUpdraftEvent.prototype.enable = function () {
  77192. this._tickCallback.call(this);
  77193. this._scene.registerBeforeRender(this._tickCallback);
  77194. };
  77195. /**
  77196. * Disables the cortex.
  77197. */
  77198. PhysicsUpdraftEvent.prototype.disable = function () {
  77199. this._scene.unregisterBeforeRender(this._tickCallback);
  77200. };
  77201. /**
  77202. * Disposes the sphere.
  77203. * @param {bolean} force
  77204. */
  77205. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  77206. var _this = this;
  77207. if (force === void 0) { force = true; }
  77208. if (force) {
  77209. this._cylinder.dispose();
  77210. }
  77211. else {
  77212. setTimeout(function () {
  77213. if (!_this._dataFetched) {
  77214. _this._cylinder.dispose();
  77215. }
  77216. }, 0);
  77217. }
  77218. };
  77219. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  77220. if (impostor.mass === 0) {
  77221. return null;
  77222. }
  77223. if (!this._intersectsWithCylinder(impostor)) {
  77224. return null;
  77225. }
  77226. var impostorObjectCenter = impostor.getObjectCenter();
  77227. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  77228. var direction = this._originDirection;
  77229. }
  77230. else {
  77231. var direction = impostorObjectCenter.subtract(this._originTop);
  77232. }
  77233. var multiplier = this._strength * -1;
  77234. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  77235. return { force: force, contactPoint: impostorObjectCenter };
  77236. };
  77237. PhysicsUpdraftEvent.prototype._tick = function () {
  77238. var _this = this;
  77239. this._physicsEngine.getImpostors().forEach(function (impostor) {
  77240. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  77241. if (!impostorForceAndContactPoint) {
  77242. return;
  77243. }
  77244. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  77245. });
  77246. };
  77247. /*** Helpers ***/
  77248. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  77249. if (!this._cylinder) {
  77250. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  77251. height: this._height,
  77252. diameter: this._radius * 2,
  77253. }, this._scene);
  77254. this._cylinder.isVisible = false;
  77255. }
  77256. };
  77257. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  77258. var impostorObject = impostor.object;
  77259. this._prepareCylinder();
  77260. this._cylinder.position = this._cylinderPosition;
  77261. return this._cylinder.intersectsMesh(impostorObject, true);
  77262. };
  77263. return PhysicsUpdraftEvent;
  77264. }());
  77265. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  77266. /***** Vortex *****/
  77267. var PhysicsVortexEvent = /** @class */ (function () {
  77268. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  77269. this._scene = _scene;
  77270. this._origin = _origin;
  77271. this._radius = _radius;
  77272. this._strength = _strength;
  77273. this._height = _height;
  77274. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  77275. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  77276. this._updraftMultiplier = 0.02;
  77277. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  77278. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  77279. this._physicsEngine = this._scene.getPhysicsEngine();
  77280. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  77281. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  77282. this._tickCallback = this._tick.bind(this);
  77283. }
  77284. /**
  77285. * Returns the data related to the vortex event (cylinder).
  77286. * @returns {PhysicsVortexEventData}
  77287. */
  77288. PhysicsVortexEvent.prototype.getData = function () {
  77289. this._dataFetched = true;
  77290. return {
  77291. cylinder: this._cylinder,
  77292. };
  77293. };
  77294. /**
  77295. * Enables the vortex.
  77296. */
  77297. PhysicsVortexEvent.prototype.enable = function () {
  77298. this._tickCallback.call(this);
  77299. this._scene.registerBeforeRender(this._tickCallback);
  77300. };
  77301. /**
  77302. * Disables the cortex.
  77303. */
  77304. PhysicsVortexEvent.prototype.disable = function () {
  77305. this._scene.unregisterBeforeRender(this._tickCallback);
  77306. };
  77307. /**
  77308. * Disposes the sphere.
  77309. * @param {bolean} force
  77310. */
  77311. PhysicsVortexEvent.prototype.dispose = function (force) {
  77312. var _this = this;
  77313. if (force === void 0) { force = true; }
  77314. if (force) {
  77315. this._cylinder.dispose();
  77316. }
  77317. else {
  77318. setTimeout(function () {
  77319. if (!_this._dataFetched) {
  77320. _this._cylinder.dispose();
  77321. }
  77322. }, 0);
  77323. }
  77324. };
  77325. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  77326. if (impostor.mass === 0) {
  77327. return null;
  77328. }
  77329. if (!this._intersectsWithCylinder(impostor)) {
  77330. return null;
  77331. }
  77332. if (impostor.object.getClassName() !== 'Mesh') {
  77333. return null;
  77334. }
  77335. var impostorObject = impostor.object;
  77336. var impostorObjectCenter = impostor.getObjectCenter();
  77337. 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)
  77338. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  77339. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  77340. var hit = ray.intersectsMesh(impostorObject);
  77341. var contactPoint = hit.pickedPoint;
  77342. if (!contactPoint) {
  77343. return null;
  77344. }
  77345. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  77346. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  77347. var directionToOrigin = contactPoint.normalize();
  77348. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  77349. directionToOrigin = directionToOrigin.negate();
  77350. }
  77351. // TODO: find a more physically based solution
  77352. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  77353. var forceX = directionToOrigin.x * this._strength / 8;
  77354. var forceY = directionToOrigin.y * this._updraftMultiplier;
  77355. var forceZ = directionToOrigin.z * this._strength / 8;
  77356. }
  77357. else {
  77358. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  77359. var forceY = this._originTop.y * this._updraftMultiplier;
  77360. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  77361. }
  77362. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  77363. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  77364. return { force: force, contactPoint: impostorObjectCenter };
  77365. };
  77366. PhysicsVortexEvent.prototype._tick = function () {
  77367. var _this = this;
  77368. this._physicsEngine.getImpostors().forEach(function (impostor) {
  77369. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  77370. if (!impostorForceAndContactPoint) {
  77371. return;
  77372. }
  77373. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  77374. });
  77375. };
  77376. /*** Helpers ***/
  77377. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  77378. if (!this._cylinder) {
  77379. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  77380. height: this._height,
  77381. diameter: this._radius * 2,
  77382. }, this._scene);
  77383. this._cylinder.isVisible = false;
  77384. }
  77385. };
  77386. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  77387. var impostorObject = impostor.object;
  77388. this._prepareCylinder();
  77389. this._cylinder.position = this._cylinderPosition;
  77390. return this._cylinder.intersectsMesh(impostorObject, true);
  77391. };
  77392. return PhysicsVortexEvent;
  77393. }());
  77394. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  77395. /***** Enums *****/
  77396. /**
  77397. * The strenght of the force in correspondence to the distance of the affected object
  77398. */
  77399. var PhysicsRadialImpulseFalloff;
  77400. (function (PhysicsRadialImpulseFalloff) {
  77401. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  77402. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear"; // impulse gets weaker if it's further from the origin
  77403. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  77404. /**
  77405. * The strenght of the force in correspondence to the distance of the affected object
  77406. */
  77407. var PhysicsUpdraftMode;
  77408. (function (PhysicsUpdraftMode) {
  77409. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  77410. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular"; // once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder
  77411. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  77412. })(BABYLON || (BABYLON = {}));
  77413. //# sourceMappingURL=babylon.physicsHelper.js.map
  77414. var BABYLON;
  77415. (function (BABYLON) {
  77416. var CannonJSPlugin = /** @class */ (function () {
  77417. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  77418. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  77419. if (iterations === void 0) { iterations = 10; }
  77420. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  77421. this.name = "CannonJSPlugin";
  77422. this._physicsMaterials = new Array();
  77423. this._fixedTimeStep = 1 / 60;
  77424. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  77425. this.BJSCANNON = typeof CANNON !== 'undefined' ? CANNON : ( true ? __webpack_require__(17) : undefined);
  77426. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  77427. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  77428. this._tmpPosition = BABYLON.Vector3.Zero();
  77429. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  77430. this._tmpUnityRotation = new BABYLON.Quaternion();
  77431. if (!this.isSupported()) {
  77432. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  77433. return;
  77434. }
  77435. this._extendNamespace();
  77436. this.world = new this.BJSCANNON.World();
  77437. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  77438. this.world.solver.iterations = iterations;
  77439. }
  77440. CannonJSPlugin.prototype.setGravity = function (gravity) {
  77441. this.world.gravity.copy(gravity);
  77442. };
  77443. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  77444. this._fixedTimeStep = timeStep;
  77445. };
  77446. CannonJSPlugin.prototype.getTimeStep = function () {
  77447. return this._fixedTimeStep;
  77448. };
  77449. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  77450. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  77451. };
  77452. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  77453. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  77454. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  77455. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  77456. };
  77457. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  77458. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  77459. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  77460. impostor.physicsBody.applyForce(impulse, worldPoint);
  77461. };
  77462. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  77463. //parent-child relationship. Does this impostor has a parent impostor?
  77464. if (impostor.parent) {
  77465. if (impostor.physicsBody) {
  77466. this.removePhysicsBody(impostor);
  77467. //TODO is that needed?
  77468. impostor.forceUpdate();
  77469. }
  77470. return;
  77471. }
  77472. //should a new body be created for this impostor?
  77473. if (impostor.isBodyInitRequired()) {
  77474. var shape = this._createShape(impostor);
  77475. //unregister events, if body is being changed
  77476. var oldBody = impostor.physicsBody;
  77477. if (oldBody) {
  77478. this.removePhysicsBody(impostor);
  77479. }
  77480. //create the body and material
  77481. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  77482. var bodyCreationObject = {
  77483. mass: impostor.getParam("mass"),
  77484. material: material
  77485. };
  77486. // A simple extend, in case native options were used.
  77487. var nativeOptions = impostor.getParam("nativeOptions");
  77488. for (var key in nativeOptions) {
  77489. if (nativeOptions.hasOwnProperty(key)) {
  77490. bodyCreationObject[key] = nativeOptions[key];
  77491. }
  77492. }
  77493. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  77494. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  77495. this.world.addEventListener("preStep", impostor.beforeStep);
  77496. this.world.addEventListener("postStep", impostor.afterStep);
  77497. impostor.physicsBody.addShape(shape);
  77498. this.world.add(impostor.physicsBody);
  77499. //try to keep the body moving in the right direction by taking old properties.
  77500. //Should be tested!
  77501. if (oldBody) {
  77502. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  77503. impostor.physicsBody[param].copy(oldBody[param]);
  77504. });
  77505. }
  77506. this._processChildMeshes(impostor);
  77507. }
  77508. //now update the body's transformation
  77509. this._updatePhysicsBodyTransformation(impostor);
  77510. };
  77511. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  77512. var _this = this;
  77513. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  77514. var currentRotation = mainImpostor.object.rotationQuaternion;
  77515. if (meshChildren.length) {
  77516. var processMesh = function (localPosition, mesh) {
  77517. if (!currentRotation || !mesh.rotationQuaternion) {
  77518. return;
  77519. }
  77520. var childImpostor = mesh.getPhysicsImpostor();
  77521. if (childImpostor) {
  77522. var parent = childImpostor.parent;
  77523. if (parent !== mainImpostor) {
  77524. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  77525. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  77526. if (childImpostor.physicsBody) {
  77527. _this.removePhysicsBody(childImpostor);
  77528. childImpostor.physicsBody = null;
  77529. }
  77530. childImpostor.parent = mainImpostor;
  77531. childImpostor.resetUpdateFlags();
  77532. 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));
  77533. //Add the mass of the children.
  77534. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  77535. }
  77536. }
  77537. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  77538. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  77539. };
  77540. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  77541. }
  77542. };
  77543. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  77544. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  77545. this.world.removeEventListener("preStep", impostor.beforeStep);
  77546. this.world.removeEventListener("postStep", impostor.afterStep);
  77547. this.world.remove(impostor.physicsBody);
  77548. };
  77549. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  77550. var mainBody = impostorJoint.mainImpostor.physicsBody;
  77551. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  77552. if (!mainBody || !connectedBody) {
  77553. return;
  77554. }
  77555. var constraint;
  77556. var jointData = impostorJoint.joint.jointData;
  77557. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  77558. var constraintData = {
  77559. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  77560. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  77561. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  77562. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  77563. maxForce: jointData.nativeParams.maxForce,
  77564. collideConnected: !!jointData.collision
  77565. };
  77566. switch (impostorJoint.joint.type) {
  77567. case BABYLON.PhysicsJoint.HingeJoint:
  77568. case BABYLON.PhysicsJoint.Hinge2Joint:
  77569. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  77570. break;
  77571. case BABYLON.PhysicsJoint.DistanceJoint:
  77572. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  77573. break;
  77574. case BABYLON.PhysicsJoint.SpringJoint:
  77575. var springData = jointData;
  77576. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  77577. restLength: springData.length,
  77578. stiffness: springData.stiffness,
  77579. damping: springData.damping,
  77580. localAnchorA: constraintData.pivotA,
  77581. localAnchorB: constraintData.pivotB
  77582. });
  77583. break;
  77584. case BABYLON.PhysicsJoint.LockJoint:
  77585. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  77586. break;
  77587. case BABYLON.PhysicsJoint.PointToPointJoint:
  77588. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  77589. default:
  77590. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  77591. break;
  77592. }
  77593. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  77594. constraint.collideConnected = !!jointData.collision;
  77595. impostorJoint.joint.physicsJoint = constraint;
  77596. //don't add spring as constraint, as it is not one.
  77597. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  77598. this.world.addConstraint(constraint);
  77599. }
  77600. else {
  77601. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  77602. constraint.applyForce();
  77603. });
  77604. }
  77605. };
  77606. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  77607. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  77608. };
  77609. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  77610. var index;
  77611. var mat;
  77612. for (index = 0; index < this._physicsMaterials.length; index++) {
  77613. mat = this._physicsMaterials[index];
  77614. if (mat.friction === friction && mat.restitution === restitution) {
  77615. return mat;
  77616. }
  77617. }
  77618. var currentMat = new this.BJSCANNON.Material(name);
  77619. currentMat.friction = friction;
  77620. currentMat.restitution = restitution;
  77621. this._physicsMaterials.push(currentMat);
  77622. return currentMat;
  77623. };
  77624. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  77625. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  77626. };
  77627. CannonJSPlugin.prototype._createShape = function (impostor) {
  77628. var object = impostor.object;
  77629. var returnValue;
  77630. var extendSize = impostor.getObjectExtendSize();
  77631. switch (impostor.type) {
  77632. case BABYLON.PhysicsImpostor.SphereImpostor:
  77633. var radiusX = extendSize.x;
  77634. var radiusY = extendSize.y;
  77635. var radiusZ = extendSize.z;
  77636. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  77637. break;
  77638. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  77639. case BABYLON.PhysicsImpostor.CylinderImpostor:
  77640. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  77641. break;
  77642. case BABYLON.PhysicsImpostor.BoxImpostor:
  77643. var box = extendSize.scale(0.5);
  77644. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  77645. break;
  77646. case BABYLON.PhysicsImpostor.PlaneImpostor:
  77647. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  77648. returnValue = new this.BJSCANNON.Plane();
  77649. break;
  77650. case BABYLON.PhysicsImpostor.MeshImpostor:
  77651. // should transform the vertex data to world coordinates!!
  77652. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  77653. var rawFaces = object.getIndices ? object.getIndices() : [];
  77654. if (!rawVerts)
  77655. return;
  77656. // get only scale! so the object could transform correctly.
  77657. var oldPosition = object.position.clone();
  77658. var oldRotation = object.rotation && object.rotation.clone();
  77659. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  77660. object.position.copyFromFloats(0, 0, 0);
  77661. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  77662. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  77663. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  77664. var transform = object.computeWorldMatrix(true);
  77665. // convert rawVerts to object space
  77666. var temp = new Array();
  77667. var index;
  77668. for (index = 0; index < rawVerts.length; index += 3) {
  77669. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  77670. }
  77671. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  77672. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  77673. //now set back the transformation!
  77674. object.position.copyFrom(oldPosition);
  77675. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  77676. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  77677. break;
  77678. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  77679. var oldPosition2 = object.position.clone();
  77680. var oldRotation2 = object.rotation && object.rotation.clone();
  77681. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  77682. object.position.copyFromFloats(0, 0, 0);
  77683. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  77684. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  77685. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  77686. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  77687. returnValue = this._createHeightmap(object);
  77688. object.position.copyFrom(oldPosition2);
  77689. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  77690. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  77691. object.computeWorldMatrix(true);
  77692. break;
  77693. case BABYLON.PhysicsImpostor.ParticleImpostor:
  77694. returnValue = new this.BJSCANNON.Particle();
  77695. break;
  77696. }
  77697. return returnValue;
  77698. };
  77699. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  77700. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  77701. var transform = object.computeWorldMatrix(true);
  77702. // convert rawVerts to object space
  77703. var temp = new Array();
  77704. var index;
  77705. for (index = 0; index < pos.length; index += 3) {
  77706. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  77707. }
  77708. pos = temp;
  77709. var matrix = new Array();
  77710. //For now pointDepth will not be used and will be automatically calculated.
  77711. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  77712. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  77713. var boundingInfo = object.getBoundingInfo();
  77714. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  77715. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  77716. var elementSize = dim * 2 / arraySize;
  77717. for (var i = 0; i < pos.length; i = i + 3) {
  77718. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  77719. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  77720. var y = -pos[i + 2] + minY;
  77721. if (!matrix[x]) {
  77722. matrix[x] = [];
  77723. }
  77724. if (!matrix[x][z]) {
  77725. matrix[x][z] = y;
  77726. }
  77727. matrix[x][z] = Math.max(y, matrix[x][z]);
  77728. }
  77729. for (var x = 0; x <= arraySize; ++x) {
  77730. if (!matrix[x]) {
  77731. var loc = 1;
  77732. while (!matrix[(x + loc) % arraySize]) {
  77733. loc++;
  77734. }
  77735. matrix[x] = matrix[(x + loc) % arraySize].slice();
  77736. //console.log("missing x", x);
  77737. }
  77738. for (var z = 0; z <= arraySize; ++z) {
  77739. if (!matrix[x][z]) {
  77740. var loc = 1;
  77741. var newValue;
  77742. while (newValue === undefined) {
  77743. newValue = matrix[x][(z + loc++) % arraySize];
  77744. }
  77745. matrix[x][z] = newValue;
  77746. }
  77747. }
  77748. }
  77749. var shape = new this.BJSCANNON.Heightfield(matrix, {
  77750. elementSize: elementSize
  77751. });
  77752. //For future reference, needed for body transformation
  77753. shape.minY = minY;
  77754. return shape;
  77755. };
  77756. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  77757. var object = impostor.object;
  77758. //make sure it is updated...
  77759. object.computeWorldMatrix && object.computeWorldMatrix(true);
  77760. // The delta between the mesh position and the mesh bounding box center
  77761. var bInfo = object.getBoundingInfo();
  77762. if (!bInfo)
  77763. return;
  77764. var center = impostor.getObjectCenter();
  77765. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  77766. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  77767. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  77768. this._tmpPosition.copyFrom(center);
  77769. var quaternion = object.rotationQuaternion;
  77770. if (!quaternion) {
  77771. return;
  77772. }
  77773. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  77774. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  77775. //-90 DEG in X, precalculated
  77776. quaternion = quaternion.multiply(this._minus90X);
  77777. //Invert! (Precalculated, 90 deg in X)
  77778. //No need to clone. this will never change.
  77779. impostor.setDeltaRotation(this._plus90X);
  77780. }
  77781. //If it is a heightfield, if should be centered.
  77782. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  77783. var mesh = object;
  77784. var boundingInfo = mesh.getBoundingInfo();
  77785. //calculate the correct body position:
  77786. var rotationQuaternion = mesh.rotationQuaternion;
  77787. mesh.rotationQuaternion = this._tmpUnityRotation;
  77788. mesh.computeWorldMatrix(true);
  77789. //get original center with no rotation
  77790. var c = center.clone();
  77791. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  77792. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  77793. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  77794. mesh.setPreTransformMatrix(p);
  77795. mesh.computeWorldMatrix(true);
  77796. //calculate the translation
  77797. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  77798. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  77799. //add it inverted to the delta
  77800. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  77801. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  77802. //rotation is back
  77803. mesh.rotationQuaternion = rotationQuaternion;
  77804. mesh.setPreTransformMatrix(oldPivot);
  77805. mesh.computeWorldMatrix(true);
  77806. }
  77807. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  77808. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  77809. //this._tmpPosition.copyFrom(object.position);
  77810. }
  77811. impostor.setDeltaPosition(this._tmpDeltaPosition);
  77812. //Now update the impostor object
  77813. impostor.physicsBody.position.copy(this._tmpPosition);
  77814. impostor.physicsBody.quaternion.copy(quaternion);
  77815. };
  77816. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  77817. impostor.object.position.copyFrom(impostor.physicsBody.position);
  77818. if (impostor.object.rotationQuaternion) {
  77819. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  77820. }
  77821. };
  77822. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  77823. impostor.physicsBody.position.copy(newPosition);
  77824. impostor.physicsBody.quaternion.copy(newRotation);
  77825. };
  77826. CannonJSPlugin.prototype.isSupported = function () {
  77827. return this.BJSCANNON !== undefined;
  77828. };
  77829. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  77830. impostor.physicsBody.velocity.copy(velocity);
  77831. };
  77832. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  77833. impostor.physicsBody.angularVelocity.copy(velocity);
  77834. };
  77835. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  77836. var v = impostor.physicsBody.velocity;
  77837. if (!v) {
  77838. return null;
  77839. }
  77840. return new BABYLON.Vector3(v.x, v.y, v.z);
  77841. };
  77842. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  77843. var v = impostor.physicsBody.angularVelocity;
  77844. if (!v) {
  77845. return null;
  77846. }
  77847. return new BABYLON.Vector3(v.x, v.y, v.z);
  77848. };
  77849. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  77850. impostor.physicsBody.mass = mass;
  77851. impostor.physicsBody.updateMassProperties();
  77852. };
  77853. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  77854. return impostor.physicsBody.mass;
  77855. };
  77856. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  77857. return impostor.physicsBody.material.friction;
  77858. };
  77859. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  77860. impostor.physicsBody.material.friction = friction;
  77861. };
  77862. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  77863. return impostor.physicsBody.material.restitution;
  77864. };
  77865. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  77866. impostor.physicsBody.material.restitution = restitution;
  77867. };
  77868. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  77869. impostor.physicsBody.sleep();
  77870. };
  77871. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  77872. impostor.physicsBody.wakeUp();
  77873. };
  77874. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  77875. joint.physicsJoint.distance = maxDistance;
  77876. };
  77877. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  77878. // if (!motorIndex) {
  77879. // joint.physicsJoint.enableMotor();
  77880. // }
  77881. // }
  77882. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  77883. // if (!motorIndex) {
  77884. // joint.physicsJoint.disableMotor();
  77885. // }
  77886. // }
  77887. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  77888. if (!motorIndex) {
  77889. joint.physicsJoint.enableMotor();
  77890. joint.physicsJoint.setMotorSpeed(speed);
  77891. if (maxForce) {
  77892. this.setLimit(joint, maxForce);
  77893. }
  77894. }
  77895. };
  77896. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  77897. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  77898. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  77899. };
  77900. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  77901. var body = impostor.physicsBody;
  77902. mesh.position.x = body.position.x;
  77903. mesh.position.y = body.position.y;
  77904. mesh.position.z = body.position.z;
  77905. if (mesh.rotationQuaternion) {
  77906. mesh.rotationQuaternion.x = body.quaternion.x;
  77907. mesh.rotationQuaternion.y = body.quaternion.y;
  77908. mesh.rotationQuaternion.z = body.quaternion.z;
  77909. mesh.rotationQuaternion.w = body.quaternion.w;
  77910. }
  77911. };
  77912. CannonJSPlugin.prototype.getRadius = function (impostor) {
  77913. var shape = impostor.physicsBody.shapes[0];
  77914. return shape.boundingSphereRadius;
  77915. };
  77916. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  77917. var shape = impostor.physicsBody.shapes[0];
  77918. result.x = shape.halfExtents.x * 2;
  77919. result.y = shape.halfExtents.y * 2;
  77920. result.z = shape.halfExtents.z * 2;
  77921. };
  77922. CannonJSPlugin.prototype.dispose = function () {
  77923. };
  77924. CannonJSPlugin.prototype._extendNamespace = function () {
  77925. //this will force cannon to execute at least one step when using interpolation
  77926. var step_tmp1 = new this.BJSCANNON.Vec3();
  77927. var Engine = this.BJSCANNON;
  77928. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  77929. maxSubSteps = maxSubSteps || 10;
  77930. timeSinceLastCalled = timeSinceLastCalled || 0;
  77931. if (timeSinceLastCalled === 0) {
  77932. this.internalStep(dt);
  77933. this.time += dt;
  77934. }
  77935. else {
  77936. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  77937. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  77938. var t0 = performance.now();
  77939. for (var i = 0; i !== internalSteps; i++) {
  77940. this.internalStep(dt);
  77941. if (performance.now() - t0 > dt * 1000) {
  77942. break;
  77943. }
  77944. }
  77945. this.time += timeSinceLastCalled;
  77946. var h = this.time % dt;
  77947. var h_div_dt = h / dt;
  77948. var interpvelo = step_tmp1;
  77949. var bodies = this.bodies;
  77950. for (var j = 0; j !== bodies.length; j++) {
  77951. var b = bodies[j];
  77952. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  77953. b.position.vsub(b.previousPosition, interpvelo);
  77954. interpvelo.scale(h_div_dt, interpvelo);
  77955. b.position.vadd(interpvelo, b.interpolatedPosition);
  77956. }
  77957. else {
  77958. b.interpolatedPosition.copy(b.position);
  77959. b.interpolatedQuaternion.copy(b.quaternion);
  77960. }
  77961. }
  77962. }
  77963. };
  77964. };
  77965. return CannonJSPlugin;
  77966. }());
  77967. BABYLON.CannonJSPlugin = CannonJSPlugin;
  77968. })(BABYLON || (BABYLON = {}));
  77969. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  77970. var BABYLON;
  77971. (function (BABYLON) {
  77972. var OimoJSPlugin = /** @class */ (function () {
  77973. function OimoJSPlugin(iterations) {
  77974. this.name = "OimoJSPlugin";
  77975. this._tmpImpostorsArray = [];
  77976. this._tmpPositionVector = BABYLON.Vector3.Zero();
  77977. this.BJSOIMO = typeof OIMO !== 'undefined' ? OIMO : ( true ? __webpack_require__(18) : undefined);
  77978. this.world = new this.BJSOIMO.World(1 / 60, 2, iterations, true);
  77979. this.world.worldscale(1);
  77980. this.world.clear();
  77981. //making sure no stats are calculated
  77982. this.world.isNoStat = true;
  77983. }
  77984. OimoJSPlugin.prototype.setGravity = function (gravity) {
  77985. this.world.gravity.copy(gravity);
  77986. };
  77987. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  77988. this.world.timeStep = timeStep;
  77989. };
  77990. OimoJSPlugin.prototype.getTimeStep = function () {
  77991. return this.world.timeStep;
  77992. };
  77993. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  77994. var _this = this;
  77995. impostors.forEach(function (impostor) {
  77996. impostor.beforeStep();
  77997. });
  77998. this.world.step();
  77999. impostors.forEach(function (impostor) {
  78000. impostor.afterStep();
  78001. //update the ordered impostors array
  78002. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  78003. });
  78004. //check for collisions
  78005. var contact = this.world.contacts;
  78006. while (contact !== null) {
  78007. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  78008. contact = contact.next;
  78009. continue;
  78010. }
  78011. //is this body colliding with any other? get the impostor
  78012. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  78013. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  78014. if (!mainImpostor || !collidingImpostor) {
  78015. contact = contact.next;
  78016. continue;
  78017. }
  78018. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  78019. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  78020. contact = contact.next;
  78021. }
  78022. };
  78023. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  78024. var mass = impostor.physicsBody.massInfo.mass;
  78025. impostor.physicsBody.applyImpulse(contactPoint.scale(this.BJSOIMO.INV_SCALE), force.scale(this.BJSOIMO.INV_SCALE * mass));
  78026. };
  78027. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  78028. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  78029. this.applyImpulse(impostor, force, contactPoint);
  78030. };
  78031. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  78032. var _this = this;
  78033. //parent-child relationship. Does this impostor has a parent impostor?
  78034. if (impostor.parent) {
  78035. if (impostor.physicsBody) {
  78036. this.removePhysicsBody(impostor);
  78037. //TODO is that needed?
  78038. impostor.forceUpdate();
  78039. }
  78040. return;
  78041. }
  78042. if (impostor.isBodyInitRequired()) {
  78043. var bodyConfig = {
  78044. name: impostor.uniqueId,
  78045. //Oimo must have mass, also for static objects.
  78046. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  78047. size: [],
  78048. type: [],
  78049. pos: [],
  78050. rot: [],
  78051. move: impostor.getParam("mass") !== 0,
  78052. //Supporting older versions of Oimo
  78053. world: this.world
  78054. };
  78055. var impostors = [impostor];
  78056. var addToArray = function (parent) {
  78057. if (!parent.getChildMeshes)
  78058. return;
  78059. parent.getChildMeshes().forEach(function (m) {
  78060. if (m.physicsImpostor) {
  78061. impostors.push(m.physicsImpostor);
  78062. //m.physicsImpostor._init();
  78063. }
  78064. });
  78065. };
  78066. addToArray(impostor.object);
  78067. var checkWithEpsilon_1 = function (value) {
  78068. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  78069. };
  78070. impostors.forEach(function (i) {
  78071. if (!impostor.object.rotationQuaternion) {
  78072. return;
  78073. }
  78074. //get the correct bounding box
  78075. var oldQuaternion = i.object.rotationQuaternion;
  78076. var rot = new _this.BJSOIMO.Euler().setFromQuaternion({
  78077. x: impostor.object.rotationQuaternion.x,
  78078. y: impostor.object.rotationQuaternion.y,
  78079. z: impostor.object.rotationQuaternion.z,
  78080. s: impostor.object.rotationQuaternion.w
  78081. });
  78082. var extendSize = i.getObjectExtendSize();
  78083. if (i === impostor) {
  78084. var center = impostor.getObjectCenter();
  78085. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  78086. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  78087. //Can also use Array.prototype.push.apply
  78088. bodyConfig.pos.push(center.x);
  78089. bodyConfig.pos.push(center.y);
  78090. bodyConfig.pos.push(center.z);
  78091. //tmp solution
  78092. bodyConfig.rot.push(rot.x / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  78093. bodyConfig.rot.push(rot.y / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  78094. bodyConfig.rot.push(rot.z / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  78095. }
  78096. else {
  78097. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  78098. bodyConfig.pos.push(localPosition.x);
  78099. bodyConfig.pos.push(localPosition.y);
  78100. bodyConfig.pos.push(localPosition.z);
  78101. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  78102. bodyConfig.rot.push(0);
  78103. bodyConfig.rot.push(0);
  78104. bodyConfig.rot.push(0);
  78105. }
  78106. // register mesh
  78107. switch (i.type) {
  78108. case BABYLON.PhysicsImpostor.ParticleImpostor:
  78109. BABYLON.Tools.Warn("No Particle support in this.BJSOIMO.js. using SphereImpostor instead");
  78110. case BABYLON.PhysicsImpostor.SphereImpostor:
  78111. var radiusX = extendSize.x;
  78112. var radiusY = extendSize.y;
  78113. var radiusZ = extendSize.z;
  78114. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  78115. bodyConfig.type.push('sphere');
  78116. //due to the way oimo works with compounds, add 3 times
  78117. bodyConfig.size.push(size);
  78118. bodyConfig.size.push(size);
  78119. bodyConfig.size.push(size);
  78120. break;
  78121. case BABYLON.PhysicsImpostor.CylinderImpostor:
  78122. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  78123. var sizeY = checkWithEpsilon_1(extendSize.y);
  78124. bodyConfig.type.push('cylinder');
  78125. bodyConfig.size.push(sizeX);
  78126. bodyConfig.size.push(sizeY);
  78127. //due to the way oimo works with compounds, add one more value.
  78128. bodyConfig.size.push(sizeY);
  78129. break;
  78130. case BABYLON.PhysicsImpostor.PlaneImpostor:
  78131. case BABYLON.PhysicsImpostor.BoxImpostor:
  78132. default:
  78133. var sizeX = checkWithEpsilon_1(extendSize.x);
  78134. var sizeY = checkWithEpsilon_1(extendSize.y);
  78135. var sizeZ = checkWithEpsilon_1(extendSize.z);
  78136. bodyConfig.type.push('box');
  78137. bodyConfig.size.push(sizeX);
  78138. bodyConfig.size.push(sizeY);
  78139. bodyConfig.size.push(sizeZ);
  78140. break;
  78141. }
  78142. //actually not needed, but hey...
  78143. i.object.rotationQuaternion = oldQuaternion;
  78144. });
  78145. impostor.physicsBody = new this.BJSOIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  78146. }
  78147. else {
  78148. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  78149. }
  78150. impostor.setDeltaPosition(this._tmpPositionVector);
  78151. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  78152. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  78153. };
  78154. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  78155. //impostor.physicsBody.dispose();
  78156. //Same as : (older oimo versions)
  78157. this.world.removeRigidBody(impostor.physicsBody);
  78158. };
  78159. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  78160. var mainBody = impostorJoint.mainImpostor.physicsBody;
  78161. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  78162. if (!mainBody || !connectedBody) {
  78163. return;
  78164. }
  78165. var jointData = impostorJoint.joint.jointData;
  78166. var options = jointData.nativeParams || {};
  78167. var type;
  78168. var nativeJointData = {
  78169. body1: mainBody,
  78170. body2: connectedBody,
  78171. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  78172. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  78173. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  78174. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  78175. min: options.min,
  78176. max: options.max,
  78177. collision: options.collision || jointData.collision,
  78178. spring: options.spring,
  78179. //supporting older version of Oimo
  78180. world: this.world
  78181. };
  78182. switch (impostorJoint.joint.type) {
  78183. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  78184. type = "jointBall";
  78185. break;
  78186. case BABYLON.PhysicsJoint.SpringJoint:
  78187. BABYLON.Tools.Warn("this.BJSOIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  78188. var springData = jointData;
  78189. nativeJointData.min = springData.length || nativeJointData.min;
  78190. //Max should also be set, just make sure it is at least min
  78191. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  78192. case BABYLON.PhysicsJoint.DistanceJoint:
  78193. type = "jointDistance";
  78194. nativeJointData.max = jointData.maxDistance;
  78195. break;
  78196. case BABYLON.PhysicsJoint.PrismaticJoint:
  78197. type = "jointPrisme";
  78198. break;
  78199. case BABYLON.PhysicsJoint.SliderJoint:
  78200. type = "jointSlide";
  78201. break;
  78202. case BABYLON.PhysicsJoint.WheelJoint:
  78203. type = "jointWheel";
  78204. break;
  78205. case BABYLON.PhysicsJoint.HingeJoint:
  78206. default:
  78207. type = "jointHinge";
  78208. break;
  78209. }
  78210. nativeJointData.type = type;
  78211. impostorJoint.joint.physicsJoint = new this.BJSOIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  78212. };
  78213. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  78214. //Bug in Oimo prevents us from disposing a joint in the playground
  78215. //joint.joint.physicsJoint.dispose();
  78216. //So we will bruteforce it!
  78217. try {
  78218. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  78219. }
  78220. catch (e) {
  78221. BABYLON.Tools.Warn(e);
  78222. }
  78223. };
  78224. OimoJSPlugin.prototype.isSupported = function () {
  78225. return this.BJSOIMO !== undefined;
  78226. };
  78227. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  78228. if (!impostor.physicsBody.sleeping) {
  78229. //TODO check that
  78230. if (impostor.physicsBody.shapes.next) {
  78231. var parentShape = this._getLastShape(impostor.physicsBody);
  78232. impostor.object.position.x = parentShape.position.x * this.BJSOIMO.WORLD_SCALE;
  78233. impostor.object.position.y = parentShape.position.y * this.BJSOIMO.WORLD_SCALE;
  78234. impostor.object.position.z = parentShape.position.z * this.BJSOIMO.WORLD_SCALE;
  78235. }
  78236. else {
  78237. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  78238. }
  78239. if (impostor.object.rotationQuaternion) {
  78240. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  78241. impostor.object.rotationQuaternion.normalize();
  78242. }
  78243. }
  78244. };
  78245. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  78246. var body = impostor.physicsBody;
  78247. body.position.init(newPosition.x * this.BJSOIMO.INV_SCALE, newPosition.y * this.BJSOIMO.INV_SCALE, newPosition.z * this.BJSOIMO.INV_SCALE);
  78248. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  78249. body.syncShapes();
  78250. body.awake();
  78251. };
  78252. OimoJSPlugin.prototype._getLastShape = function (body) {
  78253. var lastShape = body.shapes;
  78254. while (lastShape.next) {
  78255. lastShape = lastShape.next;
  78256. }
  78257. return lastShape;
  78258. };
  78259. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  78260. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  78261. };
  78262. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  78263. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  78264. };
  78265. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  78266. var v = impostor.physicsBody.linearVelocity;
  78267. if (!v) {
  78268. return null;
  78269. }
  78270. return new BABYLON.Vector3(v.x, v.y, v.z);
  78271. };
  78272. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  78273. var v = impostor.physicsBody.angularVelocity;
  78274. if (!v) {
  78275. return null;
  78276. }
  78277. return new BABYLON.Vector3(v.x, v.y, v.z);
  78278. };
  78279. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  78280. var staticBody = mass === 0;
  78281. //this will actually set the body's density and not its mass.
  78282. //But this is how oimo treats the mass variable.
  78283. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  78284. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  78285. };
  78286. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  78287. return impostor.physicsBody.shapes.density;
  78288. };
  78289. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  78290. return impostor.physicsBody.shapes.friction;
  78291. };
  78292. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  78293. impostor.physicsBody.shapes.friction = friction;
  78294. };
  78295. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  78296. return impostor.physicsBody.shapes.restitution;
  78297. };
  78298. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  78299. impostor.physicsBody.shapes.restitution = restitution;
  78300. };
  78301. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  78302. impostor.physicsBody.sleep();
  78303. };
  78304. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  78305. impostor.physicsBody.awake();
  78306. };
  78307. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  78308. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  78309. if (minDistance !== void 0) {
  78310. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  78311. }
  78312. };
  78313. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  78314. //TODO separate rotational and transational motors.
  78315. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  78316. if (motor) {
  78317. motor.setMotor(speed, maxForce);
  78318. }
  78319. };
  78320. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  78321. //TODO separate rotational and transational motors.
  78322. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  78323. if (motor) {
  78324. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  78325. }
  78326. };
  78327. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  78328. var body = impostor.physicsBody;
  78329. mesh.position.x = body.position.x;
  78330. mesh.position.y = body.position.y;
  78331. mesh.position.z = body.position.z;
  78332. if (mesh.rotationQuaternion) {
  78333. mesh.rotationQuaternion.x = body.orientation.x;
  78334. mesh.rotationQuaternion.y = body.orientation.y;
  78335. mesh.rotationQuaternion.z = body.orientation.z;
  78336. mesh.rotationQuaternion.w = body.orientation.s;
  78337. }
  78338. };
  78339. OimoJSPlugin.prototype.getRadius = function (impostor) {
  78340. return impostor.physicsBody.shapes.radius;
  78341. };
  78342. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  78343. var shape = impostor.physicsBody.shapes;
  78344. result.x = shape.halfWidth * 2;
  78345. result.y = shape.halfHeight * 2;
  78346. result.z = shape.halfDepth * 2;
  78347. };
  78348. OimoJSPlugin.prototype.dispose = function () {
  78349. this.world.clear();
  78350. };
  78351. return OimoJSPlugin;
  78352. }());
  78353. BABYLON.OimoJSPlugin = OimoJSPlugin;
  78354. })(BABYLON || (BABYLON = {}));
  78355. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  78356. var BABYLON;
  78357. (function (BABYLON) {
  78358. /*
  78359. * Based on jsTGALoader - Javascript loader for TGA file
  78360. * By Vincent Thibault
  78361. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  78362. */
  78363. var TGATools = /** @class */ (function () {
  78364. function TGATools() {
  78365. }
  78366. TGATools.GetTGAHeader = function (data) {
  78367. var offset = 0;
  78368. var header = {
  78369. id_length: data[offset++],
  78370. colormap_type: data[offset++],
  78371. image_type: data[offset++],
  78372. colormap_index: data[offset++] | data[offset++] << 8,
  78373. colormap_length: data[offset++] | data[offset++] << 8,
  78374. colormap_size: data[offset++],
  78375. origin: [
  78376. data[offset++] | data[offset++] << 8,
  78377. data[offset++] | data[offset++] << 8
  78378. ],
  78379. width: data[offset++] | data[offset++] << 8,
  78380. height: data[offset++] | data[offset++] << 8,
  78381. pixel_size: data[offset++],
  78382. flags: data[offset++]
  78383. };
  78384. return header;
  78385. };
  78386. TGATools.UploadContent = function (gl, data) {
  78387. // Not enough data to contain header ?
  78388. if (data.length < 19) {
  78389. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  78390. return;
  78391. }
  78392. // Read Header
  78393. var offset = 18;
  78394. var header = TGATools.GetTGAHeader(data);
  78395. // Assume it's a valid Targa file.
  78396. if (header.id_length + offset > data.length) {
  78397. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  78398. return;
  78399. }
  78400. // Skip not needed data
  78401. offset += header.id_length;
  78402. var use_rle = false;
  78403. var use_pal = false;
  78404. var use_grey = false;
  78405. // Get some informations.
  78406. switch (header.image_type) {
  78407. case TGATools._TYPE_RLE_INDEXED:
  78408. use_rle = true;
  78409. case TGATools._TYPE_INDEXED:
  78410. use_pal = true;
  78411. break;
  78412. case TGATools._TYPE_RLE_RGB:
  78413. use_rle = true;
  78414. case TGATools._TYPE_RGB:
  78415. // use_rgb = true;
  78416. break;
  78417. case TGATools._TYPE_RLE_GREY:
  78418. use_rle = true;
  78419. case TGATools._TYPE_GREY:
  78420. use_grey = true;
  78421. break;
  78422. }
  78423. var pixel_data;
  78424. // var numAlphaBits = header.flags & 0xf;
  78425. var pixel_size = header.pixel_size >> 3;
  78426. var pixel_total = header.width * header.height * pixel_size;
  78427. // Read palettes
  78428. var palettes;
  78429. if (use_pal) {
  78430. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  78431. }
  78432. // Read LRE
  78433. if (use_rle) {
  78434. pixel_data = new Uint8Array(pixel_total);
  78435. var c, count, i;
  78436. var localOffset = 0;
  78437. var pixels = new Uint8Array(pixel_size);
  78438. while (offset < pixel_total && localOffset < pixel_total) {
  78439. c = data[offset++];
  78440. count = (c & 0x7f) + 1;
  78441. // RLE pixels
  78442. if (c & 0x80) {
  78443. // Bind pixel tmp array
  78444. for (i = 0; i < pixel_size; ++i) {
  78445. pixels[i] = data[offset++];
  78446. }
  78447. // Copy pixel array
  78448. for (i = 0; i < count; ++i) {
  78449. pixel_data.set(pixels, localOffset + i * pixel_size);
  78450. }
  78451. localOffset += pixel_size * count;
  78452. }
  78453. else {
  78454. count *= pixel_size;
  78455. for (i = 0; i < count; ++i) {
  78456. pixel_data[localOffset + i] = data[offset++];
  78457. }
  78458. localOffset += count;
  78459. }
  78460. }
  78461. }
  78462. else {
  78463. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  78464. }
  78465. // Load to texture
  78466. var x_start, y_start, x_step, y_step, y_end, x_end;
  78467. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  78468. default:
  78469. case TGATools._ORIGIN_UL:
  78470. x_start = 0;
  78471. x_step = 1;
  78472. x_end = header.width;
  78473. y_start = 0;
  78474. y_step = 1;
  78475. y_end = header.height;
  78476. break;
  78477. case TGATools._ORIGIN_BL:
  78478. x_start = 0;
  78479. x_step = 1;
  78480. x_end = header.width;
  78481. y_start = header.height - 1;
  78482. y_step = -1;
  78483. y_end = -1;
  78484. break;
  78485. case TGATools._ORIGIN_UR:
  78486. x_start = header.width - 1;
  78487. x_step = -1;
  78488. x_end = -1;
  78489. y_start = 0;
  78490. y_step = 1;
  78491. y_end = header.height;
  78492. break;
  78493. case TGATools._ORIGIN_BR:
  78494. x_start = header.width - 1;
  78495. x_step = -1;
  78496. x_end = -1;
  78497. y_start = header.height - 1;
  78498. y_step = -1;
  78499. y_end = -1;
  78500. break;
  78501. }
  78502. // Load the specify method
  78503. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  78504. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  78505. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  78506. };
  78507. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  78508. var image = pixel_data, colormap = palettes;
  78509. var width = header.width, height = header.height;
  78510. var color, i = 0, x, y;
  78511. var imageData = new Uint8Array(width * height * 4);
  78512. for (y = y_start; y !== y_end; y += y_step) {
  78513. for (x = x_start; x !== x_end; x += x_step, i++) {
  78514. color = image[i];
  78515. imageData[(x + width * y) * 4 + 3] = 255;
  78516. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  78517. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  78518. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  78519. }
  78520. }
  78521. return imageData;
  78522. };
  78523. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  78524. var image = pixel_data;
  78525. var width = header.width, height = header.height;
  78526. var color, i = 0, x, y;
  78527. var imageData = new Uint8Array(width * height * 4);
  78528. for (y = y_start; y !== y_end; y += y_step) {
  78529. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  78530. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  78531. var r = (((color & 0x7C00) >> 10) * 255) / 0x1F | 0;
  78532. var g = (((color & 0x03E0) >> 5) * 255) / 0x1F | 0;
  78533. var b = ((color & 0x001F) * 255) / 0x1F | 0;
  78534. imageData[(x + width * y) * 4 + 0] = r;
  78535. imageData[(x + width * y) * 4 + 1] = g;
  78536. imageData[(x + width * y) * 4 + 2] = b;
  78537. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  78538. }
  78539. }
  78540. return imageData;
  78541. };
  78542. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  78543. var image = pixel_data;
  78544. var width = header.width, height = header.height;
  78545. var i = 0, x, y;
  78546. var imageData = new Uint8Array(width * height * 4);
  78547. for (y = y_start; y !== y_end; y += y_step) {
  78548. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  78549. imageData[(x + width * y) * 4 + 3] = 255;
  78550. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  78551. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  78552. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  78553. }
  78554. }
  78555. return imageData;
  78556. };
  78557. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  78558. var image = pixel_data;
  78559. var width = header.width, height = header.height;
  78560. var i = 0, x, y;
  78561. var imageData = new Uint8Array(width * height * 4);
  78562. for (y = y_start; y !== y_end; y += y_step) {
  78563. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  78564. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  78565. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  78566. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  78567. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  78568. }
  78569. }
  78570. return imageData;
  78571. };
  78572. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  78573. var image = pixel_data;
  78574. var width = header.width, height = header.height;
  78575. var color, i = 0, x, y;
  78576. var imageData = new Uint8Array(width * height * 4);
  78577. for (y = y_start; y !== y_end; y += y_step) {
  78578. for (x = x_start; x !== x_end; x += x_step, i++) {
  78579. color = image[i];
  78580. imageData[(x + width * y) * 4 + 0] = color;
  78581. imageData[(x + width * y) * 4 + 1] = color;
  78582. imageData[(x + width * y) * 4 + 2] = color;
  78583. imageData[(x + width * y) * 4 + 3] = 255;
  78584. }
  78585. }
  78586. return imageData;
  78587. };
  78588. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  78589. var image = pixel_data;
  78590. var width = header.width, height = header.height;
  78591. var i = 0, x, y;
  78592. var imageData = new Uint8Array(width * height * 4);
  78593. for (y = y_start; y !== y_end; y += y_step) {
  78594. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  78595. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  78596. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  78597. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  78598. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  78599. }
  78600. }
  78601. return imageData;
  78602. };
  78603. //private static _TYPE_NO_DATA = 0;
  78604. TGATools._TYPE_INDEXED = 1;
  78605. TGATools._TYPE_RGB = 2;
  78606. TGATools._TYPE_GREY = 3;
  78607. TGATools._TYPE_RLE_INDEXED = 9;
  78608. TGATools._TYPE_RLE_RGB = 10;
  78609. TGATools._TYPE_RLE_GREY = 11;
  78610. TGATools._ORIGIN_MASK = 0x30;
  78611. TGATools._ORIGIN_SHIFT = 0x04;
  78612. TGATools._ORIGIN_BL = 0x00;
  78613. TGATools._ORIGIN_BR = 0x01;
  78614. TGATools._ORIGIN_UL = 0x02;
  78615. TGATools._ORIGIN_UR = 0x03;
  78616. return TGATools;
  78617. }());
  78618. BABYLON.TGATools = TGATools;
  78619. })(BABYLON || (BABYLON = {}));
  78620. //# sourceMappingURL=babylon.tga.js.map
  78621. var BABYLON;
  78622. (function (BABYLON) {
  78623. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  78624. // All values and structures referenced from:
  78625. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  78626. var DDS_MAGIC = 0x20534444;
  78627. var
  78628. //DDSD_CAPS = 0x1,
  78629. //DDSD_HEIGHT = 0x2,
  78630. //DDSD_WIDTH = 0x4,
  78631. //DDSD_PITCH = 0x8,
  78632. //DDSD_PIXELFORMAT = 0x1000,
  78633. DDSD_MIPMAPCOUNT = 0x20000;
  78634. //DDSD_LINEARSIZE = 0x80000,
  78635. //DDSD_DEPTH = 0x800000;
  78636. // var DDSCAPS_COMPLEX = 0x8,
  78637. // DDSCAPS_MIPMAP = 0x400000,
  78638. // DDSCAPS_TEXTURE = 0x1000;
  78639. var DDSCAPS2_CUBEMAP = 0x200;
  78640. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  78641. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  78642. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  78643. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  78644. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  78645. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  78646. // DDSCAPS2_VOLUME = 0x200000;
  78647. var
  78648. //DDPF_ALPHAPIXELS = 0x1,
  78649. //DDPF_ALPHA = 0x2,
  78650. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  78651. //DDPF_YUV = 0x200,
  78652. DDPF_LUMINANCE = 0x20000;
  78653. function FourCCToInt32(value) {
  78654. return value.charCodeAt(0) +
  78655. (value.charCodeAt(1) << 8) +
  78656. (value.charCodeAt(2) << 16) +
  78657. (value.charCodeAt(3) << 24);
  78658. }
  78659. function Int32ToFourCC(value) {
  78660. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  78661. }
  78662. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  78663. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  78664. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  78665. var FOURCC_DX10 = FourCCToInt32("DX10");
  78666. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  78667. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  78668. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  78669. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  78670. var headerLengthInt = 31; // The header length in 32 bit ints
  78671. // Offsets into the header array
  78672. var off_magic = 0;
  78673. var off_size = 1;
  78674. var off_flags = 2;
  78675. var off_height = 3;
  78676. var off_width = 4;
  78677. var off_mipmapCount = 7;
  78678. var off_pfFlags = 20;
  78679. var off_pfFourCC = 21;
  78680. var off_RGBbpp = 22;
  78681. var off_RMask = 23;
  78682. var off_GMask = 24;
  78683. var off_BMask = 25;
  78684. var off_AMask = 26;
  78685. // var off_caps1 = 27;
  78686. var off_caps2 = 28;
  78687. // var off_caps3 = 29;
  78688. // var off_caps4 = 30;
  78689. var off_dxgiFormat = 32;
  78690. ;
  78691. var DDSTools = /** @class */ (function () {
  78692. function DDSTools() {
  78693. }
  78694. DDSTools.GetDDSInfo = function (arrayBuffer) {
  78695. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  78696. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  78697. var mipmapCount = 1;
  78698. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  78699. mipmapCount = Math.max(1, header[off_mipmapCount]);
  78700. }
  78701. var fourCC = header[off_pfFourCC];
  78702. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  78703. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  78704. switch (fourCC) {
  78705. case FOURCC_D3DFMT_R16G16B16A16F:
  78706. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  78707. break;
  78708. case FOURCC_D3DFMT_R32G32B32A32F:
  78709. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  78710. break;
  78711. case FOURCC_DX10:
  78712. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  78713. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  78714. break;
  78715. }
  78716. }
  78717. return {
  78718. width: header[off_width],
  78719. height: header[off_height],
  78720. mipmapCount: mipmapCount,
  78721. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  78722. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  78723. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  78724. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  78725. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  78726. dxgiFormat: dxgiFormat,
  78727. textureType: textureType
  78728. };
  78729. };
  78730. DDSTools._ToHalfFloat = function (value) {
  78731. if (!DDSTools._FloatView) {
  78732. DDSTools._FloatView = new Float32Array(1);
  78733. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  78734. }
  78735. DDSTools._FloatView[0] = value;
  78736. var x = DDSTools._Int32View[0];
  78737. var bits = (x >> 16) & 0x8000; /* Get the sign */
  78738. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  78739. var e = (x >> 23) & 0xff; /* Using int is faster here */
  78740. /* If zero, or denormal, or exponent underflows too much for a denormal
  78741. * half, return signed zero. */
  78742. if (e < 103) {
  78743. return bits;
  78744. }
  78745. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  78746. if (e > 142) {
  78747. bits |= 0x7c00;
  78748. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  78749. * not Inf, so make sure we set one mantissa bit too. */
  78750. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  78751. return bits;
  78752. }
  78753. /* If exponent underflows but not too much, return a denormal */
  78754. if (e < 113) {
  78755. m |= 0x0800;
  78756. /* Extra rounding may overflow and set mantissa to 0 and exponent
  78757. * to 1, which is OK. */
  78758. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  78759. return bits;
  78760. }
  78761. bits |= ((e - 112) << 10) | (m >> 1);
  78762. bits += m & 1;
  78763. return bits;
  78764. };
  78765. DDSTools._FromHalfFloat = function (value) {
  78766. var s = (value & 0x8000) >> 15;
  78767. var e = (value & 0x7C00) >> 10;
  78768. var f = value & 0x03FF;
  78769. if (e === 0) {
  78770. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  78771. }
  78772. else if (e == 0x1F) {
  78773. return f ? NaN : ((s ? -1 : 1) * Infinity);
  78774. }
  78775. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  78776. };
  78777. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  78778. var destArray = new Float32Array(dataLength);
  78779. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  78780. var index = 0;
  78781. for (var y = 0; y < height; y++) {
  78782. for (var x = 0; x < width; x++) {
  78783. var srcPos = (x + y * width) * 4;
  78784. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  78785. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  78786. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  78787. if (DDSTools.StoreLODInAlphaChannel) {
  78788. destArray[index + 3] = lod;
  78789. }
  78790. else {
  78791. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  78792. }
  78793. index += 4;
  78794. }
  78795. }
  78796. return destArray;
  78797. };
  78798. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  78799. if (DDSTools.StoreLODInAlphaChannel) {
  78800. var destArray = new Uint16Array(dataLength);
  78801. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  78802. var index = 0;
  78803. for (var y = 0; y < height; y++) {
  78804. for (var x = 0; x < width; x++) {
  78805. var srcPos = (x + y * width) * 4;
  78806. destArray[index] = srcData[srcPos];
  78807. destArray[index + 1] = srcData[srcPos + 1];
  78808. destArray[index + 2] = srcData[srcPos + 2];
  78809. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  78810. index += 4;
  78811. }
  78812. }
  78813. return destArray;
  78814. }
  78815. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  78816. };
  78817. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  78818. if (DDSTools.StoreLODInAlphaChannel) {
  78819. var destArray = new Float32Array(dataLength);
  78820. var srcData = new Float32Array(arrayBuffer, dataOffset);
  78821. var index = 0;
  78822. for (var y = 0; y < height; y++) {
  78823. for (var x = 0; x < width; x++) {
  78824. var srcPos = (x + y * width) * 4;
  78825. destArray[index] = srcData[srcPos];
  78826. destArray[index + 1] = srcData[srcPos + 1];
  78827. destArray[index + 2] = srcData[srcPos + 2];
  78828. destArray[index + 3] = lod;
  78829. index += 4;
  78830. }
  78831. }
  78832. return destArray;
  78833. }
  78834. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  78835. };
  78836. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  78837. var destArray = new Uint8Array(dataLength);
  78838. var srcData = new Float32Array(arrayBuffer, dataOffset);
  78839. var index = 0;
  78840. for (var y = 0; y < height; y++) {
  78841. for (var x = 0; x < width; x++) {
  78842. var srcPos = (x + y * width) * 4;
  78843. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  78844. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  78845. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  78846. if (DDSTools.StoreLODInAlphaChannel) {
  78847. destArray[index + 3] = lod;
  78848. }
  78849. else {
  78850. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  78851. }
  78852. index += 4;
  78853. }
  78854. }
  78855. return destArray;
  78856. };
  78857. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  78858. var destArray = new Uint8Array(dataLength);
  78859. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  78860. var index = 0;
  78861. for (var y = 0; y < height; y++) {
  78862. for (var x = 0; x < width; x++) {
  78863. var srcPos = (x + y * width) * 4;
  78864. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  78865. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  78866. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  78867. if (DDSTools.StoreLODInAlphaChannel) {
  78868. destArray[index + 3] = lod;
  78869. }
  78870. else {
  78871. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  78872. }
  78873. index += 4;
  78874. }
  78875. }
  78876. return destArray;
  78877. };
  78878. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  78879. var byteArray = new Uint8Array(dataLength);
  78880. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  78881. var index = 0;
  78882. for (var y = 0; y < height; y++) {
  78883. for (var x = 0; x < width; x++) {
  78884. var srcPos = (x + y * width) * 4;
  78885. byteArray[index] = srcData[srcPos + rOffset];
  78886. byteArray[index + 1] = srcData[srcPos + gOffset];
  78887. byteArray[index + 2] = srcData[srcPos + bOffset];
  78888. byteArray[index + 3] = srcData[srcPos + aOffset];
  78889. index += 4;
  78890. }
  78891. }
  78892. return byteArray;
  78893. };
  78894. DDSTools._ExtractLongWordOrder = function (value) {
  78895. if (value === 0 || value === 255 || value === -16777216) {
  78896. return 0;
  78897. }
  78898. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  78899. };
  78900. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  78901. var byteArray = new Uint8Array(dataLength);
  78902. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  78903. var index = 0;
  78904. for (var y = 0; y < height; y++) {
  78905. for (var x = 0; x < width; x++) {
  78906. var srcPos = (x + y * width) * 3;
  78907. byteArray[index] = srcData[srcPos + rOffset];
  78908. byteArray[index + 1] = srcData[srcPos + gOffset];
  78909. byteArray[index + 2] = srcData[srcPos + bOffset];
  78910. index += 3;
  78911. }
  78912. }
  78913. return byteArray;
  78914. };
  78915. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  78916. var byteArray = new Uint8Array(dataLength);
  78917. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  78918. var index = 0;
  78919. for (var y = 0; y < height; y++) {
  78920. for (var x = 0; x < width; x++) {
  78921. var srcPos = (x + y * width);
  78922. byteArray[index] = srcData[srcPos];
  78923. index++;
  78924. }
  78925. }
  78926. return byteArray;
  78927. };
  78928. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  78929. if (lodIndex === void 0) { lodIndex = -1; }
  78930. var ext = engine.getCaps().s3tc;
  78931. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  78932. var fourCC, width, height, dataLength = 0, dataOffset;
  78933. var byteArray, mipmapCount, mip;
  78934. var internalFormat = 0;
  78935. var format = 0;
  78936. var blockBytes = 1;
  78937. if (header[off_magic] !== DDS_MAGIC) {
  78938. BABYLON.Tools.Error("Invalid magic number in DDS header");
  78939. return;
  78940. }
  78941. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  78942. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  78943. return;
  78944. }
  78945. if (info.isCompressed && !ext) {
  78946. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  78947. return;
  78948. }
  78949. var bpp = header[off_RGBbpp];
  78950. dataOffset = header[off_size] + 4;
  78951. var computeFormats = false;
  78952. if (info.isFourCC) {
  78953. fourCC = header[off_pfFourCC];
  78954. switch (fourCC) {
  78955. case FOURCC_DXT1:
  78956. blockBytes = 8;
  78957. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  78958. break;
  78959. case FOURCC_DXT3:
  78960. blockBytes = 16;
  78961. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  78962. break;
  78963. case FOURCC_DXT5:
  78964. blockBytes = 16;
  78965. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  78966. break;
  78967. case FOURCC_D3DFMT_R16G16B16A16F:
  78968. computeFormats = true;
  78969. break;
  78970. case FOURCC_D3DFMT_R32G32B32A32F:
  78971. computeFormats = true;
  78972. break;
  78973. case FOURCC_DX10:
  78974. // There is an additionnal header so dataOffset need to be changed
  78975. dataOffset += 5 * 4; // 5 uints
  78976. var supported = false;
  78977. switch (info.dxgiFormat) {
  78978. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  78979. computeFormats = true;
  78980. supported = true;
  78981. break;
  78982. case DXGI_FORMAT_B8G8R8X8_UNORM:
  78983. info.isRGB = true;
  78984. info.isFourCC = false;
  78985. bpp = 32;
  78986. supported = true;
  78987. break;
  78988. }
  78989. if (supported) {
  78990. break;
  78991. }
  78992. default:
  78993. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  78994. return;
  78995. }
  78996. }
  78997. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  78998. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  78999. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  79000. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  79001. if (computeFormats) {
  79002. format = engine._getWebGLTextureType(info.textureType);
  79003. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  79004. }
  79005. mipmapCount = 1;
  79006. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  79007. mipmapCount = Math.max(1, header[off_mipmapCount]);
  79008. }
  79009. for (var face = 0; face < faces; face++) {
  79010. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face + (currentFace ? currentFace : 0));
  79011. width = header[off_width];
  79012. height = header[off_height];
  79013. for (mip = 0; mip < mipmapCount; ++mip) {
  79014. if (lodIndex === -1 || lodIndex === mip) {
  79015. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  79016. var i = (lodIndex === -1) ? mip : 0;
  79017. if (!info.isCompressed && info.isFourCC) {
  79018. dataLength = width * height * 4;
  79019. var floatArray = null;
  79020. if (engine.badOS || engine.badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) {
  79021. if (bpp === 128) {
  79022. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  79023. }
  79024. else if (bpp === 64) {
  79025. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  79026. }
  79027. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  79028. format = engine._getWebGLTextureType(info.textureType);
  79029. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  79030. }
  79031. else {
  79032. if (bpp === 128) {
  79033. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  79034. }
  79035. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  79036. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  79037. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  79038. format = engine._getWebGLTextureType(info.textureType);
  79039. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  79040. }
  79041. else {
  79042. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  79043. }
  79044. }
  79045. if (floatArray) {
  79046. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, floatArray);
  79047. }
  79048. }
  79049. else if (info.isRGB) {
  79050. if (bpp === 24) {
  79051. dataLength = width * height * 3;
  79052. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  79053. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  79054. }
  79055. else {
  79056. dataLength = width * height * 4;
  79057. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  79058. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  79059. }
  79060. }
  79061. else if (info.isLuminance) {
  79062. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  79063. var unpaddedRowSize = width;
  79064. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  79065. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  79066. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  79067. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  79068. }
  79069. else {
  79070. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  79071. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  79072. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  79073. }
  79074. }
  79075. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  79076. width *= 0.5;
  79077. height *= 0.5;
  79078. width = Math.max(1.0, width);
  79079. height = Math.max(1.0, height);
  79080. }
  79081. if (currentFace !== undefined) {
  79082. // Loading a single face
  79083. break;
  79084. }
  79085. }
  79086. };
  79087. DDSTools.StoreLODInAlphaChannel = false;
  79088. return DDSTools;
  79089. }());
  79090. BABYLON.DDSTools = DDSTools;
  79091. })(BABYLON || (BABYLON = {}));
  79092. //# sourceMappingURL=babylon.dds.js.map
  79093. var BABYLON;
  79094. (function (BABYLON) {
  79095. /**
  79096. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  79097. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  79098. */
  79099. var KhronosTextureContainer = /** @class */ (function () {
  79100. /**
  79101. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  79102. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  79103. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  79104. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  79105. */
  79106. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  79107. this.arrayBuffer = arrayBuffer;
  79108. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  79109. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  79110. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  79111. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  79112. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  79113. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  79114. BABYLON.Tools.Error("texture missing KTX identifier");
  79115. return;
  79116. }
  79117. // load the reset of the header in native 32 bit int
  79118. var header = new Int32Array(this.arrayBuffer, 12, 13);
  79119. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  79120. var oppositeEndianess = header[0] === 0x01020304;
  79121. // read all the header elements in order they exist in the file, without modification (sans endainness)
  79122. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  79123. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  79124. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  79125. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  79126. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  79127. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  79128. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  79129. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  79130. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  79131. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  79132. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  79133. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  79134. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  79135. if (this.glType !== 0) {
  79136. BABYLON.Tools.Error("only compressed formats currently supported");
  79137. return;
  79138. }
  79139. else {
  79140. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  79141. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  79142. }
  79143. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  79144. BABYLON.Tools.Error("only 2D textures currently supported");
  79145. return;
  79146. }
  79147. if (this.numberOfArrayElements !== 0) {
  79148. BABYLON.Tools.Error("texture arrays not currently supported");
  79149. return;
  79150. }
  79151. if (this.numberOfFaces !== facesExpected) {
  79152. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  79153. return;
  79154. }
  79155. // we now have a completely validated file, so could use existence of loadType as success
  79156. // would need to make this more elaborate & adjust checks above to support more than one load type
  79157. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  79158. }
  79159. // not as fast hardware based, but will probably never need to use
  79160. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  79161. return ((val & 0xFF) << 24)
  79162. | ((val & 0xFF00) << 8)
  79163. | ((val >> 8) & 0xFF00)
  79164. | ((val >> 24) & 0xFF);
  79165. };
  79166. /**
  79167. * It is assumed that the texture has already been created & is currently bound
  79168. */
  79169. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  79170. switch (this.loadType) {
  79171. case KhronosTextureContainer.COMPRESSED_2D:
  79172. this._upload2DCompressedLevels(gl, loadMipmaps);
  79173. break;
  79174. case KhronosTextureContainer.TEX_2D:
  79175. case KhronosTextureContainer.COMPRESSED_3D:
  79176. case KhronosTextureContainer.TEX_3D:
  79177. }
  79178. };
  79179. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  79180. // initialize width & height for level 1
  79181. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  79182. var width = this.pixelWidth;
  79183. var height = this.pixelHeight;
  79184. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  79185. for (var level = 0; level < mipmapCount; level++) {
  79186. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  79187. for (var face = 0; face < this.numberOfFaces; face++) {
  79188. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  79189. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  79190. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  79191. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  79192. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  79193. }
  79194. width = Math.max(1.0, width * 0.5);
  79195. height = Math.max(1.0, height * 0.5);
  79196. }
  79197. };
  79198. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  79199. // load types
  79200. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  79201. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  79202. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  79203. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  79204. return KhronosTextureContainer;
  79205. }());
  79206. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  79207. })(BABYLON || (BABYLON = {}));
  79208. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  79209. var BABYLON;
  79210. (function (BABYLON) {
  79211. var Debug = /** @class */ (function () {
  79212. function Debug() {
  79213. }
  79214. Debug.AxesViewer = /** @class */ (function () {
  79215. function AxesViewer(scene, scaleLines) {
  79216. if (scaleLines === void 0) { scaleLines = 1; }
  79217. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  79218. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  79219. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  79220. this.scaleLines = 1;
  79221. this.scaleLines = scaleLines;
  79222. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  79223. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  79224. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  79225. this._xmesh.renderingGroupId = 2;
  79226. this._ymesh.renderingGroupId = 2;
  79227. this._zmesh.renderingGroupId = 2;
  79228. this._xmesh.material.checkReadyOnlyOnce = true;
  79229. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  79230. this._ymesh.material.checkReadyOnlyOnce = true;
  79231. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  79232. this._zmesh.material.checkReadyOnlyOnce = true;
  79233. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  79234. this.scene = scene;
  79235. }
  79236. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  79237. var scaleLines = this.scaleLines;
  79238. if (this._xmesh) {
  79239. this._xmesh.position.copyFrom(position);
  79240. }
  79241. if (this._ymesh) {
  79242. this._ymesh.position.copyFrom(position);
  79243. }
  79244. if (this._zmesh) {
  79245. this._zmesh.position.copyFrom(position);
  79246. }
  79247. var point2 = this._xline[1];
  79248. point2.x = xaxis.x * scaleLines;
  79249. point2.y = xaxis.y * scaleLines;
  79250. point2.z = xaxis.z * scaleLines;
  79251. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  79252. point2 = this._yline[1];
  79253. point2.x = yaxis.x * scaleLines;
  79254. point2.y = yaxis.y * scaleLines;
  79255. point2.z = yaxis.z * scaleLines;
  79256. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  79257. point2 = this._zline[1];
  79258. point2.x = zaxis.x * scaleLines;
  79259. point2.y = zaxis.y * scaleLines;
  79260. point2.z = zaxis.z * scaleLines;
  79261. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  79262. };
  79263. AxesViewer.prototype.dispose = function () {
  79264. if (this._xmesh) {
  79265. this._xmesh.dispose();
  79266. }
  79267. if (this._ymesh) {
  79268. this._ymesh.dispose();
  79269. }
  79270. if (this._zmesh) {
  79271. this._zmesh.dispose();
  79272. }
  79273. this._xmesh = null;
  79274. this._ymesh = null;
  79275. this._zmesh = null;
  79276. this.scene = null;
  79277. };
  79278. return AxesViewer;
  79279. }());
  79280. Debug.BoneAxesViewer = /** @class */ (function (_super) {
  79281. __extends(BoneAxesViewer, _super);
  79282. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  79283. if (scaleLines === void 0) { scaleLines = 1; }
  79284. var _this = _super.call(this, scene, scaleLines) || this;
  79285. _this.pos = BABYLON.Vector3.Zero();
  79286. _this.xaxis = BABYLON.Vector3.Zero();
  79287. _this.yaxis = BABYLON.Vector3.Zero();
  79288. _this.zaxis = BABYLON.Vector3.Zero();
  79289. _this.mesh = mesh;
  79290. _this.bone = bone;
  79291. return _this;
  79292. }
  79293. BoneAxesViewer.prototype.update = function () {
  79294. if (!this.mesh || !this.bone) {
  79295. return;
  79296. }
  79297. var bone = this.bone;
  79298. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  79299. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  79300. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  79301. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  79302. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  79303. };
  79304. BoneAxesViewer.prototype.dispose = function () {
  79305. if (this.mesh) {
  79306. this.mesh = null;
  79307. this.bone = null;
  79308. _super.prototype.dispose.call(this);
  79309. }
  79310. };
  79311. return BoneAxesViewer;
  79312. }(Debug.AxesViewer));
  79313. Debug.PhysicsViewer = /** @class */ (function () {
  79314. function PhysicsViewer(scene) {
  79315. this._impostors = [];
  79316. this._meshes = [];
  79317. this._numMeshes = 0;
  79318. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  79319. var physicEngine = this._scene.getPhysicsEngine();
  79320. if (physicEngine) {
  79321. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  79322. }
  79323. }
  79324. PhysicsViewer.prototype._updateDebugMeshes = function () {
  79325. var plugin = this._physicsEnginePlugin;
  79326. for (var i = 0; i < this._numMeshes; i++) {
  79327. var impostor = this._impostors[i];
  79328. if (!impostor) {
  79329. continue;
  79330. }
  79331. if (impostor.isDisposed) {
  79332. this.hideImpostor(this._impostors[i--]);
  79333. }
  79334. else {
  79335. var mesh = this._meshes[i];
  79336. if (mesh && plugin) {
  79337. plugin.syncMeshWithImpostor(mesh, impostor);
  79338. }
  79339. }
  79340. }
  79341. };
  79342. PhysicsViewer.prototype.showImpostor = function (impostor) {
  79343. if (!this._scene) {
  79344. return;
  79345. }
  79346. for (var i = 0; i < this._numMeshes; i++) {
  79347. if (this._impostors[i] == impostor) {
  79348. return;
  79349. }
  79350. }
  79351. var debugMesh = this._getDebugMesh(impostor, this._scene);
  79352. if (debugMesh) {
  79353. this._impostors[this._numMeshes] = impostor;
  79354. this._meshes[this._numMeshes] = debugMesh;
  79355. if (this._numMeshes === 0) {
  79356. this._renderFunction = this._updateDebugMeshes.bind(this);
  79357. this._scene.registerBeforeRender(this._renderFunction);
  79358. }
  79359. this._numMeshes++;
  79360. }
  79361. };
  79362. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  79363. if (!impostor || !this._scene) {
  79364. return;
  79365. }
  79366. var removed = false;
  79367. for (var i = 0; i < this._numMeshes; i++) {
  79368. if (this._impostors[i] == impostor) {
  79369. var mesh = this._meshes[i];
  79370. if (!mesh) {
  79371. continue;
  79372. }
  79373. this._scene.removeMesh(mesh);
  79374. mesh.dispose();
  79375. this._numMeshes--;
  79376. if (this._numMeshes > 0) {
  79377. this._meshes[i] = this._meshes[this._numMeshes];
  79378. this._impostors[i] = this._impostors[this._numMeshes];
  79379. this._meshes[this._numMeshes] = null;
  79380. this._impostors[this._numMeshes] = null;
  79381. }
  79382. else {
  79383. this._meshes[0] = null;
  79384. this._impostors[0] = null;
  79385. }
  79386. removed = true;
  79387. break;
  79388. }
  79389. }
  79390. if (removed && this._numMeshes === 0) {
  79391. this._scene.unregisterBeforeRender(this._renderFunction);
  79392. }
  79393. };
  79394. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  79395. if (!this._debugMaterial) {
  79396. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  79397. this._debugMaterial.wireframe = true;
  79398. }
  79399. return this._debugMaterial;
  79400. };
  79401. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  79402. if (!this._debugBoxMesh) {
  79403. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  79404. this._debugBoxMesh.renderingGroupId = 1;
  79405. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  79406. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  79407. scene.removeMesh(this._debugBoxMesh);
  79408. }
  79409. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  79410. };
  79411. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  79412. if (!this._debugSphereMesh) {
  79413. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  79414. this._debugSphereMesh.renderingGroupId = 1;
  79415. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  79416. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  79417. scene.removeMesh(this._debugSphereMesh);
  79418. }
  79419. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  79420. };
  79421. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  79422. var mesh = null;
  79423. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  79424. mesh = this._getDebugBoxMesh(scene);
  79425. impostor.getBoxSizeToRef(mesh.scaling);
  79426. }
  79427. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  79428. mesh = this._getDebugSphereMesh(scene);
  79429. var radius = impostor.getRadius();
  79430. mesh.scaling.x = radius * 2;
  79431. mesh.scaling.y = radius * 2;
  79432. mesh.scaling.z = radius * 2;
  79433. }
  79434. return mesh;
  79435. };
  79436. PhysicsViewer.prototype.dispose = function () {
  79437. for (var i = 0; i < this._numMeshes; i++) {
  79438. this.hideImpostor(this._impostors[i]);
  79439. }
  79440. if (this._debugBoxMesh) {
  79441. this._debugBoxMesh.dispose();
  79442. }
  79443. if (this._debugSphereMesh) {
  79444. this._debugSphereMesh.dispose();
  79445. }
  79446. if (this._debugMaterial) {
  79447. this._debugMaterial.dispose();
  79448. }
  79449. this._impostors.length = 0;
  79450. this._scene = null;
  79451. this._physicsEnginePlugin = null;
  79452. };
  79453. return PhysicsViewer;
  79454. }());
  79455. Debug.SkeletonViewer = /** @class */ (function () {
  79456. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  79457. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  79458. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  79459. this.skeleton = skeleton;
  79460. this.mesh = mesh;
  79461. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  79462. this.renderingGroupId = renderingGroupId;
  79463. this.color = BABYLON.Color3.White();
  79464. this._debugLines = new Array();
  79465. this._isEnabled = false;
  79466. this._scene = scene;
  79467. this.update();
  79468. this._renderFunction = this.update.bind(this);
  79469. }
  79470. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  79471. get: function () {
  79472. return this._isEnabled;
  79473. },
  79474. set: function (value) {
  79475. if (this._isEnabled === value) {
  79476. return;
  79477. }
  79478. this._isEnabled = value;
  79479. if (value) {
  79480. this._scene.registerBeforeRender(this._renderFunction);
  79481. }
  79482. else {
  79483. this._scene.unregisterBeforeRender(this._renderFunction);
  79484. }
  79485. },
  79486. enumerable: true,
  79487. configurable: true
  79488. });
  79489. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  79490. if (x === void 0) { x = 0; }
  79491. if (y === void 0) { y = 0; }
  79492. if (z === void 0) { z = 0; }
  79493. var tmat = BABYLON.Tmp.Matrix[0];
  79494. var parentBone = bone.getParent();
  79495. tmat.copyFrom(bone.getLocalMatrix());
  79496. if (x !== 0 || y !== 0 || z !== 0) {
  79497. var tmat2 = BABYLON.Tmp.Matrix[1];
  79498. BABYLON.Matrix.IdentityToRef(tmat2);
  79499. tmat2.m[12] = x;
  79500. tmat2.m[13] = y;
  79501. tmat2.m[14] = z;
  79502. tmat2.multiplyToRef(tmat, tmat);
  79503. }
  79504. if (parentBone) {
  79505. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  79506. }
  79507. tmat.multiplyToRef(meshMat, tmat);
  79508. position.x = tmat.m[12];
  79509. position.y = tmat.m[13];
  79510. position.z = tmat.m[14];
  79511. };
  79512. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  79513. var len = bones.length;
  79514. var meshPos = this.mesh.position;
  79515. for (var i = 0; i < len; i++) {
  79516. var bone = bones[i];
  79517. var points = this._debugLines[i];
  79518. if (!points) {
  79519. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  79520. this._debugLines[i] = points;
  79521. }
  79522. this._getBonePosition(points[0], bone, meshMat);
  79523. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  79524. points[0].subtractInPlace(meshPos);
  79525. points[1].subtractInPlace(meshPos);
  79526. }
  79527. };
  79528. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  79529. var len = bones.length;
  79530. var boneNum = 0;
  79531. var meshPos = this.mesh.position;
  79532. for (var i = len - 1; i >= 0; i--) {
  79533. var childBone = bones[i];
  79534. var parentBone = childBone.getParent();
  79535. if (!parentBone) {
  79536. continue;
  79537. }
  79538. var points = this._debugLines[boneNum];
  79539. if (!points) {
  79540. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  79541. this._debugLines[boneNum] = points;
  79542. }
  79543. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  79544. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  79545. points[0].subtractInPlace(meshPos);
  79546. points[1].subtractInPlace(meshPos);
  79547. boneNum++;
  79548. }
  79549. };
  79550. SkeletonViewer.prototype.update = function () {
  79551. if (this.autoUpdateBonesMatrices) {
  79552. this.skeleton.computeAbsoluteTransforms();
  79553. }
  79554. if (this.skeleton.bones[0].length === undefined) {
  79555. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  79556. }
  79557. else {
  79558. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  79559. }
  79560. if (!this._debugMesh) {
  79561. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  79562. this._debugMesh.renderingGroupId = this.renderingGroupId;
  79563. }
  79564. else {
  79565. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  79566. }
  79567. this._debugMesh.position.copyFrom(this.mesh.position);
  79568. this._debugMesh.color = this.color;
  79569. };
  79570. SkeletonViewer.prototype.dispose = function () {
  79571. if (this._debugMesh) {
  79572. this.isEnabled = false;
  79573. this._debugMesh.dispose();
  79574. this._debugMesh = null;
  79575. }
  79576. };
  79577. return SkeletonViewer;
  79578. }());
  79579. return Debug;
  79580. }());
  79581. BABYLON.Debug = Debug;
  79582. })(BABYLON || (BABYLON = {}));
  79583. //# sourceMappingURL=babylon.debugModules.js.map
  79584. var BABYLON;
  79585. (function (BABYLON) {
  79586. var RayHelper = /** @class */ (function () {
  79587. function RayHelper(ray) {
  79588. this.ray = ray;
  79589. }
  79590. RayHelper.CreateAndShow = function (ray, scene, color) {
  79591. var helper = new RayHelper(ray);
  79592. helper.show(scene, color);
  79593. return helper;
  79594. };
  79595. RayHelper.prototype.show = function (scene, color) {
  79596. if (!this._renderFunction && this.ray) {
  79597. var ray = this.ray;
  79598. this._renderFunction = this._render.bind(this);
  79599. this._scene = scene;
  79600. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  79601. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  79602. if (this._renderFunction) {
  79603. this._scene.registerBeforeRender(this._renderFunction);
  79604. }
  79605. }
  79606. if (color && this._renderLine) {
  79607. this._renderLine.color.copyFrom(color);
  79608. }
  79609. };
  79610. RayHelper.prototype.hide = function () {
  79611. if (this._renderFunction && this._scene) {
  79612. this._scene.unregisterBeforeRender(this._renderFunction);
  79613. this._scene = null;
  79614. this._renderFunction = null;
  79615. if (this._renderLine) {
  79616. this._renderLine.dispose();
  79617. this._renderLine = null;
  79618. }
  79619. this._renderPoints = [];
  79620. }
  79621. };
  79622. RayHelper.prototype._render = function () {
  79623. var ray = this.ray;
  79624. if (!ray) {
  79625. return;
  79626. }
  79627. var point = this._renderPoints[1];
  79628. var len = Math.min(ray.length, 1000000);
  79629. point.copyFrom(ray.direction);
  79630. point.scaleInPlace(len);
  79631. point.addInPlace(ray.origin);
  79632. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  79633. };
  79634. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  79635. this._attachedToMesh = mesh;
  79636. var ray = this.ray;
  79637. if (!ray) {
  79638. return;
  79639. }
  79640. if (!ray.direction) {
  79641. ray.direction = BABYLON.Vector3.Zero();
  79642. }
  79643. if (!ray.origin) {
  79644. ray.origin = BABYLON.Vector3.Zero();
  79645. }
  79646. if (length) {
  79647. ray.length = length;
  79648. }
  79649. if (!meshSpaceOrigin) {
  79650. meshSpaceOrigin = BABYLON.Vector3.Zero();
  79651. }
  79652. if (!meshSpaceDirection) {
  79653. // -1 so that this will work with Mesh.lookAt
  79654. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  79655. }
  79656. if (!this._meshSpaceDirection) {
  79657. this._meshSpaceDirection = meshSpaceDirection.clone();
  79658. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  79659. }
  79660. else {
  79661. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  79662. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  79663. }
  79664. if (!this._updateToMeshFunction) {
  79665. this._updateToMeshFunction = this._updateToMesh.bind(this);
  79666. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  79667. }
  79668. this._updateToMesh();
  79669. };
  79670. RayHelper.prototype.detachFromMesh = function () {
  79671. if (this._attachedToMesh) {
  79672. if (this._updateToMeshFunction) {
  79673. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  79674. }
  79675. this._attachedToMesh = null;
  79676. this._updateToMeshFunction = null;
  79677. }
  79678. };
  79679. RayHelper.prototype._updateToMesh = function () {
  79680. var ray = this.ray;
  79681. if (!this._attachedToMesh || !ray) {
  79682. return;
  79683. }
  79684. if (this._attachedToMesh._isDisposed) {
  79685. this.detachFromMesh();
  79686. return;
  79687. }
  79688. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  79689. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  79690. };
  79691. RayHelper.prototype.dispose = function () {
  79692. this.hide();
  79693. this.detachFromMesh();
  79694. this.ray = null;
  79695. };
  79696. return RayHelper;
  79697. }());
  79698. BABYLON.RayHelper = RayHelper;
  79699. })(BABYLON || (BABYLON = {}));
  79700. //# sourceMappingURL=babylon.rayHelper.js.map
  79701. var BABYLON;
  79702. (function (BABYLON) {
  79703. // load the inspector using require, if not present in the global namespace.
  79704. var DebugLayer = /** @class */ (function () {
  79705. function DebugLayer(scene) {
  79706. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  79707. this._scene = scene;
  79708. // load inspector using require, if it doesn't exist on the global namespace.
  79709. }
  79710. /** Creates the inspector window. */
  79711. DebugLayer.prototype._createInspector = function (config) {
  79712. if (config === void 0) { config = {}; }
  79713. var popup = config.popup || false;
  79714. var initialTab = config.initialTab || 0;
  79715. var parentElement = config.parentElement || null;
  79716. if (!this._inspector) {
  79717. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  79718. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  79719. } // else nothing to do,; instance is already existing
  79720. };
  79721. DebugLayer.prototype.isVisible = function () {
  79722. if (!this._inspector) {
  79723. return false;
  79724. }
  79725. return true;
  79726. };
  79727. DebugLayer.prototype.hide = function () {
  79728. if (this._inspector) {
  79729. try {
  79730. this._inspector.dispose();
  79731. }
  79732. catch (e) {
  79733. // If the inspector has been removed directly from the inspector tool
  79734. }
  79735. this._inspector = null;
  79736. }
  79737. };
  79738. DebugLayer.prototype.show = function (config) {
  79739. if (config === void 0) { config = {}; }
  79740. if (typeof this.BJSINSPECTOR == 'undefined') {
  79741. // Load inspector and add it to the DOM
  79742. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  79743. }
  79744. else {
  79745. // Otherwise creates the inspector
  79746. this._createInspector(config);
  79747. }
  79748. };
  79749. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  79750. return DebugLayer;
  79751. }());
  79752. BABYLON.DebugLayer = DebugLayer;
  79753. })(BABYLON || (BABYLON = {}));
  79754. //# sourceMappingURL=babylon.debugLayer.js.map
  79755. var BABYLON;
  79756. (function (BABYLON) {
  79757. var BoundingBoxRenderer = /** @class */ (function () {
  79758. function BoundingBoxRenderer(scene) {
  79759. this.frontColor = new BABYLON.Color3(1, 1, 1);
  79760. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  79761. this.showBackLines = true;
  79762. this.renderList = new BABYLON.SmartArray(32);
  79763. this._vertexBuffers = {};
  79764. this._scene = scene;
  79765. }
  79766. BoundingBoxRenderer.prototype._prepareRessources = function () {
  79767. if (this._colorShader) {
  79768. return;
  79769. }
  79770. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  79771. attributes: [BABYLON.VertexBuffer.PositionKind],
  79772. uniforms: ["world", "viewProjection", "color"]
  79773. });
  79774. var engine = this._scene.getEngine();
  79775. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  79776. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  79777. this._createIndexBuffer();
  79778. };
  79779. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  79780. var engine = this._scene.getEngine();
  79781. 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]);
  79782. };
  79783. BoundingBoxRenderer.prototype._rebuild = function () {
  79784. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  79785. if (vb) {
  79786. vb._rebuild();
  79787. }
  79788. this._createIndexBuffer();
  79789. };
  79790. BoundingBoxRenderer.prototype.reset = function () {
  79791. this.renderList.reset();
  79792. };
  79793. BoundingBoxRenderer.prototype.render = function () {
  79794. if (this.renderList.length === 0) {
  79795. return;
  79796. }
  79797. this._prepareRessources();
  79798. if (!this._colorShader.isReady()) {
  79799. return;
  79800. }
  79801. var engine = this._scene.getEngine();
  79802. engine.setDepthWrite(false);
  79803. this._colorShader._preBind();
  79804. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  79805. var boundingBox = this.renderList.data[boundingBoxIndex];
  79806. var min = boundingBox.minimum;
  79807. var max = boundingBox.maximum;
  79808. var diff = max.subtract(min);
  79809. var median = min.add(diff.scale(0.5));
  79810. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  79811. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  79812. .multiply(boundingBox.getWorldMatrix());
  79813. // VBOs
  79814. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  79815. if (this.showBackLines) {
  79816. // Back
  79817. engine.setDepthFunctionToGreaterOrEqual();
  79818. this._scene.resetCachedMaterial();
  79819. this._colorShader.setColor4("color", this.backColor.toColor4());
  79820. this._colorShader.bind(worldMatrix);
  79821. // Draw order
  79822. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  79823. }
  79824. // Front
  79825. engine.setDepthFunctionToLess();
  79826. this._scene.resetCachedMaterial();
  79827. this._colorShader.setColor4("color", this.frontColor.toColor4());
  79828. this._colorShader.bind(worldMatrix);
  79829. // Draw order
  79830. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  79831. }
  79832. this._colorShader.unbind();
  79833. engine.setDepthFunctionToLessOrEqual();
  79834. engine.setDepthWrite(true);
  79835. };
  79836. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  79837. this._prepareRessources();
  79838. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  79839. return;
  79840. }
  79841. var engine = this._scene.getEngine();
  79842. engine.setDepthWrite(false);
  79843. engine.setColorWrite(false);
  79844. this._colorShader._preBind();
  79845. var boundingBox = mesh._boundingInfo.boundingBox;
  79846. var min = boundingBox.minimum;
  79847. var max = boundingBox.maximum;
  79848. var diff = max.subtract(min);
  79849. var median = min.add(diff.scale(0.5));
  79850. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  79851. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  79852. .multiply(boundingBox.getWorldMatrix());
  79853. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  79854. engine.setDepthFunctionToLess();
  79855. this._scene.resetCachedMaterial();
  79856. this._colorShader.bind(worldMatrix);
  79857. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  79858. this._colorShader.unbind();
  79859. engine.setDepthFunctionToLessOrEqual();
  79860. engine.setDepthWrite(true);
  79861. engine.setColorWrite(true);
  79862. };
  79863. BoundingBoxRenderer.prototype.dispose = function () {
  79864. if (!this._colorShader) {
  79865. return;
  79866. }
  79867. this.renderList.dispose();
  79868. this._colorShader.dispose();
  79869. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  79870. if (buffer) {
  79871. buffer.dispose();
  79872. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  79873. }
  79874. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  79875. };
  79876. return BoundingBoxRenderer;
  79877. }());
  79878. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  79879. })(BABYLON || (BABYLON = {}));
  79880. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  79881. var BABYLON;
  79882. (function (BABYLON) {
  79883. var MorphTarget = /** @class */ (function () {
  79884. function MorphTarget(name, influence) {
  79885. if (influence === void 0) { influence = 0; }
  79886. this.name = name;
  79887. this.animations = new Array();
  79888. this._positions = null;
  79889. this._normals = null;
  79890. this._tangents = null;
  79891. this.onInfluenceChanged = new BABYLON.Observable();
  79892. this.influence = influence;
  79893. }
  79894. Object.defineProperty(MorphTarget.prototype, "influence", {
  79895. get: function () {
  79896. return this._influence;
  79897. },
  79898. set: function (influence) {
  79899. if (this._influence === influence) {
  79900. return;
  79901. }
  79902. var previous = this._influence;
  79903. this._influence = influence;
  79904. if (this.onInfluenceChanged.hasObservers) {
  79905. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  79906. }
  79907. },
  79908. enumerable: true,
  79909. configurable: true
  79910. });
  79911. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  79912. get: function () {
  79913. return !!this._positions;
  79914. },
  79915. enumerable: true,
  79916. configurable: true
  79917. });
  79918. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  79919. get: function () {
  79920. return !!this._normals;
  79921. },
  79922. enumerable: true,
  79923. configurable: true
  79924. });
  79925. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  79926. get: function () {
  79927. return !!this._tangents;
  79928. },
  79929. enumerable: true,
  79930. configurable: true
  79931. });
  79932. MorphTarget.prototype.setPositions = function (data) {
  79933. this._positions = data;
  79934. };
  79935. MorphTarget.prototype.getPositions = function () {
  79936. return this._positions;
  79937. };
  79938. MorphTarget.prototype.setNormals = function (data) {
  79939. this._normals = data;
  79940. };
  79941. MorphTarget.prototype.getNormals = function () {
  79942. return this._normals;
  79943. };
  79944. MorphTarget.prototype.setTangents = function (data) {
  79945. this._tangents = data;
  79946. };
  79947. MorphTarget.prototype.getTangents = function () {
  79948. return this._tangents;
  79949. };
  79950. /**
  79951. * Serializes the current target into a Serialization object.
  79952. * Returns the serialized object.
  79953. */
  79954. MorphTarget.prototype.serialize = function () {
  79955. var serializationObject = {};
  79956. serializationObject.name = this.name;
  79957. serializationObject.influence = this.influence;
  79958. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  79959. if (this.hasNormals) {
  79960. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  79961. }
  79962. if (this.hasTangents) {
  79963. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  79964. }
  79965. // Animations
  79966. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  79967. return serializationObject;
  79968. };
  79969. // Statics
  79970. MorphTarget.Parse = function (serializationObject) {
  79971. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  79972. result.setPositions(serializationObject.positions);
  79973. if (serializationObject.normals) {
  79974. result.setNormals(serializationObject.normals);
  79975. }
  79976. if (serializationObject.tangents) {
  79977. result.setTangents(serializationObject.tangents);
  79978. }
  79979. // Animations
  79980. if (serializationObject.animations) {
  79981. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  79982. var parsedAnimation = serializationObject.animations[animationIndex];
  79983. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  79984. }
  79985. }
  79986. return result;
  79987. };
  79988. MorphTarget.FromMesh = function (mesh, name, influence) {
  79989. if (!name) {
  79990. name = mesh.name;
  79991. }
  79992. var result = new MorphTarget(name, influence);
  79993. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  79994. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  79995. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  79996. }
  79997. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  79998. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  79999. }
  80000. return result;
  80001. };
  80002. return MorphTarget;
  80003. }());
  80004. BABYLON.MorphTarget = MorphTarget;
  80005. })(BABYLON || (BABYLON = {}));
  80006. //# sourceMappingURL=babylon.morphTarget.js.map
  80007. var BABYLON;
  80008. (function (BABYLON) {
  80009. var MorphTargetManager = /** @class */ (function () {
  80010. function MorphTargetManager(scene) {
  80011. if (scene === void 0) { scene = null; }
  80012. this._targets = new Array();
  80013. this._targetObservable = new Array();
  80014. this._activeTargets = new BABYLON.SmartArray(16);
  80015. this._supportsNormals = false;
  80016. this._supportsTangents = false;
  80017. this._vertexCount = 0;
  80018. this._uniqueId = 0;
  80019. this._tempInfluences = new Array();
  80020. if (!scene) {
  80021. scene = BABYLON.Engine.LastCreatedScene;
  80022. }
  80023. this._scene = scene;
  80024. if (this._scene) {
  80025. this._scene.morphTargetManagers.push(this);
  80026. this._uniqueId = this._scene.getUniqueId();
  80027. }
  80028. }
  80029. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  80030. get: function () {
  80031. return this._uniqueId;
  80032. },
  80033. enumerable: true,
  80034. configurable: true
  80035. });
  80036. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  80037. get: function () {
  80038. return this._vertexCount;
  80039. },
  80040. enumerable: true,
  80041. configurable: true
  80042. });
  80043. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  80044. get: function () {
  80045. return this._supportsNormals;
  80046. },
  80047. enumerable: true,
  80048. configurable: true
  80049. });
  80050. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  80051. get: function () {
  80052. return this._supportsTangents;
  80053. },
  80054. enumerable: true,
  80055. configurable: true
  80056. });
  80057. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  80058. get: function () {
  80059. return this._targets.length;
  80060. },
  80061. enumerable: true,
  80062. configurable: true
  80063. });
  80064. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  80065. get: function () {
  80066. return this._activeTargets.length;
  80067. },
  80068. enumerable: true,
  80069. configurable: true
  80070. });
  80071. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  80072. get: function () {
  80073. return this._influences;
  80074. },
  80075. enumerable: true,
  80076. configurable: true
  80077. });
  80078. MorphTargetManager.prototype.getActiveTarget = function (index) {
  80079. return this._activeTargets.data[index];
  80080. };
  80081. MorphTargetManager.prototype.getTarget = function (index) {
  80082. return this._targets[index];
  80083. };
  80084. MorphTargetManager.prototype.addTarget = function (target) {
  80085. var _this = this;
  80086. this._targets.push(target);
  80087. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  80088. _this._syncActiveTargets(needUpdate);
  80089. }));
  80090. this._syncActiveTargets(true);
  80091. };
  80092. MorphTargetManager.prototype.removeTarget = function (target) {
  80093. var index = this._targets.indexOf(target);
  80094. if (index >= 0) {
  80095. this._targets.splice(index, 1);
  80096. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  80097. this._syncActiveTargets(true);
  80098. }
  80099. };
  80100. /**
  80101. * Serializes the current manager into a Serialization object.
  80102. * Returns the serialized object.
  80103. */
  80104. MorphTargetManager.prototype.serialize = function () {
  80105. var serializationObject = {};
  80106. serializationObject.id = this.uniqueId;
  80107. serializationObject.targets = [];
  80108. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  80109. var target = _a[_i];
  80110. serializationObject.targets.push(target.serialize());
  80111. }
  80112. return serializationObject;
  80113. };
  80114. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  80115. var influenceCount = 0;
  80116. this._activeTargets.reset();
  80117. this._supportsNormals = true;
  80118. this._supportsTangents = true;
  80119. this._vertexCount = 0;
  80120. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  80121. var target = _a[_i];
  80122. this._activeTargets.push(target);
  80123. this._tempInfluences[influenceCount++] = target.influence;
  80124. var positions = target.getPositions();
  80125. if (positions) {
  80126. this._supportsNormals = this._supportsNormals && target.hasNormals;
  80127. this._supportsTangents = this._supportsTangents && target.hasTangents;
  80128. var vertexCount = positions.length / 3;
  80129. if (this._vertexCount === 0) {
  80130. this._vertexCount = vertexCount;
  80131. }
  80132. else if (this._vertexCount !== vertexCount) {
  80133. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  80134. return;
  80135. }
  80136. }
  80137. }
  80138. if (!this._influences || this._influences.length !== influenceCount) {
  80139. this._influences = new Float32Array(influenceCount);
  80140. }
  80141. for (var index = 0; index < influenceCount; index++) {
  80142. this._influences[index] = this._tempInfluences[index];
  80143. }
  80144. if (needUpdate && this._scene) {
  80145. // Flag meshes as dirty to resync with the active targets
  80146. for (var _b = 0, _c = this._scene.meshes; _b < _c.length; _b++) {
  80147. var mesh = _c[_b];
  80148. if (mesh.morphTargetManager === this) {
  80149. mesh._syncGeometryWithMorphTargetManager();
  80150. }
  80151. }
  80152. }
  80153. };
  80154. // Statics
  80155. MorphTargetManager.Parse = function (serializationObject, scene) {
  80156. var result = new MorphTargetManager(scene);
  80157. result._uniqueId = serializationObject.id;
  80158. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  80159. var targetData = _a[_i];
  80160. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  80161. }
  80162. return result;
  80163. };
  80164. return MorphTargetManager;
  80165. }());
  80166. BABYLON.MorphTargetManager = MorphTargetManager;
  80167. })(BABYLON || (BABYLON = {}));
  80168. //# sourceMappingURL=babylon.morphTargetManager.js.map
  80169. var BABYLON;
  80170. (function (BABYLON) {
  80171. var Octree = /** @class */ (function () {
  80172. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  80173. if (maxDepth === void 0) { maxDepth = 2; }
  80174. this.maxDepth = maxDepth;
  80175. this.dynamicContent = new Array();
  80176. this._maxBlockCapacity = maxBlockCapacity || 64;
  80177. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  80178. this._creationFunc = creationFunc;
  80179. }
  80180. // Methods
  80181. Octree.prototype.update = function (worldMin, worldMax, entries) {
  80182. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  80183. };
  80184. Octree.prototype.addMesh = function (entry) {
  80185. for (var index = 0; index < this.blocks.length; index++) {
  80186. var block = this.blocks[index];
  80187. block.addEntry(entry);
  80188. }
  80189. };
  80190. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  80191. this._selectionContent.reset();
  80192. for (var index = 0; index < this.blocks.length; index++) {
  80193. var block = this.blocks[index];
  80194. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  80195. }
  80196. if (allowDuplicate) {
  80197. this._selectionContent.concat(this.dynamicContent);
  80198. }
  80199. else {
  80200. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  80201. }
  80202. return this._selectionContent;
  80203. };
  80204. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  80205. this._selectionContent.reset();
  80206. for (var index = 0; index < this.blocks.length; index++) {
  80207. var block = this.blocks[index];
  80208. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  80209. }
  80210. if (allowDuplicate) {
  80211. this._selectionContent.concat(this.dynamicContent);
  80212. }
  80213. else {
  80214. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  80215. }
  80216. return this._selectionContent;
  80217. };
  80218. Octree.prototype.intersectsRay = function (ray) {
  80219. this._selectionContent.reset();
  80220. for (var index = 0; index < this.blocks.length; index++) {
  80221. var block = this.blocks[index];
  80222. block.intersectsRay(ray, this._selectionContent);
  80223. }
  80224. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  80225. return this._selectionContent;
  80226. };
  80227. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  80228. target.blocks = new Array();
  80229. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  80230. // Segmenting space
  80231. for (var x = 0; x < 2; x++) {
  80232. for (var y = 0; y < 2; y++) {
  80233. for (var z = 0; z < 2; z++) {
  80234. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  80235. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  80236. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  80237. block.addEntries(entries);
  80238. target.blocks.push(block);
  80239. }
  80240. }
  80241. }
  80242. };
  80243. Octree.CreationFuncForMeshes = function (entry, block) {
  80244. var boundingInfo = entry.getBoundingInfo();
  80245. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  80246. block.entries.push(entry);
  80247. }
  80248. };
  80249. Octree.CreationFuncForSubMeshes = function (entry, block) {
  80250. var boundingInfo = entry.getBoundingInfo();
  80251. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  80252. block.entries.push(entry);
  80253. }
  80254. };
  80255. return Octree;
  80256. }());
  80257. BABYLON.Octree = Octree;
  80258. })(BABYLON || (BABYLON = {}));
  80259. //# sourceMappingURL=babylon.octree.js.map
  80260. var BABYLON;
  80261. (function (BABYLON) {
  80262. var OctreeBlock = /** @class */ (function () {
  80263. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  80264. this.entries = new Array();
  80265. this._boundingVectors = new Array();
  80266. this._capacity = capacity;
  80267. this._depth = depth;
  80268. this._maxDepth = maxDepth;
  80269. this._creationFunc = creationFunc;
  80270. this._minPoint = minPoint;
  80271. this._maxPoint = maxPoint;
  80272. this._boundingVectors.push(minPoint.clone());
  80273. this._boundingVectors.push(maxPoint.clone());
  80274. this._boundingVectors.push(minPoint.clone());
  80275. this._boundingVectors[2].x = maxPoint.x;
  80276. this._boundingVectors.push(minPoint.clone());
  80277. this._boundingVectors[3].y = maxPoint.y;
  80278. this._boundingVectors.push(minPoint.clone());
  80279. this._boundingVectors[4].z = maxPoint.z;
  80280. this._boundingVectors.push(maxPoint.clone());
  80281. this._boundingVectors[5].z = minPoint.z;
  80282. this._boundingVectors.push(maxPoint.clone());
  80283. this._boundingVectors[6].x = minPoint.x;
  80284. this._boundingVectors.push(maxPoint.clone());
  80285. this._boundingVectors[7].y = minPoint.y;
  80286. }
  80287. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  80288. // Property
  80289. get: function () {
  80290. return this._capacity;
  80291. },
  80292. enumerable: true,
  80293. configurable: true
  80294. });
  80295. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  80296. get: function () {
  80297. return this._minPoint;
  80298. },
  80299. enumerable: true,
  80300. configurable: true
  80301. });
  80302. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  80303. get: function () {
  80304. return this._maxPoint;
  80305. },
  80306. enumerable: true,
  80307. configurable: true
  80308. });
  80309. // Methods
  80310. OctreeBlock.prototype.addEntry = function (entry) {
  80311. if (this.blocks) {
  80312. for (var index = 0; index < this.blocks.length; index++) {
  80313. var block = this.blocks[index];
  80314. block.addEntry(entry);
  80315. }
  80316. return;
  80317. }
  80318. this._creationFunc(entry, this);
  80319. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  80320. this.createInnerBlocks();
  80321. }
  80322. };
  80323. OctreeBlock.prototype.addEntries = function (entries) {
  80324. for (var index = 0; index < entries.length; index++) {
  80325. var mesh = entries[index];
  80326. this.addEntry(mesh);
  80327. }
  80328. };
  80329. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  80330. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  80331. if (this.blocks) {
  80332. for (var index = 0; index < this.blocks.length; index++) {
  80333. var block = this.blocks[index];
  80334. block.select(frustumPlanes, selection, allowDuplicate);
  80335. }
  80336. return;
  80337. }
  80338. if (allowDuplicate) {
  80339. selection.concat(this.entries);
  80340. }
  80341. else {
  80342. selection.concatWithNoDuplicate(this.entries);
  80343. }
  80344. }
  80345. };
  80346. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  80347. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  80348. if (this.blocks) {
  80349. for (var index = 0; index < this.blocks.length; index++) {
  80350. var block = this.blocks[index];
  80351. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  80352. }
  80353. return;
  80354. }
  80355. if (allowDuplicate) {
  80356. selection.concat(this.entries);
  80357. }
  80358. else {
  80359. selection.concatWithNoDuplicate(this.entries);
  80360. }
  80361. }
  80362. };
  80363. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  80364. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  80365. if (this.blocks) {
  80366. for (var index = 0; index < this.blocks.length; index++) {
  80367. var block = this.blocks[index];
  80368. block.intersectsRay(ray, selection);
  80369. }
  80370. return;
  80371. }
  80372. selection.concatWithNoDuplicate(this.entries);
  80373. }
  80374. };
  80375. OctreeBlock.prototype.createInnerBlocks = function () {
  80376. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  80377. };
  80378. return OctreeBlock;
  80379. }());
  80380. BABYLON.OctreeBlock = OctreeBlock;
  80381. })(BABYLON || (BABYLON = {}));
  80382. //# sourceMappingURL=babylon.octreeBlock.js.map
  80383. var BABYLON;
  80384. (function (BABYLON) {
  80385. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  80386. __extends(VRDistortionCorrectionPostProcess, _super);
  80387. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  80388. var _this = _super.call(this, name, "vrDistortionCorrection", [
  80389. 'LensCenter',
  80390. 'Scale',
  80391. 'ScaleIn',
  80392. 'HmdWarpParam'
  80393. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  80394. _this._isRightEye = isRightEye;
  80395. _this._distortionFactors = vrMetrics.distortionK;
  80396. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  80397. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  80398. _this.adaptScaleToCurrentViewport = true;
  80399. _this.onSizeChangedObservable.add(function () {
  80400. _this.aspectRatio = _this.width * .5 / _this.height;
  80401. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  80402. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  80403. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  80404. });
  80405. _this.onApplyObservable.add(function (effect) {
  80406. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  80407. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  80408. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  80409. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  80410. });
  80411. return _this;
  80412. }
  80413. return VRDistortionCorrectionPostProcess;
  80414. }(BABYLON.PostProcess));
  80415. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  80416. })(BABYLON || (BABYLON = {}));
  80417. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  80418. var BABYLON;
  80419. (function (BABYLON) {
  80420. var AnaglyphPostProcess = /** @class */ (function (_super) {
  80421. __extends(AnaglyphPostProcess, _super);
  80422. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  80423. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  80424. _this._passedProcess = rigCameras[0]._rigPostProcess;
  80425. _this.onApplyObservable.add(function (effect) {
  80426. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  80427. });
  80428. return _this;
  80429. }
  80430. return AnaglyphPostProcess;
  80431. }(BABYLON.PostProcess));
  80432. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  80433. })(BABYLON || (BABYLON = {}));
  80434. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  80435. var BABYLON;
  80436. (function (BABYLON) {
  80437. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  80438. __extends(StereoscopicInterlacePostProcess, _super);
  80439. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  80440. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  80441. _this._passedProcess = rigCameras[0]._rigPostProcess;
  80442. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  80443. _this.onSizeChangedObservable.add(function () {
  80444. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  80445. });
  80446. _this.onApplyObservable.add(function (effect) {
  80447. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  80448. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  80449. });
  80450. return _this;
  80451. }
  80452. return StereoscopicInterlacePostProcess;
  80453. }(BABYLON.PostProcess));
  80454. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  80455. })(BABYLON || (BABYLON = {}));
  80456. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  80457. var BABYLON;
  80458. (function (BABYLON) {
  80459. /**
  80460. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  80461. * Screen rotation is taken into account.
  80462. */
  80463. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  80464. function FreeCameraDeviceOrientationInput() {
  80465. var _this = this;
  80466. this._screenOrientationAngle = 0;
  80467. this._screenQuaternion = new BABYLON.Quaternion();
  80468. this._alpha = 0;
  80469. this._beta = 0;
  80470. this._gamma = 0;
  80471. this._orientationChanged = function () {
  80472. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  80473. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  80474. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  80475. };
  80476. this._deviceOrientation = function (evt) {
  80477. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  80478. _this._beta = evt.beta !== null ? evt.beta : 0;
  80479. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  80480. };
  80481. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  80482. this._orientationChanged();
  80483. }
  80484. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  80485. get: function () {
  80486. return this._camera;
  80487. },
  80488. set: function (camera) {
  80489. this._camera = camera;
  80490. if (this._camera != null && !this._camera.rotationQuaternion) {
  80491. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  80492. }
  80493. },
  80494. enumerable: true,
  80495. configurable: true
  80496. });
  80497. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  80498. window.addEventListener("orientationchange", this._orientationChanged);
  80499. window.addEventListener("deviceorientation", this._deviceOrientation);
  80500. //In certain cases, the attach control is called AFTER orientation was changed,
  80501. //So this is needed.
  80502. this._orientationChanged();
  80503. };
  80504. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  80505. window.removeEventListener("orientationchange", this._orientationChanged);
  80506. window.removeEventListener("deviceorientation", this._deviceOrientation);
  80507. };
  80508. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  80509. //if no device orientation provided, don't update the rotation.
  80510. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  80511. if (!this._alpha)
  80512. return;
  80513. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  80514. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  80515. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  80516. //Mirror on XY Plane
  80517. this._camera.rotationQuaternion.z *= -1;
  80518. this._camera.rotationQuaternion.w *= -1;
  80519. };
  80520. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  80521. return "FreeCameraDeviceOrientationInput";
  80522. };
  80523. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  80524. return "deviceOrientation";
  80525. };
  80526. return FreeCameraDeviceOrientationInput;
  80527. }());
  80528. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  80529. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  80530. })(BABYLON || (BABYLON = {}));
  80531. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  80532. var BABYLON;
  80533. (function (BABYLON) {
  80534. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  80535. function ArcRotateCameraVRDeviceOrientationInput() {
  80536. this.alphaCorrection = 1;
  80537. this.betaCorrection = 1;
  80538. this.gammaCorrection = 1;
  80539. this._alpha = 0;
  80540. this._gamma = 0;
  80541. this._dirty = false;
  80542. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  80543. }
  80544. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  80545. this.camera.attachControl(element, noPreventDefault);
  80546. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  80547. };
  80548. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  80549. if (evt.alpha !== null) {
  80550. this._alpha = +evt.alpha | 0;
  80551. }
  80552. if (evt.gamma !== null) {
  80553. this._gamma = +evt.gamma | 0;
  80554. }
  80555. this._dirty = true;
  80556. };
  80557. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  80558. if (this._dirty) {
  80559. this._dirty = false;
  80560. if (this._gamma < 0) {
  80561. this._gamma = 180 + this._gamma;
  80562. }
  80563. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  80564. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  80565. }
  80566. };
  80567. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  80568. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  80569. };
  80570. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  80571. return "ArcRotateCameraVRDeviceOrientationInput";
  80572. };
  80573. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  80574. return "VRDeviceOrientation";
  80575. };
  80576. return ArcRotateCameraVRDeviceOrientationInput;
  80577. }());
  80578. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  80579. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  80580. })(BABYLON || (BABYLON = {}));
  80581. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  80582. var BABYLON;
  80583. (function (BABYLON) {
  80584. var VRCameraMetrics = /** @class */ (function () {
  80585. function VRCameraMetrics() {
  80586. this.compensateDistortion = true;
  80587. }
  80588. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  80589. get: function () {
  80590. return this.hResolution / (2 * this.vResolution);
  80591. },
  80592. enumerable: true,
  80593. configurable: true
  80594. });
  80595. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  80596. get: function () {
  80597. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  80598. },
  80599. enumerable: true,
  80600. configurable: true
  80601. });
  80602. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  80603. get: function () {
  80604. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  80605. var h = (4 * meters) / this.hScreenSize;
  80606. return BABYLON.Matrix.Translation(h, 0, 0);
  80607. },
  80608. enumerable: true,
  80609. configurable: true
  80610. });
  80611. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  80612. get: function () {
  80613. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  80614. var h = (4 * meters) / this.hScreenSize;
  80615. return BABYLON.Matrix.Translation(-h, 0, 0);
  80616. },
  80617. enumerable: true,
  80618. configurable: true
  80619. });
  80620. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  80621. get: function () {
  80622. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  80623. },
  80624. enumerable: true,
  80625. configurable: true
  80626. });
  80627. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  80628. get: function () {
  80629. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  80630. },
  80631. enumerable: true,
  80632. configurable: true
  80633. });
  80634. VRCameraMetrics.GetDefault = function () {
  80635. var result = new VRCameraMetrics();
  80636. result.hResolution = 1280;
  80637. result.vResolution = 800;
  80638. result.hScreenSize = 0.149759993;
  80639. result.vScreenSize = 0.0935999975;
  80640. result.vScreenCenter = 0.0467999987;
  80641. result.eyeToScreenDistance = 0.0410000011;
  80642. result.lensSeparationDistance = 0.0635000020;
  80643. result.interpupillaryDistance = 0.0640000030;
  80644. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  80645. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  80646. result.postProcessScaleFactor = 1.714605507808412;
  80647. result.lensCenterOffset = 0.151976421;
  80648. return result;
  80649. };
  80650. return VRCameraMetrics;
  80651. }());
  80652. BABYLON.VRCameraMetrics = VRCameraMetrics;
  80653. })(BABYLON || (BABYLON = {}));
  80654. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  80655. var BABYLON;
  80656. (function (BABYLON) {
  80657. /**
  80658. * This represents a WebVR camera.
  80659. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  80660. * @example http://doc.babylonjs.com/how_to/webvr_camera
  80661. */
  80662. var WebVRFreeCamera = /** @class */ (function (_super) {
  80663. __extends(WebVRFreeCamera, _super);
  80664. /**
  80665. * Instantiates a WebVRFreeCamera.
  80666. * @param name The name of the WebVRFreeCamera
  80667. * @param position The starting anchor position for the camera
  80668. * @param scene The scene the camera belongs to
  80669. * @param webVROptions a set of customizable options for the webVRCamera
  80670. */
  80671. function WebVRFreeCamera(name, position, scene, webVROptions) {
  80672. if (webVROptions === void 0) { webVROptions = {}; }
  80673. var _this = _super.call(this, name, position, scene) || this;
  80674. _this.webVROptions = webVROptions;
  80675. /**
  80676. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  80677. */
  80678. _this._vrDevice = null;
  80679. /**
  80680. * The rawPose of the vrDevice.
  80681. */
  80682. _this.rawPose = null;
  80683. _this._specsVersion = "1.1";
  80684. _this._attached = false;
  80685. _this._descendants = [];
  80686. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  80687. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  80688. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  80689. _this._standingMatrix = null;
  80690. /**
  80691. * Represents device position in babylon space.
  80692. */
  80693. _this.devicePosition = BABYLON.Vector3.Zero();
  80694. /**
  80695. * Represents device rotation in babylon space.
  80696. */
  80697. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  80698. /**
  80699. * The scale of the device to be used when translating from device space to babylon space.
  80700. */
  80701. _this.deviceScaleFactor = 1;
  80702. _this._deviceToWorld = BABYLON.Matrix.Identity();
  80703. _this._worldToDevice = BABYLON.Matrix.Identity();
  80704. /**
  80705. * References to the webVR controllers for the vrDevice.
  80706. */
  80707. _this.controllers = [];
  80708. /**
  80709. * Emits an event when a controller is attached.
  80710. */
  80711. _this.onControllersAttachedObservable = new BABYLON.Observable();
  80712. /**
  80713. * Emits an event when a controller's mesh has been loaded;
  80714. */
  80715. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  80716. /**
  80717. * If the rig cameras be used as parent instead of this camera.
  80718. */
  80719. _this.rigParenting = true;
  80720. _this._defaultHeight = undefined;
  80721. _this._workingVector = BABYLON.Vector3.Zero();
  80722. _this._oneVector = BABYLON.Vector3.One();
  80723. _this._workingMatrix = BABYLON.Matrix.Identity();
  80724. _this._cache.position = BABYLON.Vector3.Zero();
  80725. if (webVROptions.defaultHeight) {
  80726. _this._defaultHeight = webVROptions.defaultHeight;
  80727. _this.position.y = _this._defaultHeight;
  80728. }
  80729. _this.minZ = 0.1;
  80730. //legacy support - the compensation boolean was removed.
  80731. if (arguments.length === 5) {
  80732. _this.webVROptions = arguments[4];
  80733. }
  80734. // default webVR options
  80735. if (_this.webVROptions.trackPosition == undefined) {
  80736. _this.webVROptions.trackPosition = true;
  80737. }
  80738. if (_this.webVROptions.controllerMeshes == undefined) {
  80739. _this.webVROptions.controllerMeshes = true;
  80740. }
  80741. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  80742. _this.webVROptions.defaultLightingOnControllers = true;
  80743. }
  80744. _this.rotationQuaternion = new BABYLON.Quaternion();
  80745. if (_this.webVROptions && _this.webVROptions.positionScale) {
  80746. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  80747. }
  80748. //enable VR
  80749. var engine = _this.getEngine();
  80750. _this._onVREnabled = function (success) { if (success) {
  80751. _this.initControllers();
  80752. } };
  80753. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  80754. engine.initWebVR().add(function (event) {
  80755. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  80756. return;
  80757. }
  80758. _this._vrDevice = event.vrDisplay;
  80759. //reset the rig parameters.
  80760. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  80761. if (_this._attached) {
  80762. _this.getEngine().enableVR();
  80763. }
  80764. });
  80765. if (typeof (VRFrameData) !== "undefined")
  80766. _this._frameData = new VRFrameData();
  80767. /**
  80768. * The idea behind the following lines:
  80769. * objects that have the camera as parent should actually have the rig cameras as a parent.
  80770. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  80771. * the second will not show it correctly.
  80772. *
  80773. * To solve this - each object that has the camera as parent will be added to a protected array.
  80774. * When the rig camera renders, it will take this array and set all of those to be its children.
  80775. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  80776. * Amazing!
  80777. */
  80778. scene.onBeforeCameraRenderObservable.add(function (camera) {
  80779. if (camera.parent === _this && _this.rigParenting) {
  80780. _this._descendants = _this.getDescendants(true, function (n) {
  80781. // don't take the cameras or the controllers!
  80782. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  80783. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  80784. return !isController && !isRigCamera;
  80785. });
  80786. _this._descendants.forEach(function (node) {
  80787. node.parent = camera;
  80788. });
  80789. }
  80790. });
  80791. scene.onAfterCameraRenderObservable.add(function (camera) {
  80792. if (camera.parent === _this && _this.rigParenting) {
  80793. _this._descendants.forEach(function (node) {
  80794. node.parent = _this;
  80795. });
  80796. }
  80797. });
  80798. return _this;
  80799. }
  80800. /**
  80801. * Gets the device distance from the ground in meters.
  80802. * @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.
  80803. */
  80804. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  80805. if (this._standingMatrix) {
  80806. // Add standing matrix offset to get real offset from ground in room
  80807. this._standingMatrix.getTranslationToRef(this._workingVector);
  80808. return this._deviceRoomPosition.y + this._workingVector.y;
  80809. }
  80810. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  80811. return this._defaultHeight || 0;
  80812. };
  80813. /**
  80814. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  80815. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  80816. */
  80817. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  80818. var _this = this;
  80819. if (callback === void 0) { callback = function (bool) { }; }
  80820. // Use standing matrix if available
  80821. this.getEngine().initWebVRAsync().then(function (result) {
  80822. if (!result.vrDisplay || !result.vrDisplay.stageParameters || !result.vrDisplay.stageParameters.sittingToStandingTransform) {
  80823. callback(false);
  80824. }
  80825. else {
  80826. _this._standingMatrix = new BABYLON.Matrix();
  80827. BABYLON.Matrix.FromFloat32ArrayToRefScaled(result.vrDisplay.stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  80828. if (!_this.getScene().useRightHandedSystem) {
  80829. [2, 6, 8, 9, 14].forEach(function (num) {
  80830. if (_this._standingMatrix) {
  80831. _this._standingMatrix.m[num] *= -1;
  80832. }
  80833. });
  80834. }
  80835. callback(true);
  80836. }
  80837. });
  80838. };
  80839. /**
  80840. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  80841. * @returns A promise with a boolean set to if the standing matrix is supported.
  80842. */
  80843. WebVRFreeCamera.prototype.useStandingMatrixAsync = function () {
  80844. var _this = this;
  80845. return new Promise(function (res, rej) {
  80846. _this.useStandingMatrix(function (supported) {
  80847. res(supported);
  80848. });
  80849. });
  80850. };
  80851. /**
  80852. * Disposes the camera
  80853. */
  80854. WebVRFreeCamera.prototype.dispose = function () {
  80855. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  80856. _super.prototype.dispose.call(this);
  80857. };
  80858. /**
  80859. * Gets a vrController by name.
  80860. * @param name The name of the controller to retreive
  80861. * @returns the controller matching the name specified or null if not found
  80862. */
  80863. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  80864. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  80865. var gp = _a[_i];
  80866. if (gp.hand === name) {
  80867. return gp;
  80868. }
  80869. }
  80870. return null;
  80871. };
  80872. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  80873. /**
  80874. * The controller corrisponding to the users left hand.
  80875. */
  80876. get: function () {
  80877. if (!this._leftController) {
  80878. this._leftController = this.getControllerByName("left");
  80879. }
  80880. return this._leftController;
  80881. },
  80882. enumerable: true,
  80883. configurable: true
  80884. });
  80885. ;
  80886. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  80887. /**
  80888. * The controller corrisponding to the users right hand.
  80889. */
  80890. get: function () {
  80891. if (!this._rightController) {
  80892. this._rightController = this.getControllerByName("right");
  80893. }
  80894. return this._rightController;
  80895. },
  80896. enumerable: true,
  80897. configurable: true
  80898. });
  80899. ;
  80900. /**
  80901. * Casts a ray forward from the vrCamera's gaze.
  80902. * @param length Length of the ray (default: 100)
  80903. * @returns the ray corrisponding to the gaze
  80904. */
  80905. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  80906. if (length === void 0) { length = 100; }
  80907. if (this.leftCamera) {
  80908. // Use left eye to avoid computation to compute center on every call
  80909. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  80910. }
  80911. else {
  80912. return _super.prototype.getForwardRay.call(this, length);
  80913. }
  80914. };
  80915. /**
  80916. * Updates the camera based on device's frame data
  80917. */
  80918. WebVRFreeCamera.prototype._checkInputs = function () {
  80919. if (this._vrDevice && this._vrDevice.isPresenting) {
  80920. this._vrDevice.getFrameData(this._frameData);
  80921. this.updateFromDevice(this._frameData.pose);
  80922. }
  80923. _super.prototype._checkInputs.call(this);
  80924. };
  80925. /**
  80926. * Updates the poseControlled values based on the input device pose.
  80927. * @param poseData Pose coming from the device
  80928. */
  80929. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  80930. if (poseData && poseData.orientation) {
  80931. this.rawPose = poseData;
  80932. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  80933. if (this.getScene().useRightHandedSystem) {
  80934. this._deviceRoomRotationQuaternion.z *= -1;
  80935. this._deviceRoomRotationQuaternion.w *= -1;
  80936. }
  80937. if (this.webVROptions.trackPosition && this.rawPose.position) {
  80938. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  80939. if (this.getScene().useRightHandedSystem) {
  80940. this._deviceRoomPosition.z *= -1;
  80941. }
  80942. }
  80943. }
  80944. };
  80945. /**
  80946. * WebVR's attach control will start broadcasting frames to the device.
  80947. * Note that in certain browsers (chrome for example) this function must be called
  80948. * within a user-interaction callback. Example:
  80949. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  80950. *
  80951. * @param element html element to attach the vrDevice to
  80952. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  80953. */
  80954. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  80955. _super.prototype.attachControl.call(this, element, noPreventDefault);
  80956. this._attached = true;
  80957. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  80958. if (this._vrDevice) {
  80959. this.getEngine().enableVR();
  80960. }
  80961. };
  80962. /**
  80963. * Detaches the camera from the html element and disables VR
  80964. *
  80965. * @param element html element to detach from
  80966. */
  80967. WebVRFreeCamera.prototype.detachControl = function (element) {
  80968. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  80969. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  80970. _super.prototype.detachControl.call(this, element);
  80971. this._attached = false;
  80972. this.getEngine().disableVR();
  80973. };
  80974. /**
  80975. * @returns the name of this class
  80976. */
  80977. WebVRFreeCamera.prototype.getClassName = function () {
  80978. return "WebVRFreeCamera";
  80979. };
  80980. /**
  80981. * Calls resetPose on the vrDisplay
  80982. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  80983. */
  80984. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  80985. //uses the vrDisplay's "resetPose()".
  80986. //pitch and roll won't be affected.
  80987. this._vrDevice.resetPose();
  80988. };
  80989. /**
  80990. * Updates the rig cameras (left and right eye)
  80991. */
  80992. WebVRFreeCamera.prototype._updateRigCameras = function () {
  80993. var camLeft = this._rigCameras[0];
  80994. var camRight = this._rigCameras[1];
  80995. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  80996. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  80997. camLeft.position.copyFrom(this._deviceRoomPosition);
  80998. camRight.position.copyFrom(this._deviceRoomPosition);
  80999. };
  81000. /**
  81001. * Updates the cached values of the camera
  81002. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  81003. */
  81004. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  81005. var _this = this;
  81006. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  81007. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  81008. if (!this.updateCacheCalled) {
  81009. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  81010. this.updateCacheCalled = true;
  81011. this.update();
  81012. }
  81013. // Set working vector to the device position in room space rotated by the new rotation
  81014. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  81015. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  81016. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  81017. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  81018. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  81019. // Add translation from anchor position
  81020. this._deviceToWorld.getTranslationToRef(this._workingVector);
  81021. this._workingVector.addInPlace(this.position);
  81022. this._workingVector.subtractInPlace(this._cache.position);
  81023. this._deviceToWorld.setTranslation(this._workingVector);
  81024. // Set an inverted matrix to be used when updating the camera
  81025. this._deviceToWorld.invertToRef(this._worldToDevice);
  81026. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  81027. this.controllers.forEach(function (controller) {
  81028. controller._deviceToWorld.copyFrom(_this._deviceToWorld);
  81029. controller.update();
  81030. });
  81031. }
  81032. if (!ignoreParentClass) {
  81033. _super.prototype._updateCache.call(this);
  81034. }
  81035. this.updateCacheCalled = false;
  81036. };
  81037. /**
  81038. * Updates the current device position and rotation in the babylon world
  81039. */
  81040. WebVRFreeCamera.prototype.update = function () {
  81041. // Get current device position in babylon world
  81042. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  81043. // Get current device rotation in babylon world
  81044. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  81045. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  81046. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  81047. _super.prototype.update.call(this);
  81048. };
  81049. /**
  81050. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  81051. * @returns an identity matrix
  81052. */
  81053. WebVRFreeCamera.prototype._getViewMatrix = function () {
  81054. return BABYLON.Matrix.Identity();
  81055. };
  81056. /**
  81057. * This function is called by the two RIG cameras.
  81058. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  81059. */
  81060. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  81061. var _this = this;
  81062. // Update the parent camera prior to using a child camera to avoid desynchronization
  81063. var parentCamera = this._cameraRigParams["parentCamera"];
  81064. parentCamera._updateCache();
  81065. //WebVR 1.1
  81066. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  81067. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  81068. if (!this.getScene().useRightHandedSystem) {
  81069. [2, 6, 8, 9, 14].forEach(function (num) {
  81070. _this._webvrViewMatrix.m[num] *= -1;
  81071. });
  81072. }
  81073. // update the camera rotation matrix
  81074. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  81075. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  81076. // Computing target and final matrix
  81077. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  81078. // should the view matrix be updated with scale and position offset?
  81079. if (parentCamera.deviceScaleFactor !== 1) {
  81080. this._webvrViewMatrix.invert();
  81081. // scale the position, if set
  81082. if (parentCamera.deviceScaleFactor) {
  81083. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  81084. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  81085. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  81086. }
  81087. this._webvrViewMatrix.invert();
  81088. }
  81089. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  81090. return this._webvrViewMatrix;
  81091. };
  81092. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  81093. var _this = this;
  81094. var parentCamera = this.parent;
  81095. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  81096. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  81097. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  81098. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  81099. //babylon compatible matrix
  81100. if (!this.getScene().useRightHandedSystem) {
  81101. [8, 9, 10, 11].forEach(function (num) {
  81102. _this._projectionMatrix.m[num] *= -1;
  81103. });
  81104. }
  81105. return this._projectionMatrix;
  81106. };
  81107. /**
  81108. * Initializes the controllers and their meshes
  81109. */
  81110. WebVRFreeCamera.prototype.initControllers = function () {
  81111. var _this = this;
  81112. this.controllers = [];
  81113. var manager = this.getScene().gamepadManager;
  81114. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  81115. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  81116. var webVrController = gamepad;
  81117. if (webVrController.defaultModel) {
  81118. webVrController.defaultModel.setEnabled(false);
  81119. }
  81120. if (webVrController.hand === "right") {
  81121. _this._rightController = null;
  81122. }
  81123. if (webVrController.hand === "left") {
  81124. _this._leftController = null;
  81125. }
  81126. var controllerIndex = _this.controllers.indexOf(webVrController);
  81127. if (controllerIndex !== -1) {
  81128. _this.controllers.splice(controllerIndex, 1);
  81129. }
  81130. }
  81131. });
  81132. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  81133. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  81134. var webVrController_1 = gamepad;
  81135. webVrController_1.deviceScaleFactor = _this.deviceScaleFactor;
  81136. webVrController_1._deviceToWorld.copyFrom(_this._deviceToWorld);
  81137. if (_this.webVROptions.controllerMeshes) {
  81138. if (webVrController_1.defaultModel) {
  81139. webVrController_1.defaultModel.setEnabled(true);
  81140. }
  81141. else {
  81142. // Load the meshes
  81143. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  81144. loadedMesh.scaling.scaleInPlace(_this.deviceScaleFactor);
  81145. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  81146. if (_this.webVROptions.defaultLightingOnControllers) {
  81147. if (!_this._lightOnControllers) {
  81148. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  81149. }
  81150. var activateLightOnSubMeshes_1 = function (mesh, light) {
  81151. var children = mesh.getChildren();
  81152. if (children.length !== 0) {
  81153. children.forEach(function (mesh) {
  81154. light.includedOnlyMeshes.push(mesh);
  81155. activateLightOnSubMeshes_1(mesh, light);
  81156. });
  81157. }
  81158. };
  81159. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  81160. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  81161. }
  81162. });
  81163. }
  81164. }
  81165. webVrController_1.attachToPoseControlledCamera(_this);
  81166. // since this is async - sanity check. Is the controller already stored?
  81167. if (_this.controllers.indexOf(webVrController_1) === -1) {
  81168. //add to the controllers array
  81169. _this.controllers.push(webVrController_1);
  81170. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  81171. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  81172. // So we're overriding setting left & right manually to be sure
  81173. var firstViveWandDetected = false;
  81174. for (var i = 0; i < _this.controllers.length; i++) {
  81175. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  81176. if (!firstViveWandDetected) {
  81177. firstViveWandDetected = true;
  81178. _this.controllers[i].hand = "left";
  81179. }
  81180. else {
  81181. _this.controllers[i].hand = "right";
  81182. }
  81183. }
  81184. }
  81185. //did we find enough controllers? Great! let the developer know.
  81186. if (_this.controllers.length >= 2) {
  81187. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  81188. }
  81189. }
  81190. }
  81191. });
  81192. };
  81193. return WebVRFreeCamera;
  81194. }(BABYLON.FreeCamera));
  81195. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  81196. })(BABYLON || (BABYLON = {}));
  81197. //# sourceMappingURL=babylon.webVRCamera.js.map
  81198. var BABYLON;
  81199. (function (BABYLON) {
  81200. // We're mainly based on the logic defined into the FreeCamera code
  81201. /**
  81202. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  81203. * being tilted forward or back and left or right.
  81204. */
  81205. var DeviceOrientationCamera = /** @class */ (function (_super) {
  81206. __extends(DeviceOrientationCamera, _super);
  81207. /**
  81208. * Creates a new device orientation camera. @see DeviceOrientationCamera
  81209. * @param name The name of the camera
  81210. * @param position The start position camera
  81211. * @param scene The scene the camera belongs to
  81212. */
  81213. function DeviceOrientationCamera(name, position, scene) {
  81214. var _this = _super.call(this, name, position, scene) || this;
  81215. _this._quaternionCache = new BABYLON.Quaternion();
  81216. _this.inputs.addDeviceOrientation();
  81217. return _this;
  81218. }
  81219. /**
  81220. * Gets the current instance class name ("DeviceOrientationCamera").
  81221. * This helps avoiding instanceof at run time.
  81222. * @returns the class name
  81223. */
  81224. DeviceOrientationCamera.prototype.getClassName = function () {
  81225. return "DeviceOrientationCamera";
  81226. };
  81227. /**
  81228. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  81229. */
  81230. DeviceOrientationCamera.prototype._checkInputs = function () {
  81231. _super.prototype._checkInputs.call(this);
  81232. this._quaternionCache.copyFrom(this.rotationQuaternion);
  81233. if (this._initialQuaternion) {
  81234. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  81235. }
  81236. };
  81237. /**
  81238. * Reset the camera to its default orientation on the specified axis only.
  81239. * @param axis The axis to reset
  81240. */
  81241. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  81242. var _this = this;
  81243. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  81244. //can only work if this camera has a rotation quaternion already.
  81245. if (!this.rotationQuaternion)
  81246. return;
  81247. if (!this._initialQuaternion) {
  81248. this._initialQuaternion = new BABYLON.Quaternion();
  81249. }
  81250. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  81251. ['x', 'y', 'z'].forEach(function (axisName) {
  81252. if (!axis[axisName]) {
  81253. _this._initialQuaternion[axisName] = 0;
  81254. }
  81255. else {
  81256. _this._initialQuaternion[axisName] *= -1;
  81257. }
  81258. });
  81259. this._initialQuaternion.normalize();
  81260. //force rotation update
  81261. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  81262. };
  81263. return DeviceOrientationCamera;
  81264. }(BABYLON.FreeCamera));
  81265. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  81266. })(BABYLON || (BABYLON = {}));
  81267. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  81268. var BABYLON;
  81269. (function (BABYLON) {
  81270. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  81271. __extends(VRDeviceOrientationFreeCamera, _super);
  81272. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  81273. if (compensateDistortion === void 0) { compensateDistortion = true; }
  81274. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  81275. var _this = _super.call(this, name, position, scene) || this;
  81276. vrCameraMetrics.compensateDistortion = compensateDistortion;
  81277. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  81278. return _this;
  81279. }
  81280. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  81281. return "VRDeviceOrientationFreeCamera";
  81282. };
  81283. return VRDeviceOrientationFreeCamera;
  81284. }(BABYLON.DeviceOrientationCamera));
  81285. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  81286. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  81287. __extends(VRDeviceOrientationGamepadCamera, _super);
  81288. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  81289. if (compensateDistortion === void 0) { compensateDistortion = true; }
  81290. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  81291. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  81292. _this.inputs.addGamepad();
  81293. return _this;
  81294. }
  81295. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  81296. return "VRDeviceOrientationGamepadCamera";
  81297. };
  81298. return VRDeviceOrientationGamepadCamera;
  81299. }(VRDeviceOrientationFreeCamera));
  81300. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  81301. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  81302. __extends(VRDeviceOrientationArcRotateCamera, _super);
  81303. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  81304. if (compensateDistortion === void 0) { compensateDistortion = true; }
  81305. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  81306. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  81307. vrCameraMetrics.compensateDistortion = compensateDistortion;
  81308. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  81309. _this.inputs.addVRDeviceOrientation();
  81310. return _this;
  81311. }
  81312. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  81313. return "VRDeviceOrientationArcRotateCamera";
  81314. };
  81315. return VRDeviceOrientationArcRotateCamera;
  81316. }(BABYLON.ArcRotateCamera));
  81317. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  81318. })(BABYLON || (BABYLON = {}));
  81319. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  81320. var BABYLON;
  81321. (function (BABYLON) {
  81322. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  81323. __extends(AnaglyphFreeCamera, _super);
  81324. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  81325. var _this = _super.call(this, name, position, scene) || this;
  81326. _this.interaxialDistance = interaxialDistance;
  81327. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  81328. return _this;
  81329. }
  81330. AnaglyphFreeCamera.prototype.getClassName = function () {
  81331. return "AnaglyphFreeCamera";
  81332. };
  81333. return AnaglyphFreeCamera;
  81334. }(BABYLON.FreeCamera));
  81335. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  81336. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  81337. __extends(AnaglyphArcRotateCamera, _super);
  81338. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  81339. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  81340. _this.interaxialDistance = interaxialDistance;
  81341. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  81342. return _this;
  81343. }
  81344. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  81345. return "AnaglyphArcRotateCamera";
  81346. };
  81347. return AnaglyphArcRotateCamera;
  81348. }(BABYLON.ArcRotateCamera));
  81349. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  81350. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  81351. __extends(AnaglyphGamepadCamera, _super);
  81352. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  81353. var _this = _super.call(this, name, position, scene) || this;
  81354. _this.interaxialDistance = interaxialDistance;
  81355. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  81356. return _this;
  81357. }
  81358. AnaglyphGamepadCamera.prototype.getClassName = function () {
  81359. return "AnaglyphGamepadCamera";
  81360. };
  81361. return AnaglyphGamepadCamera;
  81362. }(BABYLON.GamepadCamera));
  81363. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  81364. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  81365. __extends(AnaglyphUniversalCamera, _super);
  81366. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  81367. var _this = _super.call(this, name, position, scene) || this;
  81368. _this.interaxialDistance = interaxialDistance;
  81369. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  81370. return _this;
  81371. }
  81372. AnaglyphUniversalCamera.prototype.getClassName = function () {
  81373. return "AnaglyphUniversalCamera";
  81374. };
  81375. return AnaglyphUniversalCamera;
  81376. }(BABYLON.UniversalCamera));
  81377. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  81378. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  81379. __extends(StereoscopicFreeCamera, _super);
  81380. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  81381. var _this = _super.call(this, name, position, scene) || this;
  81382. _this.interaxialDistance = interaxialDistance;
  81383. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  81384. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  81385. return _this;
  81386. }
  81387. StereoscopicFreeCamera.prototype.getClassName = function () {
  81388. return "StereoscopicFreeCamera";
  81389. };
  81390. return StereoscopicFreeCamera;
  81391. }(BABYLON.FreeCamera));
  81392. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  81393. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  81394. __extends(StereoscopicArcRotateCamera, _super);
  81395. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  81396. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  81397. _this.interaxialDistance = interaxialDistance;
  81398. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  81399. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  81400. return _this;
  81401. }
  81402. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  81403. return "StereoscopicArcRotateCamera";
  81404. };
  81405. return StereoscopicArcRotateCamera;
  81406. }(BABYLON.ArcRotateCamera));
  81407. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  81408. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  81409. __extends(StereoscopicGamepadCamera, _super);
  81410. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  81411. var _this = _super.call(this, name, position, scene) || this;
  81412. _this.interaxialDistance = interaxialDistance;
  81413. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  81414. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  81415. return _this;
  81416. }
  81417. StereoscopicGamepadCamera.prototype.getClassName = function () {
  81418. return "StereoscopicGamepadCamera";
  81419. };
  81420. return StereoscopicGamepadCamera;
  81421. }(BABYLON.GamepadCamera));
  81422. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  81423. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  81424. __extends(StereoscopicUniversalCamera, _super);
  81425. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  81426. var _this = _super.call(this, name, position, scene) || this;
  81427. _this.interaxialDistance = interaxialDistance;
  81428. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  81429. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  81430. return _this;
  81431. }
  81432. StereoscopicUniversalCamera.prototype.getClassName = function () {
  81433. return "StereoscopicUniversalCamera";
  81434. };
  81435. return StereoscopicUniversalCamera;
  81436. }(BABYLON.UniversalCamera));
  81437. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  81438. })(BABYLON || (BABYLON = {}));
  81439. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  81440. var BABYLON;
  81441. (function (BABYLON) {
  81442. var VRExperienceHelperGazer = /** @class */ (function () {
  81443. function VRExperienceHelperGazer(scene, gazeTrackerToClone) {
  81444. if (gazeTrackerToClone === void 0) { gazeTrackerToClone = null; }
  81445. this.scene = scene;
  81446. this._pointerDownOnMeshAsked = false;
  81447. this._isActionableMesh = false;
  81448. this._teleportationRequestInitiated = false;
  81449. this._teleportationBackRequestInitiated = false;
  81450. this._dpadPressed = true;
  81451. this._activePointer = false;
  81452. this._id = VRExperienceHelperGazer._idCounter++;
  81453. // Gaze tracker
  81454. if (!gazeTrackerToClone) {
  81455. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, scene, false);
  81456. this._gazeTracker.bakeCurrentTransformIntoVertices();
  81457. this._gazeTracker.isPickable = false;
  81458. this._gazeTracker.isVisible = false;
  81459. var targetMat = new BABYLON.StandardMaterial("targetMat", scene);
  81460. targetMat.specularColor = BABYLON.Color3.Black();
  81461. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  81462. targetMat.backFaceCulling = false;
  81463. this._gazeTracker.material = targetMat;
  81464. }
  81465. else {
  81466. this._gazeTracker = gazeTrackerToClone.clone("gazeTracker");
  81467. }
  81468. }
  81469. VRExperienceHelperGazer.prototype._getForwardRay = function (length) {
  81470. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, length));
  81471. };
  81472. VRExperienceHelperGazer.prototype._selectionPointerDown = function () {
  81473. this._pointerDownOnMeshAsked = true;
  81474. if (this._currentMeshSelected && this._currentHit) {
  81475. this.scene.simulatePointerDown(this._currentHit, { pointerId: this._id });
  81476. }
  81477. };
  81478. VRExperienceHelperGazer.prototype._selectionPointerUp = function () {
  81479. if (this._currentMeshSelected && this._currentHit) {
  81480. this.scene.simulatePointerUp(this._currentHit, { pointerId: this._id });
  81481. }
  81482. this._pointerDownOnMeshAsked = false;
  81483. };
  81484. VRExperienceHelperGazer.prototype._activatePointer = function () {
  81485. this._activePointer = true;
  81486. };
  81487. VRExperienceHelperGazer.prototype._deactivatePointer = function () {
  81488. this._activePointer = false;
  81489. };
  81490. VRExperienceHelperGazer.prototype._updatePointerDistance = function (distance) {
  81491. };
  81492. VRExperienceHelperGazer.prototype.dispose = function () {
  81493. this._interactionsEnabled = false;
  81494. this._teleportationEnabled = false;
  81495. };
  81496. VRExperienceHelperGazer._idCounter = 0;
  81497. return VRExperienceHelperGazer;
  81498. }());
  81499. var VRExperienceHelperControllerGazer = /** @class */ (function (_super) {
  81500. __extends(VRExperienceHelperControllerGazer, _super);
  81501. function VRExperienceHelperControllerGazer(webVRController, scene, gazeTrackerToClone) {
  81502. var _this = _super.call(this, scene, gazeTrackerToClone) || this;
  81503. _this.webVRController = webVRController;
  81504. // Laser pointer
  81505. _this._laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, scene, false);
  81506. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", scene);
  81507. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  81508. laserPointerMaterial.alpha = 0.6;
  81509. _this._laserPointer.material = laserPointerMaterial;
  81510. _this._laserPointer.rotation.x = Math.PI / 2;
  81511. _this._laserPointer.position.z = -0.5;
  81512. _this._laserPointer.isVisible = false;
  81513. if (!webVRController.mesh) {
  81514. // Create an empty mesh that is used prior to loading the high quality model
  81515. var preloadMesh = new BABYLON.Mesh("preloadControllerMesh", scene);
  81516. var preloadPointerPose = new BABYLON.Mesh(BABYLON.PoseEnabledController.POINTING_POSE, scene);
  81517. preloadPointerPose.rotation.x = -0.7;
  81518. preloadMesh.addChild(preloadPointerPose);
  81519. webVRController.attachToMesh(preloadMesh);
  81520. }
  81521. _this._setLaserPointerParent(webVRController.mesh);
  81522. return _this;
  81523. }
  81524. VRExperienceHelperControllerGazer.prototype._getForwardRay = function (length) {
  81525. return this.webVRController.getForwardRay(length);
  81526. };
  81527. VRExperienceHelperControllerGazer.prototype._activatePointer = function () {
  81528. _super.prototype._activatePointer.call(this);
  81529. this._laserPointer.isVisible = true;
  81530. };
  81531. VRExperienceHelperControllerGazer.prototype._deactivatePointer = function () {
  81532. _super.prototype._deactivatePointer.call(this);
  81533. this._laserPointer.isVisible = false;
  81534. };
  81535. VRExperienceHelperControllerGazer.prototype._setLaserPointerColor = function (color) {
  81536. this._laserPointer.material.emissiveColor = color;
  81537. };
  81538. VRExperienceHelperControllerGazer.prototype._setLaserPointerParent = function (mesh) {
  81539. var makeNotPick = function (root) {
  81540. root.name += " laserPointer";
  81541. root.getChildMeshes().forEach(function (c) {
  81542. makeNotPick(c);
  81543. });
  81544. };
  81545. makeNotPick(mesh);
  81546. var childMeshes = mesh.getChildMeshes();
  81547. this.webVRController._pointingPoseNode = null;
  81548. for (var i = 0; i < childMeshes.length; i++) {
  81549. if (childMeshes[i].name && childMeshes[i].name.indexOf(BABYLON.PoseEnabledController.POINTING_POSE) >= 0) {
  81550. mesh = childMeshes[i];
  81551. this.webVRController._pointingPoseNode = mesh;
  81552. break;
  81553. }
  81554. }
  81555. this._laserPointer.parent = mesh;
  81556. };
  81557. VRExperienceHelperControllerGazer.prototype._updatePointerDistance = function (distance) {
  81558. this._laserPointer.scaling.y = distance;
  81559. this._laserPointer.position.z = -distance / 2;
  81560. };
  81561. VRExperienceHelperControllerGazer.prototype.dispose = function () {
  81562. _super.prototype.dispose.call(this);
  81563. this._laserPointer.dispose();
  81564. };
  81565. return VRExperienceHelperControllerGazer;
  81566. }(VRExperienceHelperGazer));
  81567. var VRExperienceHelperCameraGazer = /** @class */ (function (_super) {
  81568. __extends(VRExperienceHelperCameraGazer, _super);
  81569. function VRExperienceHelperCameraGazer(getCamera, scene) {
  81570. var _this = _super.call(this, scene) || this;
  81571. _this.getCamera = getCamera;
  81572. return _this;
  81573. }
  81574. VRExperienceHelperCameraGazer.prototype._getForwardRay = function (length) {
  81575. var camera = this.getCamera();
  81576. if (camera) {
  81577. return camera.getForwardRay(length);
  81578. }
  81579. else {
  81580. return new BABYLON.Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward());
  81581. }
  81582. };
  81583. return VRExperienceHelperCameraGazer;
  81584. }(VRExperienceHelperGazer));
  81585. /**
  81586. * Helps to quickly add VR support to an existing scene.
  81587. * See http://doc.babylonjs.com/how_to/webvr_helper
  81588. */
  81589. var VRExperienceHelper = /** @class */ (function () {
  81590. /**
  81591. * Instantiates a VRExperienceHelper.
  81592. * Helps to quickly add VR support to an existing scene.
  81593. * @param scene The scene the VRExperienceHelper belongs to.
  81594. * @param webVROptions Options to modify the vr experience helper's behavior.
  81595. */
  81596. function VRExperienceHelper(scene, /** Options to modify the vr experience helper's behavior. */ webVROptions) {
  81597. if (webVROptions === void 0) { webVROptions = {}; }
  81598. var _this = this;
  81599. this.webVROptions = webVROptions;
  81600. // Can the system support WebVR, even if a headset isn't plugged in?
  81601. this._webVRsupported = false;
  81602. // If WebVR is supported, is a headset plugged in and are we ready to present?
  81603. this._webVRready = false;
  81604. // Are we waiting for the requestPresent callback to complete?
  81605. this._webVRrequesting = false;
  81606. // Are we presenting to the headset right now?
  81607. this._webVRpresenting = false;
  81608. // Are we presenting in the fullscreen fallback?
  81609. this._fullscreenVRpresenting = false;
  81610. /**
  81611. * Observable raised when entering VR.
  81612. */
  81613. this.onEnteringVRObservable = new BABYLON.Observable();
  81614. /**
  81615. * Observable raised when exiting VR.
  81616. */
  81617. this.onExitingVRObservable = new BABYLON.Observable();
  81618. /**
  81619. * Observable raised when controller mesh is loaded.
  81620. */
  81621. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  81622. this._useCustomVRButton = false;
  81623. this._teleportationRequested = false;
  81624. this._teleportActive = false;
  81625. this._floorMeshesCollection = [];
  81626. this._rotationAllowed = true;
  81627. this._teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  81628. this._rotationRightAsked = false;
  81629. this._rotationLeftAsked = false;
  81630. this._isDefaultTeleportationTarget = true;
  81631. this._teleportationFillColor = "#444444";
  81632. this._teleportationBorderColor = "#FFFFFF";
  81633. this._rotationAngle = 0;
  81634. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  81635. this._padSensibilityUp = 0.65;
  81636. this._padSensibilityDown = 0.35;
  81637. this.leftController = null;
  81638. this.rightController = null;
  81639. /**
  81640. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  81641. */
  81642. this.onNewMeshSelected = new BABYLON.Observable();
  81643. /**
  81644. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  81645. */
  81646. this.onNewMeshPicked = new BABYLON.Observable();
  81647. /**
  81648. * Observable raised before camera teleportation
  81649. */
  81650. this.onBeforeCameraTeleport = new BABYLON.Observable();
  81651. /**
  81652. * Observable raised after camera teleportation
  81653. */
  81654. this.onAfterCameraTeleport = new BABYLON.Observable();
  81655. /**
  81656. * Observable raised when current selected mesh gets unselected
  81657. */
  81658. this.onSelectedMeshUnselected = new BABYLON.Observable();
  81659. /**
  81660. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  81661. */
  81662. this.teleportationEnabled = true;
  81663. this._teleportationInitialized = false;
  81664. this._interactionsEnabled = false;
  81665. this._interactionsRequested = false;
  81666. this._displayGaze = true;
  81667. this._displayLaserPointer = true;
  81668. this._onResize = function () {
  81669. _this.moveButtonToBottomRight();
  81670. if (_this._fullscreenVRpresenting && _this._webVRready) {
  81671. _this.exitVR();
  81672. }
  81673. };
  81674. this._onFullscreenChange = function () {
  81675. if (document.fullscreen !== undefined) {
  81676. _this._fullscreenVRpresenting = document.fullscreen;
  81677. }
  81678. else if (document.mozFullScreen !== undefined) {
  81679. _this._fullscreenVRpresenting = document.mozFullScreen;
  81680. }
  81681. else if (document.webkitIsFullScreen !== undefined) {
  81682. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  81683. }
  81684. else if (document.msIsFullScreen !== undefined) {
  81685. _this._fullscreenVRpresenting = document.msIsFullScreen;
  81686. }
  81687. if (!_this._fullscreenVRpresenting && _this._canvas) {
  81688. _this.exitVR();
  81689. if (!_this._useCustomVRButton) {
  81690. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  81691. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  81692. }
  81693. }
  81694. };
  81695. this.beforeRender = function () {
  81696. if (_this.leftController && _this.leftController._activePointer) {
  81697. _this._castRayAndSelectObject(_this.leftController);
  81698. }
  81699. if (_this.rightController && _this.rightController._activePointer) {
  81700. _this._castRayAndSelectObject(_this.rightController);
  81701. }
  81702. if (!(_this.leftController && _this.leftController._activePointer) && !(_this.rightController && _this.rightController._activePointer)) {
  81703. _this._castRayAndSelectObject(_this._cameraGazer);
  81704. }
  81705. else {
  81706. _this._cameraGazer._gazeTracker.isVisible = false;
  81707. }
  81708. };
  81709. this._onNewGamepadConnected = function (gamepad) {
  81710. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  81711. if (gamepad.leftStick) {
  81712. gamepad.onleftstickchanged(function (stickValues) {
  81713. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  81714. // Listening to classic/xbox gamepad only if no VR controller is active
  81715. if ((!_this.leftController && !_this.rightController) ||
  81716. ((_this.leftController && !_this.leftController._activePointer) &&
  81717. (_this.rightController && !_this.rightController._activePointer))) {
  81718. _this._checkTeleportWithRay(stickValues, _this._cameraGazer);
  81719. _this._checkTeleportBackwards(stickValues, _this._cameraGazer);
  81720. }
  81721. }
  81722. });
  81723. }
  81724. if (gamepad.rightStick) {
  81725. gamepad.onrightstickchanged(function (stickValues) {
  81726. if (_this._teleportationInitialized) {
  81727. _this._checkRotate(stickValues, _this._cameraGazer);
  81728. }
  81729. });
  81730. }
  81731. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  81732. gamepad.onbuttondown(function (buttonPressed) {
  81733. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  81734. _this._cameraGazer._selectionPointerDown();
  81735. }
  81736. });
  81737. gamepad.onbuttonup(function (buttonPressed) {
  81738. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  81739. _this._cameraGazer._selectionPointerUp();
  81740. }
  81741. });
  81742. }
  81743. }
  81744. else {
  81745. var webVRController = gamepad;
  81746. var controller = new VRExperienceHelperControllerGazer(webVRController, _this._scene, _this._cameraGazer._gazeTracker);
  81747. if (webVRController.hand === "right" || (_this.leftController && _this.leftController.webVRController != webVRController)) {
  81748. _this.rightController = controller;
  81749. }
  81750. else {
  81751. _this.leftController = controller;
  81752. }
  81753. _this._tryEnableInteractionOnController(controller);
  81754. }
  81755. };
  81756. // 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
  81757. this._tryEnableInteractionOnController = function (controller) {
  81758. if (_this._interactionsRequested && !controller._interactionsEnabled) {
  81759. _this._enableInteractionOnController(controller);
  81760. }
  81761. if (_this._teleportationRequested && !controller._teleportationEnabled) {
  81762. _this._enableTeleportationOnController(controller);
  81763. }
  81764. };
  81765. this._onNewGamepadDisconnected = function (gamepad) {
  81766. if (gamepad instanceof BABYLON.WebVRController) {
  81767. if (gamepad.hand === "left" && _this.leftController != null) {
  81768. _this.leftController.dispose();
  81769. _this.leftController = null;
  81770. }
  81771. if (gamepad.hand === "right" && _this.rightController != null) {
  81772. _this.rightController.dispose();
  81773. _this.rightController = null;
  81774. }
  81775. }
  81776. };
  81777. this._workingVector = BABYLON.Vector3.Zero();
  81778. this._workingQuaternion = BABYLON.Quaternion.Identity();
  81779. this._workingMatrix = BABYLON.Matrix.Identity();
  81780. this._scene = scene;
  81781. this._canvas = scene.getEngine().getRenderingCanvas();
  81782. // Parse options
  81783. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  81784. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  81785. }
  81786. if (webVROptions.createDeviceOrientationCamera === undefined) {
  81787. webVROptions.createDeviceOrientationCamera = true;
  81788. }
  81789. if (webVROptions.defaultHeight === undefined) {
  81790. webVROptions.defaultHeight = 1.7;
  81791. }
  81792. if (webVROptions.useCustomVRButton) {
  81793. this._useCustomVRButton = true;
  81794. if (webVROptions.customVRButton) {
  81795. this._btnVR = webVROptions.customVRButton;
  81796. }
  81797. }
  81798. if (webVROptions.rayLength) {
  81799. this._rayLength = webVROptions.rayLength;
  81800. }
  81801. this._defaultHeight = webVROptions.defaultHeight;
  81802. if (webVROptions.positionScale) {
  81803. this._rayLength *= webVROptions.positionScale;
  81804. this._defaultHeight *= webVROptions.positionScale;
  81805. }
  81806. // Set position
  81807. if (this._scene.activeCamera) {
  81808. this._position = this._scene.activeCamera.position.clone();
  81809. }
  81810. else {
  81811. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  81812. }
  81813. // Set non-vr camera
  81814. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  81815. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  81816. // Copy data from existing camera
  81817. if (this._scene.activeCamera) {
  81818. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  81819. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  81820. // Set rotation from previous camera
  81821. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  81822. var targetCamera = this._scene.activeCamera;
  81823. if (targetCamera.rotationQuaternion) {
  81824. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  81825. }
  81826. else {
  81827. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  81828. }
  81829. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  81830. }
  81831. }
  81832. this._scene.activeCamera = this._deviceOrientationCamera;
  81833. if (this._canvas) {
  81834. this._scene.activeCamera.attachControl(this._canvas);
  81835. }
  81836. }
  81837. else {
  81838. this._existingCamera = this._scene.activeCamera;
  81839. }
  81840. // Create VR cameras
  81841. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  81842. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  81843. }
  81844. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  81845. this._webVRCamera.useStandingMatrix();
  81846. this._cameraGazer = new VRExperienceHelperCameraGazer(function () { return _this.currentVRCamera; }, scene);
  81847. // Create default button
  81848. if (!this._useCustomVRButton) {
  81849. this._btnVR = document.createElement("BUTTON");
  81850. this._btnVR.className = "babylonVRicon";
  81851. this._btnVR.id = "babylonVRiconbtn";
  81852. this._btnVR.title = "Click to switch to VR";
  81853. 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) }";
  81854. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  81855. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  81856. // css += ".babylonVRicon.vrdisplaysupported { }";
  81857. // css += ".babylonVRicon.vrdisplayready { }";
  81858. // css += ".babylonVRicon.vrdisplayrequesting { }";
  81859. var style = document.createElement('style');
  81860. style.appendChild(document.createTextNode(css));
  81861. document.getElementsByTagName('head')[0].appendChild(style);
  81862. this.moveButtonToBottomRight();
  81863. }
  81864. // VR button click event
  81865. if (this._btnVR) {
  81866. this._btnVR.addEventListener("click", function () {
  81867. if (!_this.isInVRMode) {
  81868. _this.enterVR();
  81869. }
  81870. else {
  81871. _this.exitVR();
  81872. }
  81873. });
  81874. }
  81875. // Window events
  81876. window.addEventListener("resize", this._onResize);
  81877. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  81878. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  81879. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  81880. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  81881. // Display vr button when headset is connected
  81882. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  81883. this.displayVRButton();
  81884. }
  81885. else {
  81886. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  81887. if (e.vrDisplay) {
  81888. _this.displayVRButton();
  81889. }
  81890. });
  81891. }
  81892. // Exiting VR mode using 'ESC' key on desktop
  81893. this._onKeyDown = function (event) {
  81894. if (event.keyCode === 27 && _this.isInVRMode) {
  81895. _this.exitVR();
  81896. }
  81897. };
  81898. document.addEventListener("keydown", this._onKeyDown);
  81899. // Exiting VR mode double tapping the touch screen
  81900. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  81901. if (_this.isInVRMode) {
  81902. _this.exitVR();
  81903. if (_this._fullscreenVRpresenting) {
  81904. _this._scene.getEngine().switchFullscreen(true);
  81905. }
  81906. }
  81907. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  81908. // Listen for WebVR display changes
  81909. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  81910. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  81911. this._onVRRequestPresentStart = function () {
  81912. _this._webVRrequesting = true;
  81913. _this.updateButtonVisibility();
  81914. };
  81915. this._onVRRequestPresentComplete = function (success) {
  81916. _this._webVRrequesting = false;
  81917. _this.updateButtonVisibility();
  81918. };
  81919. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  81920. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  81921. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  81922. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  81923. scene.onDisposeObservable.add(function () {
  81924. _this.dispose();
  81925. });
  81926. // Gamepad connection events
  81927. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  81928. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  81929. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  81930. this.updateButtonVisibility();
  81931. //create easing functions
  81932. this._circleEase = new BABYLON.CircleEase();
  81933. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  81934. }
  81935. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  81936. /** Return this.onEnteringVRObservable
  81937. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  81938. */
  81939. get: function () {
  81940. return this.onEnteringVRObservable;
  81941. },
  81942. enumerable: true,
  81943. configurable: true
  81944. });
  81945. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  81946. /** Return this.onExitingVRObservable
  81947. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  81948. */
  81949. get: function () {
  81950. return this.onExitingVRObservable;
  81951. },
  81952. enumerable: true,
  81953. configurable: true
  81954. });
  81955. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  81956. /** Return this.onControllerMeshLoadedObservable
  81957. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  81958. */
  81959. get: function () {
  81960. return this.onControllerMeshLoadedObservable;
  81961. },
  81962. enumerable: true,
  81963. configurable: true
  81964. });
  81965. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  81966. /**
  81967. * The mesh used to display where the user is going to teleport.
  81968. */
  81969. get: function () {
  81970. return this._teleportationTarget;
  81971. },
  81972. /**
  81973. * Sets the mesh to be used to display where the user is going to teleport.
  81974. */
  81975. set: function (value) {
  81976. if (value) {
  81977. value.name = "teleportationTarget";
  81978. this._isDefaultTeleportationTarget = false;
  81979. this._teleportationTarget = value;
  81980. }
  81981. },
  81982. enumerable: true,
  81983. configurable: true
  81984. });
  81985. Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", {
  81986. /**
  81987. * The mesh used to display where the user is selecting,
  81988. * when set bakeCurrentTransformIntoVertices will be called on the mesh.
  81989. * See http://doc.babylonjs.com/resources/baking_transformations
  81990. */
  81991. get: function () {
  81992. return this._cameraGazer._gazeTracker;
  81993. },
  81994. set: function (value) {
  81995. if (value) {
  81996. this._cameraGazer._gazeTracker = value;
  81997. this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices();
  81998. this._cameraGazer._gazeTracker.isPickable = false;
  81999. this._cameraGazer._gazeTracker.isVisible = false;
  82000. this._cameraGazer._gazeTracker.name = "gazeTracker";
  82001. if (this.leftController) {
  82002. this.leftController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  82003. }
  82004. if (this.rightController) {
  82005. this.rightController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  82006. }
  82007. }
  82008. },
  82009. enumerable: true,
  82010. configurable: true
  82011. });
  82012. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  82013. /**
  82014. * If the ray of the gaze should be displayed.
  82015. */
  82016. get: function () {
  82017. return this._displayGaze;
  82018. },
  82019. /**
  82020. * Sets if the ray of the gaze should be displayed.
  82021. */
  82022. set: function (value) {
  82023. this._displayGaze = value;
  82024. if (!value) {
  82025. this._cameraGazer._gazeTracker.isVisible = false;
  82026. if (this.leftController) {
  82027. this.leftController._gazeTracker.isVisible = false;
  82028. }
  82029. if (this.rightController) {
  82030. this.rightController._gazeTracker.isVisible = false;
  82031. }
  82032. }
  82033. },
  82034. enumerable: true,
  82035. configurable: true
  82036. });
  82037. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  82038. /**
  82039. * If the ray of the LaserPointer should be displayed.
  82040. */
  82041. get: function () {
  82042. return this._displayLaserPointer;
  82043. },
  82044. /**
  82045. * Sets if the ray of the LaserPointer should be displayed.
  82046. */
  82047. set: function (value) {
  82048. this._displayLaserPointer = value;
  82049. if (!value) {
  82050. if (this.rightController) {
  82051. this.rightController._deactivatePointer();
  82052. this.rightController._gazeTracker.isVisible = false;
  82053. }
  82054. if (this.leftController) {
  82055. this.leftController._deactivatePointer();
  82056. this.leftController._gazeTracker.isVisible = false;
  82057. }
  82058. }
  82059. else {
  82060. if (this.rightController) {
  82061. this.rightController._activatePointer();
  82062. }
  82063. else if (this.leftController) {
  82064. this.leftController._activatePointer();
  82065. }
  82066. }
  82067. },
  82068. enumerable: true,
  82069. configurable: true
  82070. });
  82071. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  82072. /**
  82073. * The deviceOrientationCamera used as the camera when not in VR.
  82074. */
  82075. get: function () {
  82076. return this._deviceOrientationCamera;
  82077. },
  82078. enumerable: true,
  82079. configurable: true
  82080. });
  82081. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  82082. /**
  82083. * Based on the current WebVR support, returns the current VR camera used.
  82084. */
  82085. get: function () {
  82086. if (this._webVRready) {
  82087. return this._webVRCamera;
  82088. }
  82089. else {
  82090. return this._scene.activeCamera;
  82091. }
  82092. },
  82093. enumerable: true,
  82094. configurable: true
  82095. });
  82096. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  82097. /**
  82098. * The webVRCamera which is used when in VR.
  82099. */
  82100. get: function () {
  82101. return this._webVRCamera;
  82102. },
  82103. enumerable: true,
  82104. configurable: true
  82105. });
  82106. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  82107. /**
  82108. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  82109. */
  82110. get: function () {
  82111. return this._vrDeviceOrientationCamera;
  82112. },
  82113. enumerable: true,
  82114. configurable: true
  82115. });
  82116. Object.defineProperty(VRExperienceHelper.prototype, "_teleportationRequestInitiated", {
  82117. get: function () {
  82118. var result = this._cameraGazer._teleportationRequestInitiated
  82119. || (this.leftController !== null && this.leftController._teleportationRequestInitiated)
  82120. || (this.rightController !== null && this.rightController._teleportationRequestInitiated);
  82121. return result;
  82122. },
  82123. enumerable: true,
  82124. configurable: true
  82125. });
  82126. // Raised when one of the controller has loaded successfully its associated default mesh
  82127. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  82128. if (this.leftController && this.leftController.webVRController == webVRController) {
  82129. if (webVRController.mesh) {
  82130. this.leftController._setLaserPointerParent(webVRController.mesh);
  82131. }
  82132. }
  82133. if (this.rightController && this.rightController.webVRController == webVRController) {
  82134. if (webVRController.mesh) {
  82135. this.rightController._setLaserPointerParent(webVRController.mesh);
  82136. }
  82137. }
  82138. try {
  82139. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  82140. }
  82141. catch (err) {
  82142. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  82143. }
  82144. };
  82145. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  82146. /**
  82147. * Gets a value indicating if we are currently in VR mode.
  82148. */
  82149. get: function () {
  82150. return this._webVRpresenting || this._fullscreenVRpresenting;
  82151. },
  82152. enumerable: true,
  82153. configurable: true
  82154. });
  82155. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  82156. var vrDisplay = this._scene.getEngine().getVRDevice();
  82157. if (vrDisplay) {
  82158. var wasPresenting = this._webVRpresenting;
  82159. // A VR display is connected
  82160. this._webVRpresenting = vrDisplay.isPresenting;
  82161. if (wasPresenting && !this._webVRpresenting)
  82162. this.exitVR();
  82163. }
  82164. else {
  82165. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  82166. }
  82167. this.updateButtonVisibility();
  82168. };
  82169. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  82170. this._webVRsupported = eventArgs.vrSupported;
  82171. this._webVRready = !!eventArgs.vrDisplay;
  82172. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  82173. this.updateButtonVisibility();
  82174. };
  82175. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  82176. if (this._canvas && !this._useCustomVRButton) {
  82177. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  82178. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  82179. }
  82180. };
  82181. VRExperienceHelper.prototype.displayVRButton = function () {
  82182. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  82183. document.body.appendChild(this._btnVR);
  82184. this._btnVRDisplayed = true;
  82185. }
  82186. };
  82187. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  82188. if (!this._btnVR || this._useCustomVRButton) {
  82189. return;
  82190. }
  82191. this._btnVR.className = "babylonVRicon";
  82192. if (this.isInVRMode) {
  82193. this._btnVR.className += " vrdisplaypresenting";
  82194. }
  82195. else {
  82196. if (this._webVRready)
  82197. this._btnVR.className += " vrdisplayready";
  82198. if (this._webVRsupported)
  82199. this._btnVR.className += " vrdisplaysupported";
  82200. if (this._webVRrequesting)
  82201. this._btnVR.className += " vrdisplayrequesting";
  82202. }
  82203. };
  82204. /**
  82205. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  82206. * Otherwise, will use the fullscreen API.
  82207. */
  82208. VRExperienceHelper.prototype.enterVR = function () {
  82209. if (this.onEnteringVRObservable) {
  82210. try {
  82211. this.onEnteringVRObservable.notifyObservers(this);
  82212. }
  82213. catch (err) {
  82214. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  82215. }
  82216. }
  82217. if (this._scene.activeCamera) {
  82218. this._position = this._scene.activeCamera.position.clone();
  82219. // make sure that we return to the last active camera
  82220. this._existingCamera = this._scene.activeCamera;
  82221. }
  82222. if (this._webVRrequesting)
  82223. return;
  82224. // If WebVR is supported and a headset is connected
  82225. if (this._webVRready) {
  82226. if (!this._webVRpresenting) {
  82227. this._webVRCamera.position = this._position;
  82228. this._scene.activeCamera = this._webVRCamera;
  82229. }
  82230. }
  82231. else if (this._vrDeviceOrientationCamera) {
  82232. this._vrDeviceOrientationCamera.position = this._position;
  82233. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  82234. this._scene.getEngine().switchFullscreen(true);
  82235. this.updateButtonVisibility();
  82236. }
  82237. if (this._scene.activeCamera && this._canvas) {
  82238. this._scene.activeCamera.attachControl(this._canvas);
  82239. }
  82240. if (this._interactionsEnabled) {
  82241. this._scene.registerBeforeRender(this.beforeRender);
  82242. }
  82243. };
  82244. /**
  82245. * Attempt to exit VR, or fullscreen.
  82246. */
  82247. VRExperienceHelper.prototype.exitVR = function () {
  82248. if (this.onExitingVRObservable) {
  82249. try {
  82250. this.onExitingVRObservable.notifyObservers(this);
  82251. }
  82252. catch (err) {
  82253. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  82254. }
  82255. }
  82256. if (this._webVRpresenting) {
  82257. this._scene.getEngine().disableVR();
  82258. }
  82259. if (this._scene.activeCamera) {
  82260. this._position = this._scene.activeCamera.position.clone();
  82261. }
  82262. if (this._deviceOrientationCamera) {
  82263. this._deviceOrientationCamera.position = this._position;
  82264. this._scene.activeCamera = this._deviceOrientationCamera;
  82265. if (this._canvas) {
  82266. this._scene.activeCamera.attachControl(this._canvas);
  82267. }
  82268. }
  82269. else if (this._existingCamera) {
  82270. this._existingCamera.position = this._position;
  82271. this._scene.activeCamera = this._existingCamera;
  82272. }
  82273. this.updateButtonVisibility();
  82274. if (this._interactionsEnabled) {
  82275. this._scene.unregisterBeforeRender(this.beforeRender);
  82276. }
  82277. };
  82278. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  82279. /**
  82280. * The position of the vr experience helper.
  82281. */
  82282. get: function () {
  82283. return this._position;
  82284. },
  82285. /**
  82286. * Sets the position of the vr experience helper.
  82287. */
  82288. set: function (value) {
  82289. this._position = value;
  82290. if (this._scene.activeCamera) {
  82291. this._scene.activeCamera.position = value;
  82292. }
  82293. },
  82294. enumerable: true,
  82295. configurable: true
  82296. });
  82297. /**
  82298. * Enables controllers and user interactions suck as selecting and object or clicking on an object.
  82299. */
  82300. VRExperienceHelper.prototype.enableInteractions = function () {
  82301. var _this = this;
  82302. if (!this._interactionsEnabled) {
  82303. this._interactionsRequested = true;
  82304. if (this.leftController) {
  82305. this._enableInteractionOnController(this.leftController);
  82306. }
  82307. if (this.rightController) {
  82308. this._enableInteractionOnController(this.rightController);
  82309. }
  82310. this.raySelectionPredicate = function (mesh) {
  82311. return mesh.isVisible;
  82312. };
  82313. this.meshSelectionPredicate = function (mesh) {
  82314. return true;
  82315. };
  82316. this._raySelectionPredicate = function (mesh) {
  82317. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  82318. && mesh.name.indexOf("teleportationTarget") === -1
  82319. && mesh.name.indexOf("torusTeleportation") === -1
  82320. && mesh.name.indexOf("laserPointer") === -1)) {
  82321. return _this.raySelectionPredicate(mesh);
  82322. }
  82323. return false;
  82324. };
  82325. this._interactionsEnabled = true;
  82326. }
  82327. };
  82328. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  82329. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  82330. if (this._floorMeshesCollection[i].id === mesh.id) {
  82331. return true;
  82332. }
  82333. }
  82334. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  82335. return true;
  82336. }
  82337. return false;
  82338. };
  82339. /**
  82340. * Adds a floor mesh to be used for teleportation.
  82341. * @param floorMesh the mesh to be used for teleportation.
  82342. */
  82343. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  82344. if (!this._floorMeshesCollection) {
  82345. return;
  82346. }
  82347. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  82348. return;
  82349. }
  82350. this._floorMeshesCollection.push(floorMesh);
  82351. };
  82352. /**
  82353. * Removes a floor mesh from being used for teleportation.
  82354. * @param floorMesh the mesh to be removed.
  82355. */
  82356. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  82357. if (!this._floorMeshesCollection) {
  82358. return;
  82359. }
  82360. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  82361. if (meshIndex !== -1) {
  82362. this._floorMeshesCollection.splice(meshIndex, 1);
  82363. }
  82364. };
  82365. /**
  82366. * Enables interactions and teleportation using the VR controllers and gaze.
  82367. * @param vrTeleportationOptions options to modify teleportation behavior.
  82368. */
  82369. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  82370. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  82371. if (!this._teleportationInitialized) {
  82372. this._teleportationRequested = true;
  82373. this.enableInteractions();
  82374. if (vrTeleportationOptions.floorMeshName) {
  82375. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  82376. }
  82377. if (vrTeleportationOptions.floorMeshes) {
  82378. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  82379. }
  82380. if (this.leftController != null) {
  82381. this._enableTeleportationOnController(this.leftController);
  82382. }
  82383. if (this.rightController != null) {
  82384. this._enableTeleportationOnController(this.rightController);
  82385. }
  82386. // Creates an image processing post process for the vignette not relying
  82387. // on the main scene configuration for image processing to reduce setup and spaces
  82388. // (gamma/linear) conflicts.
  82389. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  82390. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  82391. imageProcessingConfiguration.vignetteEnabled = true;
  82392. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  82393. this._webVRCamera.detachPostProcess(this._postProcessMove);
  82394. this._teleportationInitialized = true;
  82395. if (this._isDefaultTeleportationTarget) {
  82396. this._createTeleportationCircles();
  82397. this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor);
  82398. }
  82399. }
  82400. };
  82401. VRExperienceHelper.prototype._enableInteractionOnController = function (controller) {
  82402. var _this = this;
  82403. var controllerMesh = controller.webVRController.mesh;
  82404. if (controllerMesh) {
  82405. controller._interactionsEnabled = true;
  82406. controller._activatePointer();
  82407. controller.webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  82408. // Enabling / disabling laserPointer
  82409. if (_this._displayLaserPointer && stateObject.value === 1) {
  82410. if (controller._activePointer) {
  82411. controller._deactivatePointer();
  82412. }
  82413. else {
  82414. controller._activatePointer();
  82415. }
  82416. if (_this.displayGaze) {
  82417. controller._gazeTracker.isVisible = controller._activePointer;
  82418. }
  82419. }
  82420. });
  82421. controller.webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  82422. if (!controller._pointerDownOnMeshAsked) {
  82423. if (stateObject.value > _this._padSensibilityUp) {
  82424. controller._selectionPointerDown();
  82425. }
  82426. }
  82427. else if (stateObject.value < _this._padSensibilityDown) {
  82428. controller._selectionPointerUp();
  82429. }
  82430. });
  82431. }
  82432. };
  82433. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, gazer) {
  82434. // Dont teleport if another gaze already requested teleportation
  82435. if (this._teleportationRequestInitiated && !gazer._teleportationRequestInitiated) {
  82436. return;
  82437. }
  82438. if (!gazer._teleportationRequestInitiated) {
  82439. if (stateObject.y < -this._padSensibilityUp && gazer._dpadPressed) {
  82440. gazer._activatePointer();
  82441. gazer._teleportationRequestInitiated = true;
  82442. }
  82443. }
  82444. else {
  82445. // Listening to the proper controller values changes to confirm teleportation
  82446. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  82447. if (this._teleportActive) {
  82448. this._teleportCamera(this._haloCenter);
  82449. }
  82450. gazer._teleportationRequestInitiated = false;
  82451. }
  82452. }
  82453. };
  82454. VRExperienceHelper.prototype._checkRotate = function (stateObject, gazer) {
  82455. // Only rotate when user is not currently selecting a teleportation location
  82456. if (gazer._teleportationRequestInitiated) {
  82457. return;
  82458. }
  82459. if (!this._rotationLeftAsked) {
  82460. if (stateObject.x < -this._padSensibilityUp && gazer._dpadPressed) {
  82461. this._rotationLeftAsked = true;
  82462. if (this._rotationAllowed) {
  82463. this._rotateCamera(false);
  82464. }
  82465. }
  82466. }
  82467. else {
  82468. if (stateObject.x > -this._padSensibilityDown) {
  82469. this._rotationLeftAsked = false;
  82470. }
  82471. }
  82472. if (!this._rotationRightAsked) {
  82473. if (stateObject.x > this._padSensibilityUp && gazer._dpadPressed) {
  82474. this._rotationRightAsked = true;
  82475. if (this._rotationAllowed) {
  82476. this._rotateCamera(true);
  82477. }
  82478. }
  82479. }
  82480. else {
  82481. if (stateObject.x < this._padSensibilityDown) {
  82482. this._rotationRightAsked = false;
  82483. }
  82484. }
  82485. };
  82486. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject, gazer) {
  82487. // Only teleport backwards when user is not currently selecting a teleportation location
  82488. if (gazer._teleportationRequestInitiated) {
  82489. return;
  82490. }
  82491. // Teleport backwards
  82492. if (stateObject.y > this._padSensibilityUp && gazer._dpadPressed) {
  82493. if (!gazer._teleportationBackRequestInitiated) {
  82494. if (!this.currentVRCamera) {
  82495. return;
  82496. }
  82497. // Get rotation and position of the current camera
  82498. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  82499. var position = this.currentVRCamera.position;
  82500. // If the camera has device position, use that instead
  82501. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  82502. rotation = this.currentVRCamera.deviceRotationQuaternion;
  82503. position = this.currentVRCamera.devicePosition;
  82504. }
  82505. // Get matrix with only the y rotation of the device rotation
  82506. rotation.toEulerAnglesToRef(this._workingVector);
  82507. this._workingVector.z = 0;
  82508. this._workingVector.x = 0;
  82509. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  82510. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  82511. // Rotate backwards ray by device rotation to cast at the ground behind the user
  82512. BABYLON.Vector3.TransformCoordinatesToRef(this._teleportBackwardsVector, this._workingMatrix, this._workingVector);
  82513. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  82514. var ray = new BABYLON.Ray(position, this._workingVector);
  82515. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  82516. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  82517. this._teleportCamera(hit.pickedPoint);
  82518. }
  82519. gazer._teleportationBackRequestInitiated = true;
  82520. }
  82521. }
  82522. else {
  82523. gazer._teleportationBackRequestInitiated = false;
  82524. }
  82525. };
  82526. VRExperienceHelper.prototype._enableTeleportationOnController = function (controller) {
  82527. var _this = this;
  82528. var controllerMesh = controller.webVRController.mesh;
  82529. if (controllerMesh) {
  82530. if (!controller._interactionsEnabled) {
  82531. this._enableInteractionOnController(controller);
  82532. }
  82533. controller._interactionsEnabled = true;
  82534. controller._teleportationEnabled = true;
  82535. if (controller.webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  82536. controller._dpadPressed = false;
  82537. controller.webVRController.onPadStateChangedObservable.add(function (stateObject) {
  82538. controller._dpadPressed = stateObject.pressed;
  82539. if (!controller._dpadPressed) {
  82540. _this._rotationLeftAsked = false;
  82541. _this._rotationRightAsked = false;
  82542. controller._teleportationBackRequestInitiated = false;
  82543. }
  82544. });
  82545. }
  82546. controller.webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  82547. if (_this.teleportationEnabled) {
  82548. _this._checkTeleportBackwards(stateObject, controller);
  82549. _this._checkTeleportWithRay(stateObject, controller);
  82550. }
  82551. _this._checkRotate(stateObject, controller);
  82552. });
  82553. }
  82554. };
  82555. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  82556. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  82557. this._teleportationTarget.isPickable = false;
  82558. var length = 512;
  82559. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  82560. dynamicTexture.hasAlpha = true;
  82561. var context = dynamicTexture.getContext();
  82562. var centerX = length / 2;
  82563. var centerY = length / 2;
  82564. var radius = 200;
  82565. context.beginPath();
  82566. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  82567. context.fillStyle = this._teleportationFillColor;
  82568. context.fill();
  82569. context.lineWidth = 10;
  82570. context.strokeStyle = this._teleportationBorderColor;
  82571. context.stroke();
  82572. context.closePath();
  82573. dynamicTexture.update();
  82574. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  82575. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  82576. this._teleportationTarget.material = teleportationCircleMaterial;
  82577. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  82578. torus.isPickable = false;
  82579. torus.parent = this._teleportationTarget;
  82580. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  82581. var keys = [];
  82582. keys.push({
  82583. frame: 0,
  82584. value: 0
  82585. });
  82586. keys.push({
  82587. frame: 30,
  82588. value: 0.4
  82589. });
  82590. keys.push({
  82591. frame: 60,
  82592. value: 0
  82593. });
  82594. animationInnerCircle.setKeys(keys);
  82595. var easingFunction = new BABYLON.SineEase();
  82596. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  82597. animationInnerCircle.setEasingFunction(easingFunction);
  82598. torus.animations = [];
  82599. torus.animations.push(animationInnerCircle);
  82600. this._scene.beginAnimation(torus, 0, 60, true);
  82601. this._hideTeleportationTarget();
  82602. };
  82603. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  82604. this._teleportActive = true;
  82605. if (this._teleportationInitialized) {
  82606. this._teleportationTarget.isVisible = true;
  82607. if (this._isDefaultTeleportationTarget) {
  82608. this._teleportationTarget.getChildren()[0].isVisible = true;
  82609. }
  82610. }
  82611. };
  82612. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  82613. this._teleportActive = false;
  82614. if (this._teleportationInitialized) {
  82615. this._teleportationTarget.isVisible = false;
  82616. if (this._isDefaultTeleportationTarget) {
  82617. this._teleportationTarget.getChildren()[0].isVisible = false;
  82618. }
  82619. }
  82620. };
  82621. VRExperienceHelper.prototype._rotateCamera = function (right) {
  82622. var _this = this;
  82623. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  82624. return;
  82625. }
  82626. if (right) {
  82627. this._rotationAngle++;
  82628. }
  82629. else {
  82630. this._rotationAngle--;
  82631. }
  82632. this.currentVRCamera.animations = [];
  82633. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  82634. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  82635. var animationRotationKeys = [];
  82636. animationRotationKeys.push({
  82637. frame: 0,
  82638. value: this.currentVRCamera.rotationQuaternion
  82639. });
  82640. animationRotationKeys.push({
  82641. frame: 6,
  82642. value: target
  82643. });
  82644. animationRotation.setKeys(animationRotationKeys);
  82645. animationRotation.setEasingFunction(this._circleEase);
  82646. this.currentVRCamera.animations.push(animationRotation);
  82647. this._postProcessMove.animations = [];
  82648. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  82649. var vignetteWeightKeys = [];
  82650. vignetteWeightKeys.push({
  82651. frame: 0,
  82652. value: 0
  82653. });
  82654. vignetteWeightKeys.push({
  82655. frame: 3,
  82656. value: 4
  82657. });
  82658. vignetteWeightKeys.push({
  82659. frame: 6,
  82660. value: 0
  82661. });
  82662. animationPP.setKeys(vignetteWeightKeys);
  82663. animationPP.setEasingFunction(this._circleEase);
  82664. this._postProcessMove.animations.push(animationPP);
  82665. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  82666. var vignetteStretchKeys = [];
  82667. vignetteStretchKeys.push({
  82668. frame: 0,
  82669. value: 0
  82670. });
  82671. vignetteStretchKeys.push({
  82672. frame: 3,
  82673. value: 10
  82674. });
  82675. vignetteStretchKeys.push({
  82676. frame: 6,
  82677. value: 0
  82678. });
  82679. animationPP2.setKeys(vignetteStretchKeys);
  82680. animationPP2.setEasingFunction(this._circleEase);
  82681. this._postProcessMove.animations.push(animationPP2);
  82682. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  82683. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  82684. this._postProcessMove.samples = 4;
  82685. this._webVRCamera.attachPostProcess(this._postProcessMove);
  82686. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  82687. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  82688. });
  82689. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  82690. };
  82691. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit, gazer) {
  82692. if (hit.pickedPoint) {
  82693. if (gazer._teleportationRequestInitiated) {
  82694. this._displayTeleportationTarget();
  82695. this._haloCenter.copyFrom(hit.pickedPoint);
  82696. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  82697. }
  82698. var pickNormal = hit.getNormal(true, false);
  82699. if (pickNormal) {
  82700. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  82701. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  82702. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  82703. }
  82704. this._teleportationTarget.position.y += 0.1;
  82705. }
  82706. };
  82707. VRExperienceHelper.prototype._teleportCamera = function (location) {
  82708. var _this = this;
  82709. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  82710. return;
  82711. }
  82712. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  82713. // offset of the headset from the anchor.
  82714. if (this.webVRCamera.leftCamera) {
  82715. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  82716. this._workingVector.subtractInPlace(this.webVRCamera.position);
  82717. location.subtractToRef(this._workingVector, this._workingVector);
  82718. }
  82719. else {
  82720. this._workingVector.copyFrom(location);
  82721. }
  82722. // Add height to account for user's height offset
  82723. if (this.isInVRMode) {
  82724. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround() * this._webVRCamera.deviceScaleFactor;
  82725. }
  82726. else {
  82727. this._workingVector.y += this._defaultHeight;
  82728. }
  82729. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  82730. // Create animation from the camera's position to the new location
  82731. this.currentVRCamera.animations = [];
  82732. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  82733. var animationCameraTeleportationKeys = [{
  82734. frame: 0,
  82735. value: this.currentVRCamera.position
  82736. },
  82737. {
  82738. frame: 11,
  82739. value: this._workingVector
  82740. }
  82741. ];
  82742. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  82743. animationCameraTeleportation.setEasingFunction(this._circleEase);
  82744. this.currentVRCamera.animations.push(animationCameraTeleportation);
  82745. this._postProcessMove.animations = [];
  82746. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  82747. var vignetteWeightKeys = [];
  82748. vignetteWeightKeys.push({
  82749. frame: 0,
  82750. value: 0
  82751. });
  82752. vignetteWeightKeys.push({
  82753. frame: 5,
  82754. value: 8
  82755. });
  82756. vignetteWeightKeys.push({
  82757. frame: 11,
  82758. value: 0
  82759. });
  82760. animationPP.setKeys(vignetteWeightKeys);
  82761. this._postProcessMove.animations.push(animationPP);
  82762. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  82763. var vignetteStretchKeys = [];
  82764. vignetteStretchKeys.push({
  82765. frame: 0,
  82766. value: 0
  82767. });
  82768. vignetteStretchKeys.push({
  82769. frame: 5,
  82770. value: 10
  82771. });
  82772. vignetteStretchKeys.push({
  82773. frame: 11,
  82774. value: 0
  82775. });
  82776. animationPP2.setKeys(vignetteStretchKeys);
  82777. this._postProcessMove.animations.push(animationPP2);
  82778. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  82779. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  82780. this._webVRCamera.attachPostProcess(this._postProcessMove);
  82781. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  82782. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  82783. });
  82784. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  82785. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  82786. });
  82787. this._hideTeleportationTarget();
  82788. };
  82789. VRExperienceHelper.prototype._castRayAndSelectObject = function (gazer) {
  82790. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  82791. return;
  82792. }
  82793. var hit = this._scene.pickWithRay(gazer._getForwardRay(this._rayLength), this._raySelectionPredicate);
  82794. // Moving the gazeTracker on the mesh face targetted
  82795. if (hit && hit.pickedPoint) {
  82796. if (this._displayGaze) {
  82797. var multiplier = 1;
  82798. gazer._gazeTracker.isVisible = true;
  82799. if (gazer._isActionableMesh) {
  82800. multiplier = 3;
  82801. }
  82802. gazer._gazeTracker.scaling.x = hit.distance * multiplier;
  82803. gazer._gazeTracker.scaling.y = hit.distance * multiplier;
  82804. gazer._gazeTracker.scaling.z = hit.distance * multiplier;
  82805. var pickNormal = hit.getNormal();
  82806. // To avoid z-fighting
  82807. var deltaFighting = 0.002;
  82808. if (pickNormal) {
  82809. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  82810. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  82811. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, gazer._gazeTracker.rotation);
  82812. }
  82813. gazer._gazeTracker.position.copyFrom(hit.pickedPoint);
  82814. if (gazer._gazeTracker.position.x < 0) {
  82815. gazer._gazeTracker.position.x += deltaFighting;
  82816. }
  82817. else {
  82818. gazer._gazeTracker.position.x -= deltaFighting;
  82819. }
  82820. if (gazer._gazeTracker.position.y < 0) {
  82821. gazer._gazeTracker.position.y += deltaFighting;
  82822. }
  82823. else {
  82824. gazer._gazeTracker.position.y -= deltaFighting;
  82825. }
  82826. if (gazer._gazeTracker.position.z < 0) {
  82827. gazer._gazeTracker.position.z += deltaFighting;
  82828. }
  82829. else {
  82830. gazer._gazeTracker.position.z -= deltaFighting;
  82831. }
  82832. }
  82833. // Changing the size of the laser pointer based on the distance from the targetted point
  82834. gazer._updatePointerDistance(hit.distance);
  82835. }
  82836. else {
  82837. gazer._gazeTracker.isVisible = false;
  82838. }
  82839. if (hit && hit.pickedMesh) {
  82840. gazer._currentHit = hit;
  82841. if (gazer._pointerDownOnMeshAsked) {
  82842. this._scene.simulatePointerMove(gazer._currentHit, { pointerId: gazer._id });
  82843. }
  82844. // The object selected is the floor, we're in a teleportation scenario
  82845. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  82846. // Moving the teleportation area to this targetted point
  82847. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  82848. if (gazer._currentMeshSelected && !this._isTeleportationFloor(gazer._currentMeshSelected)) {
  82849. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  82850. }
  82851. gazer._currentMeshSelected = null;
  82852. if (gazer._teleportationRequestInitiated) {
  82853. this._moveTeleportationSelectorTo(hit, gazer);
  82854. }
  82855. return;
  82856. }
  82857. // If not, we're in a selection scenario
  82858. //this._teleportationAllowed = false;
  82859. if (hit.pickedMesh !== gazer._currentMeshSelected) {
  82860. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  82861. this.onNewMeshPicked.notifyObservers(hit);
  82862. gazer._currentMeshSelected = hit.pickedMesh;
  82863. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  82864. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  82865. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  82866. gazer._isActionableMesh = true;
  82867. }
  82868. else {
  82869. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  82870. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  82871. gazer._isActionableMesh = false;
  82872. }
  82873. try {
  82874. this.onNewMeshSelected.notifyObservers(hit.pickedMesh);
  82875. }
  82876. catch (err) {
  82877. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  82878. }
  82879. }
  82880. else {
  82881. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  82882. gazer._currentMeshSelected = null;
  82883. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  82884. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  82885. }
  82886. }
  82887. }
  82888. else {
  82889. gazer._currentHit = null;
  82890. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  82891. gazer._currentMeshSelected = null;
  82892. //this._teleportationAllowed = false;
  82893. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  82894. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  82895. }
  82896. };
  82897. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function (mesh) {
  82898. if (mesh) {
  82899. this.onSelectedMeshUnselected.notifyObservers(mesh);
  82900. }
  82901. };
  82902. /**
  82903. * Sets the color of the laser ray from the vr controllers.
  82904. * @param color new color for the ray.
  82905. */
  82906. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  82907. if (this.leftController) {
  82908. this.leftController._setLaserPointerColor(color);
  82909. }
  82910. if (this.rightController) {
  82911. this.rightController._setLaserPointerColor(color);
  82912. }
  82913. };
  82914. /**
  82915. * Sets the color of the ray from the vr headsets gaze.
  82916. * @param color new color for the ray.
  82917. */
  82918. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  82919. if (!this._cameraGazer._gazeTracker.material) {
  82920. return;
  82921. }
  82922. this._cameraGazer._gazeTracker.material.emissiveColor = color;
  82923. if (this.leftController) {
  82924. this.leftController._gazeTracker.material.emissiveColor = color;
  82925. }
  82926. if (this.rightController) {
  82927. this.rightController._gazeTracker.material.emissiveColor = color;
  82928. }
  82929. };
  82930. /**
  82931. * Exits VR and disposes of the vr experience helper
  82932. */
  82933. VRExperienceHelper.prototype.dispose = function () {
  82934. if (this.isInVRMode) {
  82935. this.exitVR();
  82936. }
  82937. if (this._postProcessMove) {
  82938. this._postProcessMove.dispose();
  82939. }
  82940. if (this._webVRCamera) {
  82941. this._webVRCamera.dispose();
  82942. }
  82943. if (this._vrDeviceOrientationCamera) {
  82944. this._vrDeviceOrientationCamera.dispose();
  82945. }
  82946. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  82947. document.body.removeChild(this._btnVR);
  82948. }
  82949. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  82950. this._deviceOrientationCamera.dispose();
  82951. }
  82952. if (this._cameraGazer) {
  82953. this._cameraGazer.dispose();
  82954. }
  82955. if (this.leftController) {
  82956. this.leftController.dispose();
  82957. }
  82958. if (this.rightController) {
  82959. this.rightController.dispose();
  82960. }
  82961. if (this._teleportationTarget) {
  82962. this._teleportationTarget.dispose();
  82963. }
  82964. this._floorMeshesCollection = [];
  82965. document.removeEventListener("keydown", this._onKeyDown);
  82966. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  82967. window.removeEventListener("resize", this._onResize);
  82968. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  82969. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  82970. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  82971. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  82972. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  82973. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  82974. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  82975. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  82976. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  82977. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  82978. this._scene.unregisterBeforeRender(this.beforeRender);
  82979. };
  82980. /**
  82981. * Gets the name of the VRExperienceHelper class
  82982. * @returns "VRExperienceHelper"
  82983. */
  82984. VRExperienceHelper.prototype.getClassName = function () {
  82985. return "VRExperienceHelper";
  82986. };
  82987. return VRExperienceHelper;
  82988. }());
  82989. BABYLON.VRExperienceHelper = VRExperienceHelper;
  82990. })(BABYLON || (BABYLON = {}));
  82991. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  82992. // Mainly based on these 2 articles :
  82993. // 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
  82994. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  82995. var BABYLON;
  82996. (function (BABYLON) {
  82997. var JoystickAxis;
  82998. (function (JoystickAxis) {
  82999. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  83000. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  83001. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  83002. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  83003. var VirtualJoystick = /** @class */ (function () {
  83004. function VirtualJoystick(leftJoystick) {
  83005. var _this = this;
  83006. if (leftJoystick) {
  83007. this._leftJoystick = true;
  83008. }
  83009. else {
  83010. this._leftJoystick = false;
  83011. }
  83012. VirtualJoystick._globalJoystickIndex++;
  83013. // By default left & right arrow keys are moving the X
  83014. // and up & down keys are moving the Y
  83015. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  83016. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  83017. this.reverseLeftRight = false;
  83018. this.reverseUpDown = false;
  83019. // collections of pointers
  83020. this._touches = new BABYLON.StringDictionary();
  83021. this.deltaPosition = BABYLON.Vector3.Zero();
  83022. this._joystickSensibility = 25;
  83023. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  83024. this._onResize = function (evt) {
  83025. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  83026. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  83027. if (VirtualJoystick.vjCanvas) {
  83028. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  83029. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  83030. }
  83031. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  83032. };
  83033. // injecting a canvas element on top of the canvas 3D game
  83034. if (!VirtualJoystick.vjCanvas) {
  83035. window.addEventListener("resize", this._onResize, false);
  83036. VirtualJoystick.vjCanvas = document.createElement("canvas");
  83037. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  83038. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  83039. VirtualJoystick.vjCanvas.width = window.innerWidth;
  83040. VirtualJoystick.vjCanvas.height = window.innerHeight;
  83041. VirtualJoystick.vjCanvas.style.width = "100%";
  83042. VirtualJoystick.vjCanvas.style.height = "100%";
  83043. VirtualJoystick.vjCanvas.style.position = "absolute";
  83044. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  83045. VirtualJoystick.vjCanvas.style.top = "0px";
  83046. VirtualJoystick.vjCanvas.style.left = "0px";
  83047. VirtualJoystick.vjCanvas.style.zIndex = "5";
  83048. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  83049. // Support for jQuery PEP polyfill
  83050. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  83051. var context = VirtualJoystick.vjCanvas.getContext('2d');
  83052. if (!context) {
  83053. throw new Error("Unable to create canvas for virtual joystick");
  83054. }
  83055. VirtualJoystick.vjCanvasContext = context;
  83056. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  83057. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  83058. document.body.appendChild(VirtualJoystick.vjCanvas);
  83059. }
  83060. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  83061. this.pressed = false;
  83062. // default joystick color
  83063. this._joystickColor = "cyan";
  83064. this._joystickPointerID = -1;
  83065. // current joystick position
  83066. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  83067. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  83068. // origin joystick position
  83069. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  83070. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  83071. this._onPointerDownHandlerRef = function (evt) {
  83072. _this._onPointerDown(evt);
  83073. };
  83074. this._onPointerMoveHandlerRef = function (evt) {
  83075. _this._onPointerMove(evt);
  83076. };
  83077. this._onPointerUpHandlerRef = function (evt) {
  83078. _this._onPointerUp(evt);
  83079. };
  83080. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  83081. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  83082. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  83083. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  83084. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  83085. evt.preventDefault(); // Disables system menu
  83086. }, false);
  83087. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  83088. }
  83089. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  83090. this._joystickSensibility = newJoystickSensibility;
  83091. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  83092. };
  83093. VirtualJoystick.prototype._onPointerDown = function (e) {
  83094. var positionOnScreenCondition;
  83095. e.preventDefault();
  83096. if (this._leftJoystick === true) {
  83097. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  83098. }
  83099. else {
  83100. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  83101. }
  83102. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  83103. // First contact will be dedicated to the virtual joystick
  83104. this._joystickPointerID = e.pointerId;
  83105. this._joystickPointerStartPos.x = e.clientX;
  83106. this._joystickPointerStartPos.y = e.clientY;
  83107. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  83108. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  83109. this._deltaJoystickVector.x = 0;
  83110. this._deltaJoystickVector.y = 0;
  83111. this.pressed = true;
  83112. this._touches.add(e.pointerId.toString(), e);
  83113. }
  83114. else {
  83115. // You can only trigger the action buttons with a joystick declared
  83116. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  83117. this._action();
  83118. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  83119. }
  83120. }
  83121. };
  83122. VirtualJoystick.prototype._onPointerMove = function (e) {
  83123. // If the current pointer is the one associated to the joystick (first touch contact)
  83124. if (this._joystickPointerID == e.pointerId) {
  83125. this._joystickPointerPos.x = e.clientX;
  83126. this._joystickPointerPos.y = e.clientY;
  83127. this._deltaJoystickVector = this._joystickPointerPos.clone();
  83128. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  83129. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  83130. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  83131. switch (this._axisTargetedByLeftAndRight) {
  83132. case JoystickAxis.X:
  83133. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  83134. break;
  83135. case JoystickAxis.Y:
  83136. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  83137. break;
  83138. case JoystickAxis.Z:
  83139. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  83140. break;
  83141. }
  83142. var directionUpDown = this.reverseUpDown ? 1 : -1;
  83143. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  83144. switch (this._axisTargetedByUpAndDown) {
  83145. case JoystickAxis.X:
  83146. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  83147. break;
  83148. case JoystickAxis.Y:
  83149. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  83150. break;
  83151. case JoystickAxis.Z:
  83152. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  83153. break;
  83154. }
  83155. }
  83156. else {
  83157. var data = this._touches.get(e.pointerId.toString());
  83158. if (data) {
  83159. data.x = e.clientX;
  83160. data.y = e.clientY;
  83161. }
  83162. }
  83163. };
  83164. VirtualJoystick.prototype._onPointerUp = function (e) {
  83165. if (this._joystickPointerID == e.pointerId) {
  83166. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  83167. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  83168. this._joystickPointerID = -1;
  83169. this.pressed = false;
  83170. }
  83171. else {
  83172. var touch = this._touches.get(e.pointerId.toString());
  83173. if (touch) {
  83174. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  83175. }
  83176. }
  83177. this._deltaJoystickVector.x = 0;
  83178. this._deltaJoystickVector.y = 0;
  83179. this._touches.remove(e.pointerId.toString());
  83180. };
  83181. /**
  83182. * Change the color of the virtual joystick
  83183. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  83184. */
  83185. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  83186. this._joystickColor = newColor;
  83187. };
  83188. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  83189. this._action = action;
  83190. };
  83191. // Define which axis you'd like to control for left & right
  83192. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  83193. switch (axis) {
  83194. case JoystickAxis.X:
  83195. case JoystickAxis.Y:
  83196. case JoystickAxis.Z:
  83197. this._axisTargetedByLeftAndRight = axis;
  83198. break;
  83199. default:
  83200. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  83201. break;
  83202. }
  83203. };
  83204. // Define which axis you'd like to control for up & down
  83205. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  83206. switch (axis) {
  83207. case JoystickAxis.X:
  83208. case JoystickAxis.Y:
  83209. case JoystickAxis.Z:
  83210. this._axisTargetedByUpAndDown = axis;
  83211. break;
  83212. default:
  83213. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  83214. break;
  83215. }
  83216. };
  83217. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  83218. var _this = this;
  83219. if (this.pressed) {
  83220. this._touches.forEach(function (key, touch) {
  83221. if (touch.pointerId === _this._joystickPointerID) {
  83222. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  83223. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  83224. VirtualJoystick.vjCanvasContext.beginPath();
  83225. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  83226. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  83227. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  83228. VirtualJoystick.vjCanvasContext.stroke();
  83229. VirtualJoystick.vjCanvasContext.closePath();
  83230. VirtualJoystick.vjCanvasContext.beginPath();
  83231. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  83232. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  83233. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  83234. VirtualJoystick.vjCanvasContext.stroke();
  83235. VirtualJoystick.vjCanvasContext.closePath();
  83236. VirtualJoystick.vjCanvasContext.beginPath();
  83237. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  83238. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  83239. VirtualJoystick.vjCanvasContext.stroke();
  83240. VirtualJoystick.vjCanvasContext.closePath();
  83241. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  83242. }
  83243. else {
  83244. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  83245. VirtualJoystick.vjCanvasContext.beginPath();
  83246. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  83247. VirtualJoystick.vjCanvasContext.beginPath();
  83248. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  83249. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  83250. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  83251. VirtualJoystick.vjCanvasContext.stroke();
  83252. VirtualJoystick.vjCanvasContext.closePath();
  83253. touch.prevX = touch.x;
  83254. touch.prevY = touch.y;
  83255. }
  83256. ;
  83257. });
  83258. }
  83259. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  83260. };
  83261. VirtualJoystick.prototype.releaseCanvas = function () {
  83262. if (VirtualJoystick.vjCanvas) {
  83263. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  83264. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  83265. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  83266. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  83267. window.removeEventListener("resize", this._onResize);
  83268. document.body.removeChild(VirtualJoystick.vjCanvas);
  83269. VirtualJoystick.vjCanvas = null;
  83270. }
  83271. };
  83272. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  83273. VirtualJoystick._globalJoystickIndex = 0;
  83274. return VirtualJoystick;
  83275. }());
  83276. BABYLON.VirtualJoystick = VirtualJoystick;
  83277. })(BABYLON || (BABYLON = {}));
  83278. //# sourceMappingURL=babylon.virtualJoystick.js.map
  83279. var BABYLON;
  83280. (function (BABYLON) {
  83281. // We're mainly based on the logic defined into the FreeCamera code
  83282. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  83283. __extends(VirtualJoysticksCamera, _super);
  83284. function VirtualJoysticksCamera(name, position, scene) {
  83285. var _this = _super.call(this, name, position, scene) || this;
  83286. _this.inputs.addVirtualJoystick();
  83287. return _this;
  83288. }
  83289. VirtualJoysticksCamera.prototype.getClassName = function () {
  83290. return "VirtualJoysticksCamera";
  83291. };
  83292. return VirtualJoysticksCamera;
  83293. }(BABYLON.FreeCamera));
  83294. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  83295. })(BABYLON || (BABYLON = {}));
  83296. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  83297. var BABYLON;
  83298. (function (BABYLON) {
  83299. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  83300. function FreeCameraVirtualJoystickInput() {
  83301. }
  83302. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  83303. return this._leftjoystick;
  83304. };
  83305. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  83306. return this._rightjoystick;
  83307. };
  83308. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  83309. if (this._leftjoystick) {
  83310. var camera = this.camera;
  83311. var speed = camera._computeLocalCameraSpeed() * 50;
  83312. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  83313. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  83314. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  83315. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  83316. if (!this._leftjoystick.pressed) {
  83317. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  83318. }
  83319. if (!this._rightjoystick.pressed) {
  83320. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  83321. }
  83322. }
  83323. };
  83324. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  83325. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  83326. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  83327. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  83328. this._leftjoystick.setJoystickSensibility(0.15);
  83329. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  83330. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  83331. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  83332. this._rightjoystick.reverseUpDown = true;
  83333. this._rightjoystick.setJoystickSensibility(0.05);
  83334. this._rightjoystick.setJoystickColor("yellow");
  83335. };
  83336. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  83337. this._leftjoystick.releaseCanvas();
  83338. this._rightjoystick.releaseCanvas();
  83339. };
  83340. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  83341. return "FreeCameraVirtualJoystickInput";
  83342. };
  83343. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  83344. return "virtualJoystick";
  83345. };
  83346. return FreeCameraVirtualJoystickInput;
  83347. }());
  83348. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  83349. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  83350. })(BABYLON || (BABYLON = {}));
  83351. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  83352. var BABYLON;
  83353. (function (BABYLON) {
  83354. var SimplificationSettings = /** @class */ (function () {
  83355. function SimplificationSettings(quality, distance, optimizeMesh) {
  83356. this.quality = quality;
  83357. this.distance = distance;
  83358. this.optimizeMesh = optimizeMesh;
  83359. }
  83360. return SimplificationSettings;
  83361. }());
  83362. BABYLON.SimplificationSettings = SimplificationSettings;
  83363. var SimplificationQueue = /** @class */ (function () {
  83364. function SimplificationQueue() {
  83365. this.running = false;
  83366. this._simplificationArray = [];
  83367. }
  83368. SimplificationQueue.prototype.addTask = function (task) {
  83369. this._simplificationArray.push(task);
  83370. };
  83371. SimplificationQueue.prototype.executeNext = function () {
  83372. var task = this._simplificationArray.pop();
  83373. if (task) {
  83374. this.running = true;
  83375. this.runSimplification(task);
  83376. }
  83377. else {
  83378. this.running = false;
  83379. }
  83380. };
  83381. SimplificationQueue.prototype.runSimplification = function (task) {
  83382. var _this = this;
  83383. if (task.parallelProcessing) {
  83384. //parallel simplifier
  83385. task.settings.forEach(function (setting) {
  83386. var simplifier = _this.getSimplifier(task);
  83387. simplifier.simplify(setting, function (newMesh) {
  83388. task.mesh.addLODLevel(setting.distance, newMesh);
  83389. newMesh.isVisible = true;
  83390. //check if it is the last
  83391. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  83392. //all done, run the success callback.
  83393. task.successCallback();
  83394. }
  83395. _this.executeNext();
  83396. });
  83397. });
  83398. }
  83399. else {
  83400. //single simplifier.
  83401. var simplifier = this.getSimplifier(task);
  83402. var runDecimation = function (setting, callback) {
  83403. simplifier.simplify(setting, function (newMesh) {
  83404. task.mesh.addLODLevel(setting.distance, newMesh);
  83405. newMesh.isVisible = true;
  83406. //run the next quality level
  83407. callback();
  83408. });
  83409. };
  83410. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  83411. runDecimation(task.settings[loop.index], function () {
  83412. loop.executeNext();
  83413. });
  83414. }, function () {
  83415. //execution ended, run the success callback.
  83416. if (task.successCallback) {
  83417. task.successCallback();
  83418. }
  83419. _this.executeNext();
  83420. });
  83421. }
  83422. };
  83423. SimplificationQueue.prototype.getSimplifier = function (task) {
  83424. switch (task.simplificationType) {
  83425. case SimplificationType.QUADRATIC:
  83426. default:
  83427. return new QuadraticErrorSimplification(task.mesh);
  83428. }
  83429. };
  83430. return SimplificationQueue;
  83431. }());
  83432. BABYLON.SimplificationQueue = SimplificationQueue;
  83433. /**
  83434. * The implemented types of simplification.
  83435. * At the moment only Quadratic Error Decimation is implemented.
  83436. */
  83437. var SimplificationType;
  83438. (function (SimplificationType) {
  83439. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  83440. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  83441. var DecimationTriangle = /** @class */ (function () {
  83442. function DecimationTriangle(vertices) {
  83443. this.vertices = vertices;
  83444. this.error = new Array(4);
  83445. this.deleted = false;
  83446. this.isDirty = false;
  83447. this.deletePending = false;
  83448. this.borderFactor = 0;
  83449. }
  83450. return DecimationTriangle;
  83451. }());
  83452. BABYLON.DecimationTriangle = DecimationTriangle;
  83453. var DecimationVertex = /** @class */ (function () {
  83454. function DecimationVertex(position, id) {
  83455. this.position = position;
  83456. this.id = id;
  83457. this.isBorder = true;
  83458. this.q = new QuadraticMatrix();
  83459. this.triangleCount = 0;
  83460. this.triangleStart = 0;
  83461. this.originalOffsets = [];
  83462. }
  83463. DecimationVertex.prototype.updatePosition = function (newPosition) {
  83464. this.position.copyFrom(newPosition);
  83465. };
  83466. return DecimationVertex;
  83467. }());
  83468. BABYLON.DecimationVertex = DecimationVertex;
  83469. var QuadraticMatrix = /** @class */ (function () {
  83470. function QuadraticMatrix(data) {
  83471. this.data = new Array(10);
  83472. for (var i = 0; i < 10; ++i) {
  83473. if (data && data[i]) {
  83474. this.data[i] = data[i];
  83475. }
  83476. else {
  83477. this.data[i] = 0;
  83478. }
  83479. }
  83480. }
  83481. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  83482. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  83483. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  83484. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  83485. return det;
  83486. };
  83487. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  83488. for (var i = 0; i < 10; ++i) {
  83489. this.data[i] += matrix.data[i];
  83490. }
  83491. };
  83492. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  83493. for (var i = 0; i < 10; ++i) {
  83494. this.data[i] += data[i];
  83495. }
  83496. };
  83497. QuadraticMatrix.prototype.add = function (matrix) {
  83498. var m = new QuadraticMatrix();
  83499. for (var i = 0; i < 10; ++i) {
  83500. m.data[i] = this.data[i] + matrix.data[i];
  83501. }
  83502. return m;
  83503. };
  83504. QuadraticMatrix.FromData = function (a, b, c, d) {
  83505. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  83506. };
  83507. //returning an array to avoid garbage collection
  83508. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  83509. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  83510. };
  83511. return QuadraticMatrix;
  83512. }());
  83513. BABYLON.QuadraticMatrix = QuadraticMatrix;
  83514. var Reference = /** @class */ (function () {
  83515. function Reference(vertexId, triangleId) {
  83516. this.vertexId = vertexId;
  83517. this.triangleId = triangleId;
  83518. }
  83519. return Reference;
  83520. }());
  83521. BABYLON.Reference = Reference;
  83522. /**
  83523. * An implementation of the Quadratic Error simplification algorithm.
  83524. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  83525. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  83526. * @author RaananW
  83527. */
  83528. var QuadraticErrorSimplification = /** @class */ (function () {
  83529. function QuadraticErrorSimplification(_mesh) {
  83530. this._mesh = _mesh;
  83531. this.syncIterations = 5000;
  83532. this.aggressiveness = 7;
  83533. this.decimationIterations = 100;
  83534. this.boundingBoxEpsilon = BABYLON.Epsilon;
  83535. }
  83536. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  83537. var _this = this;
  83538. this.initDecimatedMesh();
  83539. //iterating through the submeshes array, one after the other.
  83540. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  83541. _this.initWithMesh(loop.index, function () {
  83542. _this.runDecimation(settings, loop.index, function () {
  83543. loop.executeNext();
  83544. });
  83545. }, settings.optimizeMesh);
  83546. }, function () {
  83547. setTimeout(function () {
  83548. successCallback(_this._reconstructedMesh);
  83549. }, 0);
  83550. });
  83551. };
  83552. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  83553. var _this = this;
  83554. var targetCount = ~~(this.triangles.length * settings.quality);
  83555. var deletedTriangles = 0;
  83556. var triangleCount = this.triangles.length;
  83557. var iterationFunction = function (iteration, callback) {
  83558. setTimeout(function () {
  83559. if (iteration % 5 === 0) {
  83560. _this.updateMesh(iteration === 0);
  83561. }
  83562. for (var i = 0; i < _this.triangles.length; ++i) {
  83563. _this.triangles[i].isDirty = false;
  83564. }
  83565. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  83566. var trianglesIterator = function (i) {
  83567. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  83568. var t = _this.triangles[tIdx];
  83569. if (!t)
  83570. return;
  83571. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  83572. return;
  83573. }
  83574. for (var j = 0; j < 3; ++j) {
  83575. if (t.error[j] < threshold) {
  83576. var deleted0 = [];
  83577. var deleted1 = [];
  83578. var v0 = t.vertices[j];
  83579. var v1 = t.vertices[(j + 1) % 3];
  83580. if (v0.isBorder || v1.isBorder)
  83581. continue;
  83582. var p = BABYLON.Vector3.Zero();
  83583. var n = BABYLON.Vector3.Zero();
  83584. var uv = BABYLON.Vector2.Zero();
  83585. var color = new BABYLON.Color4(0, 0, 0, 1);
  83586. _this.calculateError(v0, v1, p, n, uv, color);
  83587. var delTr = new Array();
  83588. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  83589. continue;
  83590. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  83591. continue;
  83592. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  83593. continue;
  83594. var uniqueArray = new Array();
  83595. delTr.forEach(function (deletedT) {
  83596. if (uniqueArray.indexOf(deletedT) === -1) {
  83597. deletedT.deletePending = true;
  83598. uniqueArray.push(deletedT);
  83599. }
  83600. });
  83601. if (uniqueArray.length % 2 !== 0) {
  83602. continue;
  83603. }
  83604. v0.q = v1.q.add(v0.q);
  83605. v0.updatePosition(p);
  83606. var tStart = _this.references.length;
  83607. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  83608. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  83609. var tCount = _this.references.length - tStart;
  83610. if (tCount <= v0.triangleCount) {
  83611. if (tCount) {
  83612. for (var c = 0; c < tCount; c++) {
  83613. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  83614. }
  83615. }
  83616. }
  83617. else {
  83618. v0.triangleStart = tStart;
  83619. }
  83620. v0.triangleCount = tCount;
  83621. break;
  83622. }
  83623. }
  83624. };
  83625. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  83626. }, 0);
  83627. };
  83628. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  83629. if (triangleCount - deletedTriangles <= targetCount)
  83630. loop.breakLoop();
  83631. else {
  83632. iterationFunction(loop.index, function () {
  83633. loop.executeNext();
  83634. });
  83635. }
  83636. }, function () {
  83637. setTimeout(function () {
  83638. //reconstruct this part of the mesh
  83639. _this.reconstructMesh(submeshIndex);
  83640. successCallback();
  83641. }, 0);
  83642. });
  83643. };
  83644. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  83645. var _this = this;
  83646. this.vertices = [];
  83647. this.triangles = [];
  83648. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  83649. var indices = this._mesh.getIndices();
  83650. var submesh = this._mesh.subMeshes[submeshIndex];
  83651. var findInVertices = function (positionToSearch) {
  83652. if (optimizeMesh) {
  83653. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  83654. if (_this.vertices[ii].position.equals(positionToSearch)) {
  83655. return _this.vertices[ii];
  83656. }
  83657. }
  83658. }
  83659. return null;
  83660. };
  83661. var vertexReferences = [];
  83662. var vertexInit = function (i) {
  83663. if (!positionData) {
  83664. return;
  83665. }
  83666. var offset = i + submesh.verticesStart;
  83667. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  83668. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  83669. vertex.originalOffsets.push(offset);
  83670. if (vertex.id === _this.vertices.length) {
  83671. _this.vertices.push(vertex);
  83672. }
  83673. vertexReferences.push(vertex.id);
  83674. };
  83675. //var totalVertices = mesh.getTotalVertices();
  83676. var totalVertices = submesh.verticesCount;
  83677. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  83678. var indicesInit = function (i) {
  83679. if (!indices) {
  83680. return;
  83681. }
  83682. var offset = (submesh.indexStart / 3) + i;
  83683. var pos = (offset * 3);
  83684. var i0 = indices[pos + 0];
  83685. var i1 = indices[pos + 1];
  83686. var i2 = indices[pos + 2];
  83687. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  83688. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  83689. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  83690. var triangle = new DecimationTriangle([v0, v1, v2]);
  83691. triangle.originalOffset = pos;
  83692. _this.triangles.push(triangle);
  83693. };
  83694. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  83695. _this.init(callback);
  83696. });
  83697. });
  83698. };
  83699. QuadraticErrorSimplification.prototype.init = function (callback) {
  83700. var _this = this;
  83701. var triangleInit1 = function (i) {
  83702. var t = _this.triangles[i];
  83703. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  83704. for (var j = 0; j < 3; j++) {
  83705. 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))));
  83706. }
  83707. };
  83708. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  83709. var triangleInit2 = function (i) {
  83710. var t = _this.triangles[i];
  83711. for (var j = 0; j < 3; ++j) {
  83712. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  83713. }
  83714. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  83715. };
  83716. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  83717. callback();
  83718. });
  83719. });
  83720. };
  83721. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  83722. var newTriangles = [];
  83723. var i;
  83724. for (i = 0; i < this.vertices.length; ++i) {
  83725. this.vertices[i].triangleCount = 0;
  83726. }
  83727. var t;
  83728. var j;
  83729. for (i = 0; i < this.triangles.length; ++i) {
  83730. if (!this.triangles[i].deleted) {
  83731. t = this.triangles[i];
  83732. for (j = 0; j < 3; ++j) {
  83733. t.vertices[j].triangleCount = 1;
  83734. }
  83735. newTriangles.push(t);
  83736. }
  83737. }
  83738. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  83739. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  83740. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  83741. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  83742. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  83743. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  83744. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  83745. var vertexCount = 0;
  83746. for (i = 0; i < this.vertices.length; ++i) {
  83747. var vertex = this.vertices[i];
  83748. vertex.id = vertexCount;
  83749. if (vertex.triangleCount) {
  83750. vertex.originalOffsets.forEach(function (originalOffset) {
  83751. if (!normalData) {
  83752. return;
  83753. }
  83754. newPositionData.push(vertex.position.x);
  83755. newPositionData.push(vertex.position.y);
  83756. newPositionData.push(vertex.position.z);
  83757. newNormalData.push(normalData[originalOffset * 3]);
  83758. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  83759. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  83760. if (uvs && uvs.length) {
  83761. newUVsData.push(uvs[(originalOffset * 2)]);
  83762. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  83763. }
  83764. else if (colorsData && colorsData.length) {
  83765. newColorsData.push(colorsData[(originalOffset * 4)]);
  83766. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  83767. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  83768. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  83769. }
  83770. ++vertexCount;
  83771. });
  83772. }
  83773. }
  83774. var startingIndex = this._reconstructedMesh.getTotalIndices();
  83775. var startingVertex = this._reconstructedMesh.getTotalVertices();
  83776. var submeshesArray = this._reconstructedMesh.subMeshes;
  83777. this._reconstructedMesh.subMeshes = [];
  83778. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  83779. var originalIndices = this._mesh.getIndices();
  83780. for (i = 0; i < newTriangles.length; ++i) {
  83781. t = newTriangles[i]; //now get the new referencing point for each vertex
  83782. [0, 1, 2].forEach(function (idx) {
  83783. var id = originalIndices[t.originalOffset + idx];
  83784. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  83785. if (offset < 0)
  83786. offset = 0;
  83787. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  83788. });
  83789. }
  83790. //overwriting the old vertex buffers and indices.
  83791. this._reconstructedMesh.setIndices(newIndicesArray);
  83792. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  83793. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  83794. if (newUVsData.length > 0)
  83795. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  83796. if (newColorsData.length > 0)
  83797. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  83798. //create submesh
  83799. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  83800. if (submeshIndex > 0) {
  83801. this._reconstructedMesh.subMeshes = [];
  83802. submeshesArray.forEach(function (submesh) {
  83803. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  83804. });
  83805. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  83806. }
  83807. };
  83808. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  83809. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  83810. this._reconstructedMesh.material = this._mesh.material;
  83811. this._reconstructedMesh.parent = this._mesh.parent;
  83812. this._reconstructedMesh.isVisible = false;
  83813. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  83814. };
  83815. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  83816. for (var i = 0; i < vertex1.triangleCount; ++i) {
  83817. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  83818. if (t.deleted)
  83819. continue;
  83820. var s = this.references[vertex1.triangleStart + i].vertexId;
  83821. var v1 = t.vertices[(s + 1) % 3];
  83822. var v2 = t.vertices[(s + 2) % 3];
  83823. if ((v1 === vertex2 || v2 === vertex2)) {
  83824. deletedArray[i] = true;
  83825. delTr.push(t);
  83826. continue;
  83827. }
  83828. var d1 = v1.position.subtract(point);
  83829. d1 = d1.normalize();
  83830. var d2 = v2.position.subtract(point);
  83831. d2 = d2.normalize();
  83832. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  83833. return true;
  83834. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  83835. deletedArray[i] = false;
  83836. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  83837. return true;
  83838. }
  83839. return false;
  83840. };
  83841. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  83842. var newDeleted = deletedTriangles;
  83843. for (var i = 0; i < vertex.triangleCount; ++i) {
  83844. var ref = this.references[vertex.triangleStart + i];
  83845. var t = this.triangles[ref.triangleId];
  83846. if (t.deleted)
  83847. continue;
  83848. if (deletedArray[i] && t.deletePending) {
  83849. t.deleted = true;
  83850. newDeleted++;
  83851. continue;
  83852. }
  83853. t.vertices[ref.vertexId] = origVertex;
  83854. t.isDirty = true;
  83855. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  83856. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  83857. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  83858. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  83859. this.references.push(ref);
  83860. }
  83861. return newDeleted;
  83862. };
  83863. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  83864. for (var i = 0; i < this.vertices.length; ++i) {
  83865. var vCount = [];
  83866. var vId = [];
  83867. var v = this.vertices[i];
  83868. var j;
  83869. for (j = 0; j < v.triangleCount; ++j) {
  83870. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  83871. for (var ii = 0; ii < 3; ii++) {
  83872. var ofs = 0;
  83873. var vv = triangle.vertices[ii];
  83874. while (ofs < vCount.length) {
  83875. if (vId[ofs] === vv.id)
  83876. break;
  83877. ++ofs;
  83878. }
  83879. if (ofs === vCount.length) {
  83880. vCount.push(1);
  83881. vId.push(vv.id);
  83882. }
  83883. else {
  83884. vCount[ofs]++;
  83885. }
  83886. }
  83887. }
  83888. for (j = 0; j < vCount.length; ++j) {
  83889. if (vCount[j] === 1) {
  83890. this.vertices[vId[j]].isBorder = true;
  83891. }
  83892. else {
  83893. this.vertices[vId[j]].isBorder = false;
  83894. }
  83895. }
  83896. }
  83897. };
  83898. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  83899. if (identifyBorders === void 0) { identifyBorders = false; }
  83900. var i;
  83901. if (!identifyBorders) {
  83902. var newTrianglesVector = [];
  83903. for (i = 0; i < this.triangles.length; ++i) {
  83904. if (!this.triangles[i].deleted) {
  83905. newTrianglesVector.push(this.triangles[i]);
  83906. }
  83907. }
  83908. this.triangles = newTrianglesVector;
  83909. }
  83910. for (i = 0; i < this.vertices.length; ++i) {
  83911. this.vertices[i].triangleCount = 0;
  83912. this.vertices[i].triangleStart = 0;
  83913. }
  83914. var t;
  83915. var j;
  83916. var v;
  83917. for (i = 0; i < this.triangles.length; ++i) {
  83918. t = this.triangles[i];
  83919. for (j = 0; j < 3; ++j) {
  83920. v = t.vertices[j];
  83921. v.triangleCount++;
  83922. }
  83923. }
  83924. var tStart = 0;
  83925. for (i = 0; i < this.vertices.length; ++i) {
  83926. this.vertices[i].triangleStart = tStart;
  83927. tStart += this.vertices[i].triangleCount;
  83928. this.vertices[i].triangleCount = 0;
  83929. }
  83930. var newReferences = new Array(this.triangles.length * 3);
  83931. for (i = 0; i < this.triangles.length; ++i) {
  83932. t = this.triangles[i];
  83933. for (j = 0; j < 3; ++j) {
  83934. v = t.vertices[j];
  83935. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  83936. v.triangleCount++;
  83937. }
  83938. }
  83939. this.references = newReferences;
  83940. if (identifyBorders) {
  83941. this.identifyBorder();
  83942. }
  83943. };
  83944. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  83945. var x = point.x;
  83946. var y = point.y;
  83947. var z = point.z;
  83948. 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
  83949. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  83950. };
  83951. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  83952. var q = vertex1.q.add(vertex2.q);
  83953. var border = vertex1.isBorder && vertex2.isBorder;
  83954. var error = 0;
  83955. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  83956. if (qDet !== 0 && !border) {
  83957. if (!pointResult) {
  83958. pointResult = BABYLON.Vector3.Zero();
  83959. }
  83960. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  83961. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  83962. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  83963. error = this.vertexError(q, pointResult);
  83964. }
  83965. else {
  83966. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  83967. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  83968. var error1 = this.vertexError(q, vertex1.position);
  83969. var error2 = this.vertexError(q, vertex2.position);
  83970. var error3 = this.vertexError(q, p3);
  83971. error = Math.min(error1, error2, error3);
  83972. if (error === error1) {
  83973. if (pointResult) {
  83974. pointResult.copyFrom(vertex1.position);
  83975. }
  83976. }
  83977. else if (error === error2) {
  83978. if (pointResult) {
  83979. pointResult.copyFrom(vertex2.position);
  83980. }
  83981. }
  83982. else {
  83983. if (pointResult) {
  83984. pointResult.copyFrom(p3);
  83985. }
  83986. }
  83987. }
  83988. return error;
  83989. };
  83990. return QuadraticErrorSimplification;
  83991. }());
  83992. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  83993. })(BABYLON || (BABYLON = {}));
  83994. //# sourceMappingURL=babylon.meshSimplification.js.map
  83995. var BABYLON;
  83996. (function (BABYLON) {
  83997. var MeshLODLevel = /** @class */ (function () {
  83998. function MeshLODLevel(distance, mesh) {
  83999. this.distance = distance;
  84000. this.mesh = mesh;
  84001. }
  84002. return MeshLODLevel;
  84003. }());
  84004. BABYLON.MeshLODLevel = MeshLODLevel;
  84005. })(BABYLON || (BABYLON = {}));
  84006. //# sourceMappingURL=babylon.meshLODLevel.js.map
  84007. var BABYLON;
  84008. (function (BABYLON) {
  84009. /**
  84010. * Defines the root class used to create scene optimization to use with SceneOptimizer
  84011. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  84012. */
  84013. var SceneOptimization = /** @class */ (function () {
  84014. /**
  84015. * Creates the SceneOptimization object
  84016. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  84017. * @param desc defines the description associated with the optimization
  84018. */
  84019. function SceneOptimization(
  84020. /**
  84021. * Defines the priority of this optimization (0 by default which means first in the list)
  84022. */
  84023. priority) {
  84024. if (priority === void 0) { priority = 0; }
  84025. this.priority = priority;
  84026. }
  84027. /**
  84028. * Gets a string describing the action executed by the current optimization
  84029. * @returns description string
  84030. */
  84031. SceneOptimization.prototype.getDescription = function () {
  84032. return "";
  84033. };
  84034. /**
  84035. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  84036. * @param scene defines the current scene where to apply this optimization
  84037. * @param optimizer defines the current optimizer
  84038. * @returns true if everything that can be done was applied
  84039. */
  84040. SceneOptimization.prototype.apply = function (scene, optimizer) {
  84041. return true;
  84042. };
  84043. ;
  84044. return SceneOptimization;
  84045. }());
  84046. BABYLON.SceneOptimization = SceneOptimization;
  84047. /**
  84048. * Defines an optimization used to reduce the size of render target textures
  84049. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  84050. */
  84051. var TextureOptimization = /** @class */ (function (_super) {
  84052. __extends(TextureOptimization, _super);
  84053. /**
  84054. * Creates the TextureOptimization object
  84055. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  84056. * @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
  84057. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  84058. */
  84059. function TextureOptimization(
  84060. /**
  84061. * Defines the priority of this optimization (0 by default which means first in the list)
  84062. */
  84063. priority,
  84064. /**
  84065. * 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
  84066. */
  84067. maximumSize,
  84068. /**
  84069. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  84070. */
  84071. step) {
  84072. if (priority === void 0) { priority = 0; }
  84073. if (maximumSize === void 0) { maximumSize = 1024; }
  84074. if (step === void 0) { step = 0.5; }
  84075. var _this = _super.call(this, priority) || this;
  84076. _this.priority = priority;
  84077. _this.maximumSize = maximumSize;
  84078. _this.step = step;
  84079. return _this;
  84080. }
  84081. /**
  84082. * Gets a string describing the action executed by the current optimization
  84083. * @returns description string
  84084. */
  84085. TextureOptimization.prototype.getDescription = function () {
  84086. return "Reducing render target texture size to " + this.maximumSize;
  84087. };
  84088. /**
  84089. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  84090. * @param scene defines the current scene where to apply this optimization
  84091. * @param optimizer defines the current optimizer
  84092. * @returns true if everything that can be done was applied
  84093. */
  84094. TextureOptimization.prototype.apply = function (scene, optimizer) {
  84095. var allDone = true;
  84096. for (var index = 0; index < scene.textures.length; index++) {
  84097. var texture = scene.textures[index];
  84098. if (!texture.canRescale || texture.getContext) {
  84099. continue;
  84100. }
  84101. var currentSize = texture.getSize();
  84102. var maxDimension = Math.max(currentSize.width, currentSize.height);
  84103. if (maxDimension > this.maximumSize) {
  84104. texture.scale(this.step);
  84105. allDone = false;
  84106. }
  84107. }
  84108. return allDone;
  84109. };
  84110. return TextureOptimization;
  84111. }(SceneOptimization));
  84112. BABYLON.TextureOptimization = TextureOptimization;
  84113. /**
  84114. * Defines an optimization used to increase or decrease the rendering resolution
  84115. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  84116. */
  84117. var HardwareScalingOptimization = /** @class */ (function (_super) {
  84118. __extends(HardwareScalingOptimization, _super);
  84119. /**
  84120. * Creates the HardwareScalingOptimization object
  84121. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  84122. * @param maximumScale defines the maximum scale to use (2 by default)
  84123. * @param step defines the step to use between two passes (0.5 by default)
  84124. */
  84125. function HardwareScalingOptimization(
  84126. /**
  84127. * Defines the priority of this optimization (0 by default which means first in the list)
  84128. */
  84129. priority,
  84130. /**
  84131. * Defines the maximum scale to use (2 by default)
  84132. */
  84133. maximumScale,
  84134. /**
  84135. * Defines the step to use between two passes (0.5 by default)
  84136. */
  84137. step) {
  84138. if (priority === void 0) { priority = 0; }
  84139. if (maximumScale === void 0) { maximumScale = 2; }
  84140. if (step === void 0) { step = 0.25; }
  84141. var _this = _super.call(this, priority) || this;
  84142. _this.priority = priority;
  84143. _this.maximumScale = maximumScale;
  84144. _this.step = step;
  84145. _this._currentScale = -1;
  84146. _this._directionOffset = 1;
  84147. return _this;
  84148. }
  84149. /**
  84150. * Gets a string describing the action executed by the current optimization
  84151. * @return description string
  84152. */
  84153. HardwareScalingOptimization.prototype.getDescription = function () {
  84154. return "Setting hardware scaling level to " + this._currentScale;
  84155. };
  84156. /**
  84157. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  84158. * @param scene defines the current scene where to apply this optimization
  84159. * @param optimizer defines the current optimizer
  84160. * @returns true if everything that can be done was applied
  84161. */
  84162. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  84163. if (this._currentScale === -1) {
  84164. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  84165. if (this._currentScale > this.maximumScale) {
  84166. this._directionOffset = -1;
  84167. }
  84168. }
  84169. this._currentScale += this._directionOffset * this.step;
  84170. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  84171. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  84172. };
  84173. ;
  84174. return HardwareScalingOptimization;
  84175. }(SceneOptimization));
  84176. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  84177. /**
  84178. * Defines an optimization used to remove shadows
  84179. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  84180. */
  84181. var ShadowsOptimization = /** @class */ (function (_super) {
  84182. __extends(ShadowsOptimization, _super);
  84183. function ShadowsOptimization() {
  84184. return _super !== null && _super.apply(this, arguments) || this;
  84185. }
  84186. /**
  84187. * Gets a string describing the action executed by the current optimization
  84188. * @return description string
  84189. */
  84190. ShadowsOptimization.prototype.getDescription = function () {
  84191. return "Turning shadows on/off";
  84192. };
  84193. /**
  84194. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  84195. * @param scene defines the current scene where to apply this optimization
  84196. * @param optimizer defines the current optimizer
  84197. * @returns true if everything that can be done was applied
  84198. */
  84199. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  84200. scene.shadowsEnabled = optimizer.isInImprovementMode;
  84201. return true;
  84202. };
  84203. ;
  84204. return ShadowsOptimization;
  84205. }(SceneOptimization));
  84206. BABYLON.ShadowsOptimization = ShadowsOptimization;
  84207. /**
  84208. * Defines an optimization used to turn post-processes off
  84209. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  84210. */
  84211. var PostProcessesOptimization = /** @class */ (function (_super) {
  84212. __extends(PostProcessesOptimization, _super);
  84213. function PostProcessesOptimization() {
  84214. return _super !== null && _super.apply(this, arguments) || this;
  84215. }
  84216. /**
  84217. * Gets a string describing the action executed by the current optimization
  84218. * @return description string
  84219. */
  84220. PostProcessesOptimization.prototype.getDescription = function () {
  84221. return "Turning post-processes on/off";
  84222. };
  84223. /**
  84224. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  84225. * @param scene defines the current scene where to apply this optimization
  84226. * @param optimizer defines the current optimizer
  84227. * @returns true if everything that can be done was applied
  84228. */
  84229. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  84230. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  84231. return true;
  84232. };
  84233. ;
  84234. return PostProcessesOptimization;
  84235. }(SceneOptimization));
  84236. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  84237. /**
  84238. * Defines an optimization used to turn lens flares off
  84239. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  84240. */
  84241. var LensFlaresOptimization = /** @class */ (function (_super) {
  84242. __extends(LensFlaresOptimization, _super);
  84243. function LensFlaresOptimization() {
  84244. return _super !== null && _super.apply(this, arguments) || this;
  84245. }
  84246. /**
  84247. * Gets a string describing the action executed by the current optimization
  84248. * @return description string
  84249. */
  84250. LensFlaresOptimization.prototype.getDescription = function () {
  84251. return "Turning lens flares on/off";
  84252. };
  84253. /**
  84254. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  84255. * @param scene defines the current scene where to apply this optimization
  84256. * @param optimizer defines the current optimizer
  84257. * @returns true if everything that can be done was applied
  84258. */
  84259. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  84260. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  84261. return true;
  84262. };
  84263. ;
  84264. return LensFlaresOptimization;
  84265. }(SceneOptimization));
  84266. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  84267. /**
  84268. * Defines an optimization based on user defined callback.
  84269. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  84270. */
  84271. var CustomOptimization = /** @class */ (function (_super) {
  84272. __extends(CustomOptimization, _super);
  84273. function CustomOptimization() {
  84274. return _super !== null && _super.apply(this, arguments) || this;
  84275. }
  84276. /**
  84277. * Gets a string describing the action executed by the current optimization
  84278. * @returns description string
  84279. */
  84280. CustomOptimization.prototype.getDescription = function () {
  84281. if (this.onGetDescription) {
  84282. return this.onGetDescription();
  84283. }
  84284. return "Running user defined callback";
  84285. };
  84286. /**
  84287. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  84288. * @param scene defines the current scene where to apply this optimization
  84289. * @param optimizer defines the current optimizer
  84290. * @returns true if everything that can be done was applied
  84291. */
  84292. CustomOptimization.prototype.apply = function (scene, optimizer) {
  84293. if (this.onApply) {
  84294. return this.onApply(scene, optimizer);
  84295. }
  84296. return true;
  84297. };
  84298. ;
  84299. return CustomOptimization;
  84300. }(SceneOptimization));
  84301. BABYLON.CustomOptimization = CustomOptimization;
  84302. /**
  84303. * Defines an optimization used to turn particles off
  84304. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  84305. */
  84306. var ParticlesOptimization = /** @class */ (function (_super) {
  84307. __extends(ParticlesOptimization, _super);
  84308. function ParticlesOptimization() {
  84309. return _super !== null && _super.apply(this, arguments) || this;
  84310. }
  84311. /**
  84312. * Gets a string describing the action executed by the current optimization
  84313. * @return description string
  84314. */
  84315. ParticlesOptimization.prototype.getDescription = function () {
  84316. return "Turning particles on/off";
  84317. };
  84318. /**
  84319. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  84320. * @param scene defines the current scene where to apply this optimization
  84321. * @param optimizer defines the current optimizer
  84322. * @returns true if everything that can be done was applied
  84323. */
  84324. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  84325. scene.particlesEnabled = optimizer.isInImprovementMode;
  84326. return true;
  84327. };
  84328. ;
  84329. return ParticlesOptimization;
  84330. }(SceneOptimization));
  84331. BABYLON.ParticlesOptimization = ParticlesOptimization;
  84332. /**
  84333. * Defines an optimization used to turn render targets off
  84334. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  84335. */
  84336. var RenderTargetsOptimization = /** @class */ (function (_super) {
  84337. __extends(RenderTargetsOptimization, _super);
  84338. function RenderTargetsOptimization() {
  84339. return _super !== null && _super.apply(this, arguments) || this;
  84340. }
  84341. /**
  84342. * Gets a string describing the action executed by the current optimization
  84343. * @return description string
  84344. */
  84345. RenderTargetsOptimization.prototype.getDescription = function () {
  84346. return "Turning render targets off";
  84347. };
  84348. /**
  84349. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  84350. * @param scene defines the current scene where to apply this optimization
  84351. * @param optimizer defines the current optimizer
  84352. * @returns true if everything that can be done was applied
  84353. */
  84354. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  84355. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  84356. return true;
  84357. };
  84358. ;
  84359. return RenderTargetsOptimization;
  84360. }(SceneOptimization));
  84361. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  84362. /**
  84363. * Defines an optimization used to merge meshes with compatible materials
  84364. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  84365. */
  84366. var MergeMeshesOptimization = /** @class */ (function (_super) {
  84367. __extends(MergeMeshesOptimization, _super);
  84368. function MergeMeshesOptimization() {
  84369. var _this = _super !== null && _super.apply(this, arguments) || this;
  84370. _this._canBeMerged = function (abstractMesh) {
  84371. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  84372. return false;
  84373. }
  84374. var mesh = abstractMesh;
  84375. if (!mesh.isVisible || !mesh.isEnabled()) {
  84376. return false;
  84377. }
  84378. if (mesh.instances.length > 0) {
  84379. return false;
  84380. }
  84381. if (mesh.skeleton || mesh.hasLODLevels) {
  84382. return false;
  84383. }
  84384. if (mesh.parent) {
  84385. return false;
  84386. }
  84387. return true;
  84388. };
  84389. return _this;
  84390. }
  84391. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  84392. /**
  84393. * Gets or sets a boolean which defines if optimization octree has to be updated
  84394. */
  84395. get: function () {
  84396. return MergeMeshesOptimization._UpdateSelectionTree;
  84397. },
  84398. /**
  84399. * Gets or sets a boolean which defines if optimization octree has to be updated
  84400. */
  84401. set: function (value) {
  84402. MergeMeshesOptimization._UpdateSelectionTree = value;
  84403. },
  84404. enumerable: true,
  84405. configurable: true
  84406. });
  84407. /**
  84408. * Gets a string describing the action executed by the current optimization
  84409. * @return description string
  84410. */
  84411. MergeMeshesOptimization.prototype.getDescription = function () {
  84412. return "Merging similar meshes together";
  84413. };
  84414. /**
  84415. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  84416. * @param scene defines the current scene where to apply this optimization
  84417. * @param optimizer defines the current optimizer
  84418. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  84419. * @returns true if everything that can be done was applied
  84420. */
  84421. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  84422. var globalPool = scene.meshes.slice(0);
  84423. var globalLength = globalPool.length;
  84424. for (var index = 0; index < globalLength; index++) {
  84425. var currentPool = new Array();
  84426. var current = globalPool[index];
  84427. // Checks
  84428. if (!this._canBeMerged(current)) {
  84429. continue;
  84430. }
  84431. currentPool.push(current);
  84432. // Find compatible meshes
  84433. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  84434. var otherMesh = globalPool[subIndex];
  84435. if (!this._canBeMerged(otherMesh)) {
  84436. continue;
  84437. }
  84438. if (otherMesh.material !== current.material) {
  84439. continue;
  84440. }
  84441. if (otherMesh.checkCollisions !== current.checkCollisions) {
  84442. continue;
  84443. }
  84444. currentPool.push(otherMesh);
  84445. globalLength--;
  84446. globalPool.splice(subIndex, 1);
  84447. subIndex--;
  84448. }
  84449. if (currentPool.length < 2) {
  84450. continue;
  84451. }
  84452. // Merge meshes
  84453. BABYLON.Mesh.MergeMeshes(currentPool);
  84454. }
  84455. if (updateSelectionTree != undefined) {
  84456. if (updateSelectionTree) {
  84457. scene.createOrUpdateSelectionOctree();
  84458. }
  84459. }
  84460. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  84461. scene.createOrUpdateSelectionOctree();
  84462. }
  84463. return true;
  84464. };
  84465. ;
  84466. MergeMeshesOptimization._UpdateSelectionTree = false;
  84467. return MergeMeshesOptimization;
  84468. }(SceneOptimization));
  84469. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  84470. /**
  84471. * Defines a list of options used by SceneOptimizer
  84472. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  84473. */
  84474. var SceneOptimizerOptions = /** @class */ (function () {
  84475. /**
  84476. * Creates a new list of options used by SceneOptimizer
  84477. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  84478. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  84479. */
  84480. function SceneOptimizerOptions(
  84481. /**
  84482. * Defines the target frame rate to reach (60 by default)
  84483. */
  84484. targetFrameRate,
  84485. /**
  84486. * Defines the interval between two checkes (2000ms by default)
  84487. */
  84488. trackerDuration) {
  84489. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  84490. if (trackerDuration === void 0) { trackerDuration = 2000; }
  84491. this.targetFrameRate = targetFrameRate;
  84492. this.trackerDuration = trackerDuration;
  84493. /**
  84494. * Gets the list of optimizations to apply
  84495. */
  84496. this.optimizations = new Array();
  84497. }
  84498. /**
  84499. * Add a new optimization
  84500. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  84501. * @returns the current SceneOptimizerOptions
  84502. */
  84503. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  84504. this.optimizations.push(optimization);
  84505. return this;
  84506. };
  84507. /**
  84508. * Add a new custom optimization
  84509. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  84510. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  84511. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  84512. * @returns the current SceneOptimizerOptions
  84513. */
  84514. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  84515. if (priority === void 0) { priority = 0; }
  84516. var optimization = new CustomOptimization(priority);
  84517. optimization.onApply = onApply;
  84518. optimization.onGetDescription = onGetDescription;
  84519. this.optimizations.push(optimization);
  84520. return this;
  84521. };
  84522. /**
  84523. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  84524. * @param targetFrameRate defines the target frame rate (60 by default)
  84525. * @returns a SceneOptimizerOptions object
  84526. */
  84527. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  84528. var result = new SceneOptimizerOptions(targetFrameRate);
  84529. var priority = 0;
  84530. result.addOptimization(new MergeMeshesOptimization(priority));
  84531. result.addOptimization(new ShadowsOptimization(priority));
  84532. result.addOptimization(new LensFlaresOptimization(priority));
  84533. // Next priority
  84534. priority++;
  84535. result.addOptimization(new PostProcessesOptimization(priority));
  84536. result.addOptimization(new ParticlesOptimization(priority));
  84537. // Next priority
  84538. priority++;
  84539. result.addOptimization(new TextureOptimization(priority, 1024));
  84540. return result;
  84541. };
  84542. /**
  84543. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  84544. * @param targetFrameRate defines the target frame rate (60 by default)
  84545. * @returns a SceneOptimizerOptions object
  84546. */
  84547. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  84548. var result = new SceneOptimizerOptions(targetFrameRate);
  84549. var priority = 0;
  84550. result.addOptimization(new MergeMeshesOptimization(priority));
  84551. result.addOptimization(new ShadowsOptimization(priority));
  84552. result.addOptimization(new LensFlaresOptimization(priority));
  84553. // Next priority
  84554. priority++;
  84555. result.addOptimization(new PostProcessesOptimization(priority));
  84556. result.addOptimization(new ParticlesOptimization(priority));
  84557. // Next priority
  84558. priority++;
  84559. result.addOptimization(new TextureOptimization(priority, 512));
  84560. // Next priority
  84561. priority++;
  84562. result.addOptimization(new RenderTargetsOptimization(priority));
  84563. // Next priority
  84564. priority++;
  84565. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  84566. return result;
  84567. };
  84568. /**
  84569. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  84570. * @param targetFrameRate defines the target frame rate (60 by default)
  84571. * @returns a SceneOptimizerOptions object
  84572. */
  84573. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  84574. var result = new SceneOptimizerOptions(targetFrameRate);
  84575. var priority = 0;
  84576. result.addOptimization(new MergeMeshesOptimization(priority));
  84577. result.addOptimization(new ShadowsOptimization(priority));
  84578. result.addOptimization(new LensFlaresOptimization(priority));
  84579. // Next priority
  84580. priority++;
  84581. result.addOptimization(new PostProcessesOptimization(priority));
  84582. result.addOptimization(new ParticlesOptimization(priority));
  84583. // Next priority
  84584. priority++;
  84585. result.addOptimization(new TextureOptimization(priority, 256));
  84586. // Next priority
  84587. priority++;
  84588. result.addOptimization(new RenderTargetsOptimization(priority));
  84589. // Next priority
  84590. priority++;
  84591. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  84592. return result;
  84593. };
  84594. return SceneOptimizerOptions;
  84595. }());
  84596. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  84597. /**
  84598. * Class used to run optimizations in order to reach a target frame rate
  84599. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  84600. */
  84601. var SceneOptimizer = /** @class */ (function () {
  84602. /**
  84603. * Creates a new SceneOptimizer
  84604. * @param scene defines the scene to work on
  84605. * @param options defines the options to use with the SceneOptimizer
  84606. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  84607. * @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)
  84608. */
  84609. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  84610. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  84611. if (improvementMode === void 0) { improvementMode = false; }
  84612. var _this = this;
  84613. this._isRunning = false;
  84614. this._currentPriorityLevel = 0;
  84615. this._targetFrameRate = 60;
  84616. this._trackerDuration = 2000;
  84617. this._currentFrameRate = 0;
  84618. this._improvementMode = false;
  84619. /**
  84620. * Defines an observable called when the optimizer reaches the target frame rate
  84621. */
  84622. this.onSuccessObservable = new BABYLON.Observable();
  84623. /**
  84624. * Defines an observable called when the optimizer enables an optimization
  84625. */
  84626. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  84627. /**
  84628. * Defines an observable called when the optimizer is not able to reach the target frame rate
  84629. */
  84630. this.onFailureObservable = new BABYLON.Observable();
  84631. if (!options) {
  84632. this._options = new SceneOptimizerOptions();
  84633. }
  84634. else {
  84635. this._options = options;
  84636. }
  84637. if (this._options.targetFrameRate) {
  84638. this._targetFrameRate = this._options.targetFrameRate;
  84639. }
  84640. if (this._options.trackerDuration) {
  84641. this._trackerDuration = this._options.trackerDuration;
  84642. }
  84643. if (autoGeneratePriorities) {
  84644. var priority = 0;
  84645. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  84646. var optim = _a[_i];
  84647. optim.priority = priority++;
  84648. }
  84649. }
  84650. this._improvementMode = improvementMode;
  84651. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  84652. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  84653. _this._sceneDisposeObserver = null;
  84654. _this.dispose();
  84655. });
  84656. }
  84657. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  84658. /**
  84659. * Gets a boolean indicating if the optimizer is in improvement mode
  84660. */
  84661. get: function () {
  84662. return this._improvementMode;
  84663. },
  84664. enumerable: true,
  84665. configurable: true
  84666. });
  84667. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  84668. /**
  84669. * Gets the current priority level (0 at start)
  84670. */
  84671. get: function () {
  84672. return this._currentPriorityLevel;
  84673. },
  84674. enumerable: true,
  84675. configurable: true
  84676. });
  84677. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  84678. /**
  84679. * Gets the current frame rate checked by the SceneOptimizer
  84680. */
  84681. get: function () {
  84682. return this._currentFrameRate;
  84683. },
  84684. enumerable: true,
  84685. configurable: true
  84686. });
  84687. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  84688. /**
  84689. * Gets or sets the current target frame rate (60 by default)
  84690. */
  84691. get: function () {
  84692. return this._targetFrameRate;
  84693. },
  84694. /**
  84695. * Gets or sets the current target frame rate (60 by default)
  84696. */
  84697. set: function (value) {
  84698. this._targetFrameRate = value;
  84699. },
  84700. enumerable: true,
  84701. configurable: true
  84702. });
  84703. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  84704. /**
  84705. * Gets or sets the current interval between two checks (every 2000ms by default)
  84706. */
  84707. get: function () {
  84708. return this._trackerDuration;
  84709. },
  84710. /**
  84711. * Gets or sets the current interval between two checks (every 2000ms by default)
  84712. */
  84713. set: function (value) {
  84714. this._trackerDuration = value;
  84715. },
  84716. enumerable: true,
  84717. configurable: true
  84718. });
  84719. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  84720. /**
  84721. * Gets the list of active optimizations
  84722. */
  84723. get: function () {
  84724. return this._options.optimizations;
  84725. },
  84726. enumerable: true,
  84727. configurable: true
  84728. });
  84729. /**
  84730. * Stops the current optimizer
  84731. */
  84732. SceneOptimizer.prototype.stop = function () {
  84733. this._isRunning = false;
  84734. };
  84735. /**
  84736. * Reset the optimizer to initial step (current priority level = 0)
  84737. */
  84738. SceneOptimizer.prototype.reset = function () {
  84739. this._currentPriorityLevel = 0;
  84740. };
  84741. /**
  84742. * Start the optimizer. By default it will try to reach a specific framerate
  84743. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  84744. */
  84745. SceneOptimizer.prototype.start = function () {
  84746. var _this = this;
  84747. if (this._isRunning) {
  84748. return;
  84749. }
  84750. this._isRunning = true;
  84751. // Let's wait for the scene to be ready before running our check
  84752. this._scene.executeWhenReady(function () {
  84753. setTimeout(function () {
  84754. _this._checkCurrentState();
  84755. }, _this._trackerDuration);
  84756. });
  84757. };
  84758. SceneOptimizer.prototype._checkCurrentState = function () {
  84759. var _this = this;
  84760. if (!this._isRunning) {
  84761. return;
  84762. }
  84763. var scene = this._scene;
  84764. var options = this._options;
  84765. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  84766. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  84767. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  84768. this._isRunning = false;
  84769. this.onSuccessObservable.notifyObservers(this);
  84770. return;
  84771. }
  84772. // Apply current level of optimizations
  84773. var allDone = true;
  84774. var noOptimizationApplied = true;
  84775. for (var index = 0; index < options.optimizations.length; index++) {
  84776. var optimization = options.optimizations[index];
  84777. if (optimization.priority === this._currentPriorityLevel) {
  84778. noOptimizationApplied = false;
  84779. allDone = allDone && optimization.apply(scene, this);
  84780. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  84781. }
  84782. }
  84783. // If no optimization was applied, this is a failure :(
  84784. if (noOptimizationApplied) {
  84785. this._isRunning = false;
  84786. this.onFailureObservable.notifyObservers(this);
  84787. return;
  84788. }
  84789. // If all optimizations were done, move to next level
  84790. if (allDone) {
  84791. this._currentPriorityLevel++;
  84792. }
  84793. // Let's the system running for a specific amount of time before checking FPS
  84794. scene.executeWhenReady(function () {
  84795. setTimeout(function () {
  84796. _this._checkCurrentState();
  84797. }, _this._trackerDuration);
  84798. });
  84799. };
  84800. /**
  84801. * Release all resources
  84802. */
  84803. SceneOptimizer.prototype.dispose = function () {
  84804. this.stop();
  84805. this.onSuccessObservable.clear();
  84806. this.onFailureObservable.clear();
  84807. this.onNewOptimizationAppliedObservable.clear();
  84808. if (this._sceneDisposeObserver) {
  84809. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  84810. }
  84811. };
  84812. /**
  84813. * Helper function to create a SceneOptimizer with one single line of code
  84814. * @param scene defines the scene to work on
  84815. * @param options defines the options to use with the SceneOptimizer
  84816. * @param onSuccess defines a callback to call on success
  84817. * @param onFailure defines a callback to call on failure
  84818. * @returns the new SceneOptimizer object
  84819. */
  84820. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  84821. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  84822. if (onSuccess) {
  84823. optimizer.onSuccessObservable.add(function () {
  84824. onSuccess();
  84825. });
  84826. }
  84827. if (onFailure) {
  84828. optimizer.onFailureObservable.add(function () {
  84829. onFailure();
  84830. });
  84831. }
  84832. optimizer.start();
  84833. return optimizer;
  84834. };
  84835. return SceneOptimizer;
  84836. }());
  84837. BABYLON.SceneOptimizer = SceneOptimizer;
  84838. })(BABYLON || (BABYLON = {}));
  84839. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  84840. var BABYLON;
  84841. (function (BABYLON) {
  84842. var OutlineRenderer = /** @class */ (function () {
  84843. function OutlineRenderer(scene) {
  84844. this.zOffset = 1;
  84845. this._scene = scene;
  84846. }
  84847. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  84848. var _this = this;
  84849. if (useOverlay === void 0) { useOverlay = false; }
  84850. var scene = this._scene;
  84851. var engine = this._scene.getEngine();
  84852. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  84853. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  84854. return;
  84855. }
  84856. var mesh = subMesh.getRenderingMesh();
  84857. var material = subMesh.getMaterial();
  84858. if (!material || !scene.activeCamera) {
  84859. return;
  84860. }
  84861. engine.enableEffect(this._effect);
  84862. // Logarithmic depth
  84863. if (material.useLogarithmicDepth) {
  84864. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  84865. }
  84866. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  84867. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  84868. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  84869. // Bones
  84870. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  84871. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  84872. }
  84873. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  84874. // Alpha test
  84875. if (material && material.needAlphaTesting()) {
  84876. var alphaTexture = material.getAlphaTestTexture();
  84877. if (alphaTexture) {
  84878. this._effect.setTexture("diffuseSampler", alphaTexture);
  84879. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  84880. }
  84881. }
  84882. engine.setZOffset(-this.zOffset);
  84883. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  84884. engine.setZOffset(0);
  84885. };
  84886. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  84887. var defines = [];
  84888. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  84889. var mesh = subMesh.getMesh();
  84890. var material = subMesh.getMaterial();
  84891. if (material) {
  84892. // Alpha test
  84893. if (material.needAlphaTesting()) {
  84894. defines.push("#define ALPHATEST");
  84895. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  84896. attribs.push(BABYLON.VertexBuffer.UVKind);
  84897. defines.push("#define UV1");
  84898. }
  84899. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  84900. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  84901. defines.push("#define UV2");
  84902. }
  84903. }
  84904. //Logarithmic depth
  84905. if (material.useLogarithmicDepth) {
  84906. defines.push("#define LOGARITHMICDEPTH");
  84907. }
  84908. }
  84909. // Bones
  84910. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  84911. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  84912. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  84913. if (mesh.numBoneInfluencers > 4) {
  84914. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  84915. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  84916. }
  84917. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  84918. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  84919. }
  84920. else {
  84921. defines.push("#define NUM_BONE_INFLUENCERS 0");
  84922. }
  84923. // Instances
  84924. if (useInstances) {
  84925. defines.push("#define INSTANCES");
  84926. attribs.push("world0");
  84927. attribs.push("world1");
  84928. attribs.push("world2");
  84929. attribs.push("world3");
  84930. }
  84931. // Get correct effect
  84932. var join = defines.join("\n");
  84933. if (this._cachedDefines !== join) {
  84934. this._cachedDefines = join;
  84935. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  84936. }
  84937. return this._effect.isReady();
  84938. };
  84939. return OutlineRenderer;
  84940. }());
  84941. BABYLON.OutlineRenderer = OutlineRenderer;
  84942. })(BABYLON || (BABYLON = {}));
  84943. //# sourceMappingURL=babylon.outlineRenderer.js.map
  84944. var BABYLON;
  84945. (function (BABYLON) {
  84946. var FaceAdjacencies = /** @class */ (function () {
  84947. function FaceAdjacencies() {
  84948. this.edges = new Array();
  84949. this.edgesConnectedCount = 0;
  84950. }
  84951. return FaceAdjacencies;
  84952. }());
  84953. var EdgesRenderer = /** @class */ (function () {
  84954. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  84955. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  84956. if (epsilon === void 0) { epsilon = 0.95; }
  84957. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  84958. this.edgesWidthScalerForOrthographic = 1000.0;
  84959. this.edgesWidthScalerForPerspective = 50.0;
  84960. this._linesPositions = new Array();
  84961. this._linesNormals = new Array();
  84962. this._linesIndices = new Array();
  84963. this._buffers = {};
  84964. this._checkVerticesInsteadOfIndices = false;
  84965. this._source = source;
  84966. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  84967. this._epsilon = epsilon;
  84968. this._prepareRessources();
  84969. this._generateEdgesLines();
  84970. }
  84971. EdgesRenderer.prototype._prepareRessources = function () {
  84972. if (this._lineShader) {
  84973. return;
  84974. }
  84975. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  84976. attributes: ["position", "normal"],
  84977. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  84978. });
  84979. this._lineShader.disableDepthWrite = true;
  84980. this._lineShader.backFaceCulling = false;
  84981. };
  84982. EdgesRenderer.prototype._rebuild = function () {
  84983. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  84984. if (buffer) {
  84985. buffer._rebuild();
  84986. }
  84987. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  84988. if (buffer) {
  84989. buffer._rebuild();
  84990. }
  84991. var scene = this._source.getScene();
  84992. var engine = scene.getEngine();
  84993. this._ib = engine.createIndexBuffer(this._linesIndices);
  84994. };
  84995. EdgesRenderer.prototype.dispose = function () {
  84996. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  84997. if (buffer) {
  84998. buffer.dispose();
  84999. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  85000. }
  85001. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  85002. if (buffer) {
  85003. buffer.dispose();
  85004. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  85005. }
  85006. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  85007. this._lineShader.dispose();
  85008. };
  85009. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  85010. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  85011. return 0;
  85012. }
  85013. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  85014. return 1;
  85015. }
  85016. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  85017. return 2;
  85018. }
  85019. return -1;
  85020. };
  85021. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  85022. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  85023. return 0;
  85024. }
  85025. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  85026. return 1;
  85027. }
  85028. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  85029. return 2;
  85030. }
  85031. return -1;
  85032. };
  85033. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  85034. var needToCreateLine;
  85035. if (edge === undefined) {
  85036. needToCreateLine = true;
  85037. }
  85038. else {
  85039. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  85040. needToCreateLine = dotProduct < this._epsilon;
  85041. }
  85042. if (needToCreateLine) {
  85043. var offset = this._linesPositions.length / 3;
  85044. var normal = p0.subtract(p1);
  85045. normal.normalize();
  85046. // Positions
  85047. this._linesPositions.push(p0.x);
  85048. this._linesPositions.push(p0.y);
  85049. this._linesPositions.push(p0.z);
  85050. this._linesPositions.push(p0.x);
  85051. this._linesPositions.push(p0.y);
  85052. this._linesPositions.push(p0.z);
  85053. this._linesPositions.push(p1.x);
  85054. this._linesPositions.push(p1.y);
  85055. this._linesPositions.push(p1.z);
  85056. this._linesPositions.push(p1.x);
  85057. this._linesPositions.push(p1.y);
  85058. this._linesPositions.push(p1.z);
  85059. // Normals
  85060. this._linesNormals.push(p1.x);
  85061. this._linesNormals.push(p1.y);
  85062. this._linesNormals.push(p1.z);
  85063. this._linesNormals.push(-1);
  85064. this._linesNormals.push(p1.x);
  85065. this._linesNormals.push(p1.y);
  85066. this._linesNormals.push(p1.z);
  85067. this._linesNormals.push(1);
  85068. this._linesNormals.push(p0.x);
  85069. this._linesNormals.push(p0.y);
  85070. this._linesNormals.push(p0.z);
  85071. this._linesNormals.push(-1);
  85072. this._linesNormals.push(p0.x);
  85073. this._linesNormals.push(p0.y);
  85074. this._linesNormals.push(p0.z);
  85075. this._linesNormals.push(1);
  85076. // Indices
  85077. this._linesIndices.push(offset);
  85078. this._linesIndices.push(offset + 1);
  85079. this._linesIndices.push(offset + 2);
  85080. this._linesIndices.push(offset);
  85081. this._linesIndices.push(offset + 2);
  85082. this._linesIndices.push(offset + 3);
  85083. }
  85084. };
  85085. EdgesRenderer.prototype._generateEdgesLines = function () {
  85086. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  85087. var indices = this._source.getIndices();
  85088. if (!indices || !positions) {
  85089. return;
  85090. }
  85091. // First let's find adjacencies
  85092. var adjacencies = new Array();
  85093. var faceNormals = new Array();
  85094. var index;
  85095. var faceAdjacencies;
  85096. // Prepare faces
  85097. for (index = 0; index < indices.length; index += 3) {
  85098. faceAdjacencies = new FaceAdjacencies();
  85099. var p0Index = indices[index];
  85100. var p1Index = indices[index + 1];
  85101. var p2Index = indices[index + 2];
  85102. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  85103. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  85104. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  85105. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  85106. faceNormal.normalize();
  85107. faceNormals.push(faceNormal);
  85108. adjacencies.push(faceAdjacencies);
  85109. }
  85110. // Scan
  85111. for (index = 0; index < adjacencies.length; index++) {
  85112. faceAdjacencies = adjacencies[index];
  85113. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  85114. var otherFaceAdjacencies = adjacencies[otherIndex];
  85115. if (faceAdjacencies.edgesConnectedCount === 3) {
  85116. break;
  85117. }
  85118. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  85119. continue;
  85120. }
  85121. var otherP0 = indices[otherIndex * 3];
  85122. var otherP1 = indices[otherIndex * 3 + 1];
  85123. var otherP2 = indices[otherIndex * 3 + 2];
  85124. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  85125. var otherEdgeIndex = 0;
  85126. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  85127. continue;
  85128. }
  85129. switch (edgeIndex) {
  85130. case 0:
  85131. if (this._checkVerticesInsteadOfIndices) {
  85132. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  85133. }
  85134. else {
  85135. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  85136. }
  85137. break;
  85138. case 1:
  85139. if (this._checkVerticesInsteadOfIndices) {
  85140. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  85141. }
  85142. else {
  85143. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  85144. }
  85145. break;
  85146. case 2:
  85147. if (this._checkVerticesInsteadOfIndices) {
  85148. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  85149. }
  85150. else {
  85151. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  85152. }
  85153. break;
  85154. }
  85155. if (otherEdgeIndex === -1) {
  85156. continue;
  85157. }
  85158. faceAdjacencies.edges[edgeIndex] = otherIndex;
  85159. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  85160. faceAdjacencies.edgesConnectedCount++;
  85161. otherFaceAdjacencies.edgesConnectedCount++;
  85162. if (faceAdjacencies.edgesConnectedCount === 3) {
  85163. break;
  85164. }
  85165. }
  85166. }
  85167. }
  85168. // Create lines
  85169. for (index = 0; index < adjacencies.length; index++) {
  85170. // 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
  85171. var current = adjacencies[index];
  85172. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  85173. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  85174. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  85175. }
  85176. // Merge into a single mesh
  85177. var engine = this._source.getScene().getEngine();
  85178. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  85179. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  85180. this._ib = engine.createIndexBuffer(this._linesIndices);
  85181. this._indicesCount = this._linesIndices.length;
  85182. };
  85183. EdgesRenderer.prototype.render = function () {
  85184. var scene = this._source.getScene();
  85185. if (!this._lineShader.isReady() || !scene.activeCamera) {
  85186. return;
  85187. }
  85188. var engine = scene.getEngine();
  85189. this._lineShader._preBind();
  85190. // VBOs
  85191. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  85192. scene.resetCachedMaterial();
  85193. this._lineShader.setColor4("color", this._source.edgesColor);
  85194. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  85195. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  85196. }
  85197. else {
  85198. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  85199. }
  85200. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  85201. this._lineShader.bind(this._source.getWorldMatrix());
  85202. // Draw order
  85203. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  85204. this._lineShader.unbind();
  85205. engine.setDepthWrite(true);
  85206. };
  85207. return EdgesRenderer;
  85208. }());
  85209. BABYLON.EdgesRenderer = EdgesRenderer;
  85210. })(BABYLON || (BABYLON = {}));
  85211. //# sourceMappingURL=babylon.edgesRenderer.js.map
  85212. var __assign = (this && this.__assign) || Object.assign || function(t) {
  85213. for (var s, i = 1, n = arguments.length; i < n; i++) {
  85214. s = arguments[i];
  85215. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  85216. t[p] = s[p];
  85217. }
  85218. return t;
  85219. };
  85220. var BABYLON;
  85221. (function (BABYLON) {
  85222. /**
  85223. * The effect layer Helps adding post process effect blended with the main pass.
  85224. *
  85225. * This can be for instance use to generate glow or higlight effects on the scene.
  85226. *
  85227. * The effect layer class can not be used directly and is intented to inherited from to be
  85228. * customized per effects.
  85229. */
  85230. var EffectLayer = /** @class */ (function () {
  85231. /**
  85232. * Instantiates a new effect Layer and references it in the scene.
  85233. * @param name The name of the layer
  85234. * @param scene The scene to use the layer in
  85235. */
  85236. function EffectLayer(
  85237. /** The Friendly of the effect in the scene */
  85238. name, scene) {
  85239. this.name = name;
  85240. this._vertexBuffers = {};
  85241. this._maxSize = 0;
  85242. this._mainTextureDesiredSize = { width: 0, height: 0 };
  85243. this._shouldRender = true;
  85244. this._postProcesses = [];
  85245. this._textures = [];
  85246. this._emissiveTextureAndColor = { texture: null, color: new BABYLON.Color4() };
  85247. /**
  85248. * The clear color of the texture used to generate the glow map.
  85249. */
  85250. this.neutralColor = new BABYLON.Color4();
  85251. /**
  85252. * Specifies wether the highlight layer is enabled or not.
  85253. */
  85254. this.isEnabled = true;
  85255. /**
  85256. * An event triggered when the effect layer has been disposed.
  85257. */
  85258. this.onDisposeObservable = new BABYLON.Observable();
  85259. /**
  85260. * An event triggered when the effect layer is about rendering the main texture with the glowy parts.
  85261. */
  85262. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  85263. /**
  85264. * An event triggered when the generated texture is being merged in the scene.
  85265. */
  85266. this.onBeforeComposeObservable = new BABYLON.Observable();
  85267. /**
  85268. * An event triggered when the generated texture has been merged in the scene.
  85269. */
  85270. this.onAfterComposeObservable = new BABYLON.Observable();
  85271. /**
  85272. * An event triggered when the efffect layer changes its size.
  85273. */
  85274. this.onSizeChangedObservable = new BABYLON.Observable();
  85275. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  85276. this._engine = scene.getEngine();
  85277. this._maxSize = this._engine.getCaps().maxTextureSize;
  85278. this._scene.effectLayers.push(this);
  85279. // Generate Buffers
  85280. this._generateIndexBuffer();
  85281. this._genrateVertexBuffer();
  85282. }
  85283. Object.defineProperty(EffectLayer.prototype, "camera", {
  85284. /**
  85285. * Gets the camera attached to the layer.
  85286. */
  85287. get: function () {
  85288. return this._effectLayerOptions.camera;
  85289. },
  85290. enumerable: true,
  85291. configurable: true
  85292. });
  85293. /**
  85294. * Initializes the effect layer with the required options.
  85295. * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
  85296. */
  85297. EffectLayer.prototype._init = function (options) {
  85298. // Adapt options
  85299. this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  85300. this._setMainTextureSize();
  85301. this._createMainTexture();
  85302. this._createTextureAndPostProcesses();
  85303. this._mergeEffect = this._createMergeEffect();
  85304. };
  85305. /**
  85306. * Generates the index buffer of the full screen quad blending to the main canvas.
  85307. */
  85308. EffectLayer.prototype._generateIndexBuffer = function () {
  85309. // Indices
  85310. var indices = [];
  85311. indices.push(0);
  85312. indices.push(1);
  85313. indices.push(2);
  85314. indices.push(0);
  85315. indices.push(2);
  85316. indices.push(3);
  85317. this._indexBuffer = this._engine.createIndexBuffer(indices);
  85318. };
  85319. /**
  85320. * Generates the vertex buffer of the full screen quad blending to the main canvas.
  85321. */
  85322. EffectLayer.prototype._genrateVertexBuffer = function () {
  85323. // VBO
  85324. var vertices = [];
  85325. vertices.push(1, 1);
  85326. vertices.push(-1, 1);
  85327. vertices.push(-1, -1);
  85328. vertices.push(1, -1);
  85329. var vertexBuffer = new BABYLON.VertexBuffer(this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  85330. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  85331. };
  85332. /**
  85333. * Sets the main texture desired size which is the closest power of two
  85334. * of the engine canvas size.
  85335. */
  85336. EffectLayer.prototype._setMainTextureSize = function () {
  85337. if (this._effectLayerOptions.mainTextureFixedSize) {
  85338. this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
  85339. this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
  85340. }
  85341. else {
  85342. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
  85343. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
  85344. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  85345. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  85346. }
  85347. this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
  85348. this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
  85349. };
  85350. /**
  85351. * Creates the main texture for the effect layer.
  85352. */
  85353. EffectLayer.prototype._createMainTexture = function () {
  85354. var _this = this;
  85355. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  85356. width: this._mainTextureDesiredSize.width,
  85357. height: this._mainTextureDesiredSize.height
  85358. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  85359. this._mainTexture.activeCamera = this._effectLayerOptions.camera;
  85360. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  85361. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  85362. this._mainTexture.anisotropicFilteringLevel = 1;
  85363. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  85364. this._mainTexture.renderParticles = false;
  85365. this._mainTexture.renderList = null;
  85366. this._mainTexture.ignoreCameraViewport = true;
  85367. // Custom render function
  85368. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  85369. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  85370. var index;
  85371. var engine = _this._scene.getEngine();
  85372. if (depthOnlySubMeshes.length) {
  85373. engine.setColorWrite(false);
  85374. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  85375. _this._renderSubMesh(depthOnlySubMeshes.data[index]);
  85376. }
  85377. engine.setColorWrite(true);
  85378. }
  85379. for (index = 0; index < opaqueSubMeshes.length; index++) {
  85380. _this._renderSubMesh(opaqueSubMeshes.data[index]);
  85381. }
  85382. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  85383. _this._renderSubMesh(alphaTestSubMeshes.data[index]);
  85384. }
  85385. for (index = 0; index < transparentSubMeshes.length; index++) {
  85386. _this._renderSubMesh(transparentSubMeshes.data[index]);
  85387. }
  85388. };
  85389. this._mainTexture.onClearObservable.add(function (engine) {
  85390. engine.clear(_this.neutralColor, true, true, true);
  85391. });
  85392. };
  85393. /**
  85394. * Checks for the readiness of the element composing the layer.
  85395. * @param subMesh the mesh to check for
  85396. * @param useInstances specify wether or not to use instances to render the mesh
  85397. * @param emissiveTexture the associated emissive texture used to generate the glow
  85398. * @return true if ready otherwise, false
  85399. */
  85400. EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  85401. var material = subMesh.getMaterial();
  85402. if (!material) {
  85403. return false;
  85404. }
  85405. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  85406. return false;
  85407. }
  85408. var defines = [];
  85409. var attribs = [BABYLON.VertexBuffer.PositionKind];
  85410. var mesh = subMesh.getMesh();
  85411. var uv1 = false;
  85412. var uv2 = false;
  85413. // Alpha test
  85414. if (material && material.needAlphaTesting()) {
  85415. var alphaTexture = material.getAlphaTestTexture();
  85416. if (alphaTexture) {
  85417. defines.push("#define ALPHATEST");
  85418. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  85419. alphaTexture.coordinatesIndex === 1) {
  85420. defines.push("#define DIFFUSEUV2");
  85421. uv2 = true;
  85422. }
  85423. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  85424. defines.push("#define DIFFUSEUV1");
  85425. uv1 = true;
  85426. }
  85427. }
  85428. }
  85429. // Emissive
  85430. if (emissiveTexture) {
  85431. defines.push("#define EMISSIVE");
  85432. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  85433. emissiveTexture.coordinatesIndex === 1) {
  85434. defines.push("#define EMISSIVEUV2");
  85435. uv2 = true;
  85436. }
  85437. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  85438. defines.push("#define EMISSIVEUV1");
  85439. uv1 = true;
  85440. }
  85441. }
  85442. if (uv1) {
  85443. attribs.push(BABYLON.VertexBuffer.UVKind);
  85444. defines.push("#define UV1");
  85445. }
  85446. if (uv2) {
  85447. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  85448. defines.push("#define UV2");
  85449. }
  85450. // Bones
  85451. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  85452. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  85453. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  85454. if (mesh.numBoneInfluencers > 4) {
  85455. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  85456. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  85457. }
  85458. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  85459. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  85460. }
  85461. else {
  85462. defines.push("#define NUM_BONE_INFLUENCERS 0");
  85463. }
  85464. // Instances
  85465. if (useInstances) {
  85466. defines.push("#define INSTANCES");
  85467. attribs.push("world0");
  85468. attribs.push("world1");
  85469. attribs.push("world2");
  85470. attribs.push("world3");
  85471. }
  85472. // Get correct effect
  85473. var join = defines.join("\n");
  85474. if (this._cachedDefines !== join) {
  85475. this._cachedDefines = join;
  85476. this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix"], ["diffuseSampler", "emissiveSampler"], join);
  85477. }
  85478. return this._effectLayerMapGenerationEffect.isReady();
  85479. };
  85480. /**
  85481. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  85482. */
  85483. EffectLayer.prototype.render = function () {
  85484. var currentEffect = this._mergeEffect;
  85485. // Check
  85486. if (!currentEffect.isReady())
  85487. return;
  85488. for (var i = 0; i < this._postProcesses.length; i++) {
  85489. if (!this._postProcesses[i].isReady()) {
  85490. return;
  85491. }
  85492. }
  85493. var engine = this._scene.getEngine();
  85494. this.onBeforeComposeObservable.notifyObservers(this);
  85495. // Render
  85496. engine.enableEffect(currentEffect);
  85497. engine.setState(false);
  85498. // VBOs
  85499. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  85500. // Cache
  85501. var previousAlphaMode = engine.getAlphaMode();
  85502. // Go Blend.
  85503. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
  85504. // Blends the map on the main canvas.
  85505. this._internalRender(currentEffect);
  85506. // Restore Alpha
  85507. engine.setAlphaMode(previousAlphaMode);
  85508. this.onAfterComposeObservable.notifyObservers(this);
  85509. // Handle size changes.
  85510. var size = this._mainTexture.getSize();
  85511. this._setMainTextureSize();
  85512. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  85513. // Recreate RTT and post processes on size change.
  85514. this.onSizeChangedObservable.notifyObservers(this);
  85515. this._disposeTextureAndPostProcesses();
  85516. this._createMainTexture();
  85517. this._createTextureAndPostProcesses();
  85518. }
  85519. };
  85520. /**
  85521. * Determine if a given mesh will be used in the current effect.
  85522. * @param mesh mesh to test
  85523. * @returns true if the mesh will be used
  85524. */
  85525. EffectLayer.prototype.hasMesh = function (mesh) {
  85526. return true;
  85527. };
  85528. /**
  85529. * Returns true if the layer contains information to display, otherwise false.
  85530. * @returns true if the glow layer should be rendered
  85531. */
  85532. EffectLayer.prototype.shouldRender = function () {
  85533. return this.isEnabled && this._shouldRender;
  85534. };
  85535. /**
  85536. * Returns true if the mesh should render, otherwise false.
  85537. * @param mesh The mesh to render
  85538. * @returns true if it should render otherwise false
  85539. */
  85540. EffectLayer.prototype._shouldRenderMesh = function (mesh) {
  85541. return true;
  85542. };
  85543. /**
  85544. * Returns true if the mesh should render, otherwise false.
  85545. * @param mesh The mesh to render
  85546. * @returns true if it should render otherwise false
  85547. */
  85548. EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function (mesh) {
  85549. return true;
  85550. };
  85551. /**
  85552. * Renders the submesh passed in parameter to the generation map.
  85553. */
  85554. EffectLayer.prototype._renderSubMesh = function (subMesh) {
  85555. var _this = this;
  85556. if (!this.shouldRender()) {
  85557. return;
  85558. }
  85559. var material = subMesh.getMaterial();
  85560. var mesh = subMesh.getRenderingMesh();
  85561. var scene = this._scene;
  85562. var engine = scene.getEngine();
  85563. if (!material) {
  85564. return;
  85565. }
  85566. // Do not block in blend mode.
  85567. if (material.needAlphaBlendingForMesh(mesh)) {
  85568. return;
  85569. }
  85570. // Culling
  85571. engine.setState(material.backFaceCulling);
  85572. // Managing instances
  85573. var batch = mesh._getInstancesRenderList(subMesh._id);
  85574. if (batch.mustReturn) {
  85575. return;
  85576. }
  85577. // Early Exit per mesh
  85578. if (!this._shouldRenderMesh(mesh)) {
  85579. return;
  85580. }
  85581. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  85582. this._setEmissiveTextureAndColor(mesh, subMesh, material);
  85583. if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
  85584. engine.enableEffect(this._effectLayerMapGenerationEffect);
  85585. mesh._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  85586. this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  85587. this._effectLayerMapGenerationEffect.setFloat4("color", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
  85588. // Alpha test
  85589. if (material && material.needAlphaTesting()) {
  85590. var alphaTexture = material.getAlphaTestTexture();
  85591. if (alphaTexture) {
  85592. this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  85593. var textureMatrix = alphaTexture.getTextureMatrix();
  85594. if (textureMatrix) {
  85595. this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  85596. }
  85597. }
  85598. }
  85599. // Glow emissive only
  85600. if (this._emissiveTextureAndColor.texture) {
  85601. this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
  85602. this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
  85603. }
  85604. // Bones
  85605. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  85606. this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  85607. }
  85608. // Draw
  85609. mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); });
  85610. }
  85611. else {
  85612. // Need to reset refresh rate of the shadowMap
  85613. this._mainTexture.resetRefreshCounter();
  85614. }
  85615. };
  85616. /**
  85617. * Rebuild the required buffers.
  85618. * @ignore Internal use only.
  85619. */
  85620. EffectLayer.prototype._rebuild = function () {
  85621. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  85622. if (vb) {
  85623. vb._rebuild();
  85624. }
  85625. this._generateIndexBuffer();
  85626. };
  85627. /**
  85628. * Dispose only the render target textures and post process.
  85629. */
  85630. EffectLayer.prototype._disposeTextureAndPostProcesses = function () {
  85631. this._mainTexture.dispose();
  85632. for (var i = 0; i < this._postProcesses.length; i++) {
  85633. if (this._postProcesses[i]) {
  85634. this._postProcesses[i].dispose();
  85635. }
  85636. }
  85637. this._postProcesses = [];
  85638. for (var i = 0; i < this._textures.length; i++) {
  85639. if (this._textures[i]) {
  85640. this._textures[i].dispose();
  85641. }
  85642. }
  85643. this._textures = [];
  85644. };
  85645. /**
  85646. * Dispose the highlight layer and free resources.
  85647. */
  85648. EffectLayer.prototype.dispose = function () {
  85649. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  85650. if (vertexBuffer) {
  85651. vertexBuffer.dispose();
  85652. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  85653. }
  85654. if (this._indexBuffer) {
  85655. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  85656. this._indexBuffer = null;
  85657. }
  85658. // Clean textures and post processes
  85659. this._disposeTextureAndPostProcesses();
  85660. // Remove from scene
  85661. var index = this._scene.effectLayers.indexOf(this, 0);
  85662. if (index > -1) {
  85663. this._scene.effectLayers.splice(index, 1);
  85664. }
  85665. // Callback
  85666. this.onDisposeObservable.notifyObservers(this);
  85667. this.onDisposeObservable.clear();
  85668. this.onBeforeRenderMainTextureObservable.clear();
  85669. this.onBeforeComposeObservable.clear();
  85670. this.onAfterComposeObservable.clear();
  85671. this.onSizeChangedObservable.clear();
  85672. };
  85673. return EffectLayer;
  85674. }());
  85675. BABYLON.EffectLayer = EffectLayer;
  85676. })(BABYLON || (BABYLON = {}));
  85677. //# sourceMappingURL=babylon.effectLayer.js.map
  85678. var BABYLON;
  85679. (function (BABYLON) {
  85680. /**
  85681. * Special Glow Blur post process only blurring the alpha channel
  85682. * It enforces keeping the most luminous color in the color channel.
  85683. */
  85684. var GlowBlurPostProcess = /** @class */ (function (_super) {
  85685. __extends(GlowBlurPostProcess, _super);
  85686. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  85687. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  85688. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  85689. _this.direction = direction;
  85690. _this.kernel = kernel;
  85691. _this.onApplyObservable.add(function (effect) {
  85692. effect.setFloat2("screenSize", _this.width, _this.height);
  85693. effect.setVector2("direction", _this.direction);
  85694. effect.setFloat("blurWidth", _this.kernel);
  85695. });
  85696. return _this;
  85697. }
  85698. return GlowBlurPostProcess;
  85699. }(BABYLON.PostProcess));
  85700. /**
  85701. * The highlight layer Helps adding a glow effect around a mesh.
  85702. *
  85703. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  85704. * glowy meshes to your scene.
  85705. *
  85706. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  85707. */
  85708. var HighlightLayer = /** @class */ (function (_super) {
  85709. __extends(HighlightLayer, _super);
  85710. /**
  85711. * Instantiates a new highlight Layer and references it to the scene..
  85712. * @param name The name of the layer
  85713. * @param scene The scene to use the layer in
  85714. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  85715. */
  85716. function HighlightLayer(name, scene, options) {
  85717. var _this = _super.call(this, name, scene) || this;
  85718. _this.name = name;
  85719. /**
  85720. * Specifies whether or not the inner glow is ACTIVE in the layer.
  85721. */
  85722. _this.innerGlow = true;
  85723. /**
  85724. * Specifies whether or not the outer glow is ACTIVE in the layer.
  85725. */
  85726. _this.outerGlow = true;
  85727. /**
  85728. * An event triggered when the highlight layer is being blurred.
  85729. */
  85730. _this.onBeforeBlurObservable = new BABYLON.Observable();
  85731. /**
  85732. * An event triggered when the highlight layer has been blurred.
  85733. */
  85734. _this.onAfterBlurObservable = new BABYLON.Observable();
  85735. _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
  85736. _this._meshes = {};
  85737. _this._excludedMeshes = {};
  85738. _this.neutralColor = HighlightLayer.NeutralColor;
  85739. // Warn on stencil
  85740. if (!_this._engine.isStencilEnable) {
  85741. 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 }");
  85742. }
  85743. // Adapt options
  85744. _this._options = __assign({ mainTextureRatio: 0.5, blurTextureSizeRatio: 0.5, blurHorizontalSize: 1.0, blurVerticalSize: 1.0, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  85745. // Initialize the layer
  85746. _this._init({
  85747. alphaBlendingMode: _this._options.alphaBlendingMode,
  85748. camera: _this._options.camera,
  85749. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  85750. mainTextureRatio: _this._options.mainTextureRatio
  85751. });
  85752. // Do not render as long as no meshes have been added
  85753. _this._shouldRender = false;
  85754. return _this;
  85755. }
  85756. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  85757. /**
  85758. * Gets the horizontal size of the blur.
  85759. */
  85760. get: function () {
  85761. return this._horizontalBlurPostprocess.kernel;
  85762. },
  85763. /**
  85764. * Specifies the horizontal size of the blur.
  85765. */
  85766. set: function (value) {
  85767. this._horizontalBlurPostprocess.kernel = value;
  85768. },
  85769. enumerable: true,
  85770. configurable: true
  85771. });
  85772. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  85773. /**
  85774. * Gets the vertical size of the blur.
  85775. */
  85776. get: function () {
  85777. return this._verticalBlurPostprocess.kernel;
  85778. },
  85779. /**
  85780. * Specifies the vertical size of the blur.
  85781. */
  85782. set: function (value) {
  85783. this._verticalBlurPostprocess.kernel = value;
  85784. },
  85785. enumerable: true,
  85786. configurable: true
  85787. });
  85788. /**
  85789. * Get the effect name of the layer.
  85790. * @return The effect name
  85791. */
  85792. HighlightLayer.prototype.getEffectName = function () {
  85793. return HighlightLayer.EffectName;
  85794. };
  85795. /**
  85796. * Create the merge effect. This is the shader use to blit the information back
  85797. * to the main canvas at the end of the scene rendering.
  85798. */
  85799. HighlightLayer.prototype._createMergeEffect = function () {
  85800. // Effect
  85801. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  85802. };
  85803. /**
  85804. * Creates the render target textures and post processes used in the highlight layer.
  85805. */
  85806. HighlightLayer.prototype._createTextureAndPostProcesses = function () {
  85807. var _this = this;
  85808. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  85809. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  85810. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  85811. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  85812. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  85813. width: blurTextureWidth,
  85814. height: blurTextureHeight
  85815. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  85816. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  85817. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  85818. this._blurTexture.anisotropicFilteringLevel = 16;
  85819. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  85820. this._blurTexture.renderParticles = false;
  85821. this._blurTexture.ignoreCameraViewport = true;
  85822. this._textures = [this._blurTexture];
  85823. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  85824. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  85825. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  85826. effect.setTexture("textureSampler", _this._mainTexture);
  85827. });
  85828. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  85829. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  85830. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  85831. });
  85832. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  85833. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  85834. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  85835. });
  85836. this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  85837. }
  85838. else {
  85839. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {
  85840. width: blurTextureWidth,
  85841. height: blurTextureHeight
  85842. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  85843. this._horizontalBlurPostprocess.width = blurTextureWidth;
  85844. this._horizontalBlurPostprocess.height = blurTextureHeight;
  85845. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  85846. effect.setTexture("textureSampler", _this._mainTexture);
  85847. });
  85848. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize / 2, {
  85849. width: blurTextureWidth,
  85850. height: blurTextureHeight
  85851. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  85852. this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  85853. }
  85854. this._mainTexture.onAfterUnbindObservable.add(function () {
  85855. _this.onBeforeBlurObservable.notifyObservers(_this);
  85856. var internalTexture = _this._blurTexture.getInternalTexture();
  85857. if (internalTexture) {
  85858. _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);
  85859. }
  85860. _this.onAfterBlurObservable.notifyObservers(_this);
  85861. });
  85862. // Prevent autoClear.
  85863. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  85864. };
  85865. /**
  85866. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  85867. */
  85868. HighlightLayer.prototype.needStencil = function () {
  85869. return true;
  85870. };
  85871. /**
  85872. * Checks for the readiness of the element composing the layer.
  85873. * @param subMesh the mesh to check for
  85874. * @param useInstances specify wether or not to use instances to render the mesh
  85875. * @param emissiveTexture the associated emissive texture used to generate the glow
  85876. * @return true if ready otherwise, false
  85877. */
  85878. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  85879. var material = subMesh.getMaterial();
  85880. var mesh = subMesh.getRenderingMesh();
  85881. if (!material || !mesh || !this._meshes) {
  85882. return false;
  85883. }
  85884. var emissiveTexture = null;
  85885. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  85886. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  85887. emissiveTexture = material.emissiveTexture;
  85888. }
  85889. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  85890. };
  85891. /**
  85892. * Implementation specific of rendering the generating effect on the main canvas.
  85893. * @param effect The effect used to render through
  85894. */
  85895. HighlightLayer.prototype._internalRender = function (effect) {
  85896. // Texture
  85897. effect.setTexture("textureSampler", this._blurTexture);
  85898. // Cache
  85899. var engine = this._engine;
  85900. var previousStencilBuffer = engine.getStencilBuffer();
  85901. var previousStencilFunction = engine.getStencilFunction();
  85902. var previousStencilMask = engine.getStencilMask();
  85903. var previousStencilOperationPass = engine.getStencilOperationPass();
  85904. var previousStencilOperationFail = engine.getStencilOperationFail();
  85905. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  85906. var previousStencilReference = engine.getStencilFunctionReference();
  85907. // Stencil operations
  85908. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  85909. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  85910. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  85911. // Draw order
  85912. engine.setStencilMask(0x00);
  85913. engine.setStencilBuffer(true);
  85914. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  85915. // 2 passes inner outer
  85916. if (this.outerGlow) {
  85917. effect.setFloat("offset", 0);
  85918. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  85919. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  85920. }
  85921. if (this.innerGlow) {
  85922. effect.setFloat("offset", 1);
  85923. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  85924. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  85925. }
  85926. // Restore Cache
  85927. engine.setStencilFunction(previousStencilFunction);
  85928. engine.setStencilMask(previousStencilMask);
  85929. engine.setStencilBuffer(previousStencilBuffer);
  85930. engine.setStencilOperationPass(previousStencilOperationPass);
  85931. engine.setStencilOperationFail(previousStencilOperationFail);
  85932. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  85933. engine.setStencilFunctionReference(previousStencilReference);
  85934. };
  85935. /**
  85936. * Returns true if the layer contains information to display, otherwise false.
  85937. */
  85938. HighlightLayer.prototype.shouldRender = function () {
  85939. if (_super.prototype.shouldRender.call(this)) {
  85940. return this._meshes ? true : false;
  85941. }
  85942. return false;
  85943. };
  85944. /**
  85945. * Returns true if the mesh should render, otherwise false.
  85946. * @param mesh The mesh to render
  85947. * @returns true if it should render otherwise false
  85948. */
  85949. HighlightLayer.prototype._shouldRenderMesh = function (mesh) {
  85950. // Excluded Mesh
  85951. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  85952. return false;
  85953. }
  85954. ;
  85955. return true;
  85956. };
  85957. /**
  85958. * Sets the required values for both the emissive texture and and the main color.
  85959. */
  85960. HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  85961. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  85962. if (highlightLayerMesh) {
  85963. this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  85964. }
  85965. else {
  85966. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  85967. }
  85968. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  85969. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  85970. this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);
  85971. }
  85972. else {
  85973. this._emissiveTextureAndColor.texture = null;
  85974. }
  85975. };
  85976. /**
  85977. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  85978. * @param mesh The mesh to exclude from the highlight layer
  85979. */
  85980. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  85981. if (!this._excludedMeshes) {
  85982. return;
  85983. }
  85984. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  85985. if (!meshExcluded) {
  85986. this._excludedMeshes[mesh.uniqueId] = {
  85987. mesh: mesh,
  85988. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  85989. mesh.getEngine().setStencilBuffer(false);
  85990. }),
  85991. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  85992. mesh.getEngine().setStencilBuffer(true);
  85993. }),
  85994. };
  85995. }
  85996. };
  85997. /**
  85998. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  85999. * @param mesh The mesh to highlight
  86000. */
  86001. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  86002. if (!this._excludedMeshes) {
  86003. return;
  86004. }
  86005. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  86006. if (meshExcluded) {
  86007. if (meshExcluded.beforeRender) {
  86008. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  86009. }
  86010. if (meshExcluded.afterRender) {
  86011. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  86012. }
  86013. }
  86014. this._excludedMeshes[mesh.uniqueId] = null;
  86015. };
  86016. /**
  86017. * Determine if a given mesh will be highlighted by the current HighlightLayer
  86018. * @param mesh mesh to test
  86019. * @returns true if the mesh will be highlighted by the current HighlightLayer
  86020. */
  86021. HighlightLayer.prototype.hasMesh = function (mesh) {
  86022. if (!this._meshes) {
  86023. return false;
  86024. }
  86025. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  86026. };
  86027. /**
  86028. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  86029. * @param mesh The mesh to highlight
  86030. * @param color The color of the highlight
  86031. * @param glowEmissiveOnly Extract the glow from the emissive texture
  86032. */
  86033. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  86034. var _this = this;
  86035. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  86036. if (!this._meshes) {
  86037. return;
  86038. }
  86039. var meshHighlight = this._meshes[mesh.uniqueId];
  86040. if (meshHighlight) {
  86041. meshHighlight.color = color;
  86042. }
  86043. else {
  86044. this._meshes[mesh.uniqueId] = {
  86045. mesh: mesh,
  86046. color: color,
  86047. // Lambda required for capture due to Observable this context
  86048. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  86049. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  86050. _this._defaultStencilReference(mesh);
  86051. }
  86052. else {
  86053. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  86054. }
  86055. }),
  86056. observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),
  86057. glowEmissiveOnly: glowEmissiveOnly
  86058. };
  86059. }
  86060. this._shouldRender = true;
  86061. };
  86062. /**
  86063. * Remove a mesh from the highlight layer in order to make it stop glowing.
  86064. * @param mesh The mesh to highlight
  86065. */
  86066. HighlightLayer.prototype.removeMesh = function (mesh) {
  86067. if (!this._meshes) {
  86068. return;
  86069. }
  86070. var meshHighlight = this._meshes[mesh.uniqueId];
  86071. if (meshHighlight) {
  86072. if (meshHighlight.observerHighlight) {
  86073. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  86074. }
  86075. if (meshHighlight.observerDefault) {
  86076. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  86077. }
  86078. delete this._meshes[mesh.uniqueId];
  86079. }
  86080. this._shouldRender = false;
  86081. for (var meshHighlightToCheck in this._meshes) {
  86082. if (this._meshes[meshHighlightToCheck]) {
  86083. this._shouldRender = true;
  86084. break;
  86085. }
  86086. }
  86087. };
  86088. /**
  86089. * Force the stencil to the normal expected value for none glowing parts
  86090. */
  86091. HighlightLayer.prototype._defaultStencilReference = function (mesh) {
  86092. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
  86093. };
  86094. /**
  86095. * Free any resources and references associated to a mesh.
  86096. * Internal use
  86097. * @param mesh The mesh to free.
  86098. */
  86099. HighlightLayer.prototype._disposeMesh = function (mesh) {
  86100. this.removeMesh(mesh);
  86101. this.removeExcludedMesh(mesh);
  86102. };
  86103. /**
  86104. * Dispose the highlight layer and free resources.
  86105. */
  86106. HighlightLayer.prototype.dispose = function () {
  86107. if (this._meshes) {
  86108. // Clean mesh references
  86109. for (var id in this._meshes) {
  86110. var meshHighlight = this._meshes[id];
  86111. if (meshHighlight && meshHighlight.mesh) {
  86112. if (meshHighlight.observerHighlight) {
  86113. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  86114. }
  86115. if (meshHighlight.observerDefault) {
  86116. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  86117. }
  86118. }
  86119. }
  86120. this._meshes = null;
  86121. }
  86122. if (this._excludedMeshes) {
  86123. for (var id in this._excludedMeshes) {
  86124. var meshHighlight = this._excludedMeshes[id];
  86125. if (meshHighlight) {
  86126. if (meshHighlight.beforeRender) {
  86127. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  86128. }
  86129. if (meshHighlight.afterRender) {
  86130. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  86131. }
  86132. }
  86133. }
  86134. this._excludedMeshes = null;
  86135. }
  86136. _super.prototype.dispose.call(this);
  86137. };
  86138. /**
  86139. * Effect Name of the highlight layer.
  86140. */
  86141. HighlightLayer.EffectName = "HighlightLayer";
  86142. /**
  86143. * The neutral color used during the preparation of the glow effect.
  86144. * This is black by default as the blend operation is a blend operation.
  86145. */
  86146. HighlightLayer.NeutralColor = new BABYLON.Color4(0, 0, 0, 0);
  86147. /**
  86148. * Stencil value used for glowing meshes.
  86149. */
  86150. HighlightLayer.GlowingMeshStencilReference = 0x02;
  86151. /**
  86152. * Stencil value used for the other meshes in the scene.
  86153. */
  86154. HighlightLayer.NormalMeshStencilReference = 0x01;
  86155. return HighlightLayer;
  86156. }(BABYLON.EffectLayer));
  86157. BABYLON.HighlightLayer = HighlightLayer;
  86158. })(BABYLON || (BABYLON = {}));
  86159. //# sourceMappingURL=babylon.highlightLayer.js.map
  86160. var BABYLON;
  86161. (function (BABYLON) {
  86162. /**
  86163. * The glow layer Helps adding a glow effect around the emissive parts of a mesh.
  86164. *
  86165. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  86166. * glowy meshes to your scene.
  86167. *
  86168. * Documentation: https://doc.babylonjs.com/how_to/glow_layer
  86169. */
  86170. var GlowLayer = /** @class */ (function (_super) {
  86171. __extends(GlowLayer, _super);
  86172. /**
  86173. * Instantiates a new glow Layer and references it to the scene.
  86174. * @param name The name of the layer
  86175. * @param scene The scene to use the layer in
  86176. * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)
  86177. */
  86178. function GlowLayer(name, scene, options) {
  86179. var _this = _super.call(this, name, scene) || this;
  86180. _this.name = name;
  86181. _this._intensity = 1.0;
  86182. _this._includedOnlyMeshes = [];
  86183. _this._excludedMeshes = [];
  86184. _this.neutralColor = new BABYLON.Color4(0, 0, 0, 1);
  86185. // Adapt options
  86186. _this._options = __assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1 }, options);
  86187. // Initialize the layer
  86188. _this._init({
  86189. alphaBlendingMode: BABYLON.Engine.ALPHA_ADD,
  86190. camera: _this._options.camera,
  86191. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  86192. mainTextureRatio: _this._options.mainTextureRatio
  86193. });
  86194. return _this;
  86195. }
  86196. Object.defineProperty(GlowLayer.prototype, "blurKernelSize", {
  86197. /**
  86198. * Gets the kernel size of the blur.
  86199. */
  86200. get: function () {
  86201. return this._horizontalBlurPostprocess1.kernel;
  86202. },
  86203. /**
  86204. * Sets the kernel size of the blur.
  86205. */
  86206. set: function (value) {
  86207. this._horizontalBlurPostprocess1.kernel = value;
  86208. this._verticalBlurPostprocess1.kernel = value;
  86209. this._horizontalBlurPostprocess2.kernel = value;
  86210. this._verticalBlurPostprocess2.kernel = value;
  86211. },
  86212. enumerable: true,
  86213. configurable: true
  86214. });
  86215. Object.defineProperty(GlowLayer.prototype, "intensity", {
  86216. /**
  86217. * Gets the glow intensity.
  86218. */
  86219. get: function () {
  86220. return this._intensity;
  86221. },
  86222. /**
  86223. * Sets the glow intensity.
  86224. */
  86225. set: function (value) {
  86226. this._intensity = value;
  86227. },
  86228. enumerable: true,
  86229. configurable: true
  86230. });
  86231. /**
  86232. * Get the effect name of the layer.
  86233. * @return The effect name
  86234. */
  86235. GlowLayer.prototype.getEffectName = function () {
  86236. return GlowLayer.EffectName;
  86237. };
  86238. /**
  86239. * Create the merge effect. This is the shader use to blit the information back
  86240. * to the main canvas at the end of the scene rendering.
  86241. */
  86242. GlowLayer.prototype._createMergeEffect = function () {
  86243. // Effect
  86244. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n");
  86245. };
  86246. /**
  86247. * Creates the render target textures and post processes used in the glow layer.
  86248. */
  86249. GlowLayer.prototype._createTextureAndPostProcesses = function () {
  86250. var _this = this;
  86251. var blurTextureWidth = this._mainTextureDesiredSize.width;
  86252. var blurTextureHeight = this._mainTextureDesiredSize.height;
  86253. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  86254. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  86255. this._blurTexture1 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT", {
  86256. width: blurTextureWidth,
  86257. height: blurTextureHeight
  86258. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  86259. this._blurTexture1.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86260. this._blurTexture1.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86261. this._blurTexture1.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  86262. this._blurTexture1.renderParticles = false;
  86263. this._blurTexture1.ignoreCameraViewport = true;
  86264. var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
  86265. var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
  86266. this._blurTexture2 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT2", {
  86267. width: blurTextureWidth2,
  86268. height: blurTextureHeight2
  86269. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  86270. this._blurTexture2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86271. this._blurTexture2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86272. this._blurTexture2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  86273. this._blurTexture2.renderParticles = false;
  86274. this._blurTexture2.ignoreCameraViewport = true;
  86275. this._textures = [this._blurTexture1, this._blurTexture2];
  86276. this._horizontalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerHBP1", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  86277. width: blurTextureWidth,
  86278. height: blurTextureHeight
  86279. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  86280. this._horizontalBlurPostprocess1.width = blurTextureWidth;
  86281. this._horizontalBlurPostprocess1.height = blurTextureHeight;
  86282. this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {
  86283. effect.setTexture("textureSampler", _this._mainTexture);
  86284. });
  86285. this._verticalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerVBP1", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  86286. width: blurTextureWidth,
  86287. height: blurTextureHeight
  86288. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  86289. this._horizontalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerHBP2", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  86290. width: blurTextureWidth2,
  86291. height: blurTextureHeight2
  86292. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  86293. this._horizontalBlurPostprocess2.width = blurTextureWidth2;
  86294. this._horizontalBlurPostprocess2.height = blurTextureHeight2;
  86295. this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {
  86296. effect.setTexture("textureSampler", _this._blurTexture1);
  86297. });
  86298. this._verticalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerVBP2", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  86299. width: blurTextureWidth2,
  86300. height: blurTextureHeight2
  86301. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  86302. this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  86303. this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
  86304. this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  86305. this._mainTexture.samples = this._options.mainTextureSamples;
  86306. this._mainTexture.onAfterUnbindObservable.add(function () {
  86307. var internalTexture = _this._blurTexture1.getInternalTexture();
  86308. if (internalTexture) {
  86309. _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);
  86310. internalTexture = _this._blurTexture2.getInternalTexture();
  86311. if (internalTexture) {
  86312. _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);
  86313. }
  86314. }
  86315. });
  86316. // Prevent autoClear.
  86317. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  86318. };
  86319. /**
  86320. * Checks for the readiness of the element composing the layer.
  86321. * @param subMesh the mesh to check for
  86322. * @param useInstances specify wether or not to use instances to render the mesh
  86323. * @param emissiveTexture the associated emissive texture used to generate the glow
  86324. * @return true if ready otherwise, false
  86325. */
  86326. GlowLayer.prototype.isReady = function (subMesh, useInstances) {
  86327. var material = subMesh.getMaterial();
  86328. var mesh = subMesh.getRenderingMesh();
  86329. if (!material || !mesh) {
  86330. return false;
  86331. }
  86332. var emissiveTexture = material.emissiveTexture;
  86333. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  86334. };
  86335. /**
  86336. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  86337. */
  86338. GlowLayer.prototype.needStencil = function () {
  86339. return false;
  86340. };
  86341. /**
  86342. * Implementation specific of rendering the generating effect on the main canvas.
  86343. * @param effect The effect used to render through
  86344. */
  86345. GlowLayer.prototype._internalRender = function (effect) {
  86346. // Texture
  86347. effect.setTexture("textureSampler", this._blurTexture1);
  86348. effect.setTexture("textureSampler2", this._blurTexture2);
  86349. effect.setFloat("offset", this._intensity);
  86350. // Cache
  86351. var engine = this._engine;
  86352. var previousStencilBuffer = engine.getStencilBuffer();
  86353. // Draw order
  86354. engine.setStencilBuffer(false);
  86355. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  86356. // Draw order
  86357. engine.setStencilBuffer(previousStencilBuffer);
  86358. };
  86359. /**
  86360. * Sets the required values for both the emissive texture and and the main color.
  86361. */
  86362. GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  86363. var textureLevel = 1.0;
  86364. if (this.customEmissiveTextureSelector) {
  86365. this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);
  86366. }
  86367. else {
  86368. if (material) {
  86369. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  86370. if (this._emissiveTextureAndColor.texture) {
  86371. textureLevel = this._emissiveTextureAndColor.texture.level;
  86372. }
  86373. }
  86374. else {
  86375. this._emissiveTextureAndColor.texture = null;
  86376. }
  86377. }
  86378. if (this.customEmissiveColorSelector) {
  86379. this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);
  86380. }
  86381. else {
  86382. if (material.emissiveColor) {
  86383. this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1.0);
  86384. }
  86385. else {
  86386. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  86387. }
  86388. }
  86389. };
  86390. /**
  86391. * Returns true if the mesh should render, otherwise false.
  86392. * @param mesh The mesh to render
  86393. * @returns true if it should render otherwise false
  86394. */
  86395. GlowLayer.prototype._shouldRenderMesh = function (mesh) {
  86396. return this.hasMesh(mesh);
  86397. };
  86398. /**
  86399. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.
  86400. * @param mesh The mesh to exclude from the glow layer
  86401. */
  86402. GlowLayer.prototype.addExcludedMesh = function (mesh) {
  86403. if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {
  86404. this._excludedMeshes.push(mesh.uniqueId);
  86405. }
  86406. };
  86407. /**
  86408. * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.
  86409. * @param mesh The mesh to remove
  86410. */
  86411. GlowLayer.prototype.removeExcludedMesh = function (mesh) {
  86412. var index = this._excludedMeshes.indexOf(mesh.uniqueId);
  86413. if (index !== -1) {
  86414. this._excludedMeshes.splice(index, 1);
  86415. }
  86416. };
  86417. /**
  86418. * Add a mesh in the inclusion list to impact or being impacted by the glow layer.
  86419. * @param mesh The mesh to include in the glow layer
  86420. */
  86421. GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {
  86422. if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {
  86423. this._includedOnlyMeshes.push(mesh.uniqueId);
  86424. }
  86425. };
  86426. /**
  86427. * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.
  86428. * @param mesh The mesh to remove
  86429. */
  86430. GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {
  86431. var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
  86432. if (index !== -1) {
  86433. this._includedOnlyMeshes.splice(index, 1);
  86434. }
  86435. };
  86436. /**
  86437. * Determine if a given mesh will be used in the glow layer
  86438. * @param mesh The mesh to test
  86439. * @returns true if the mesh will be highlighted by the current glow layer
  86440. */
  86441. GlowLayer.prototype.hasMesh = function (mesh) {
  86442. // Included Mesh
  86443. if (this._includedOnlyMeshes.length) {
  86444. return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
  86445. }
  86446. ;
  86447. // Excluded Mesh
  86448. if (this._excludedMeshes.length) {
  86449. return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
  86450. }
  86451. ;
  86452. return true;
  86453. };
  86454. /**
  86455. * Free any resources and references associated to a mesh.
  86456. * Internal use
  86457. * @param mesh The mesh to free.
  86458. */
  86459. GlowLayer.prototype._disposeMesh = function (mesh) {
  86460. this.removeIncludedOnlyMesh(mesh);
  86461. this.removeExcludedMesh(mesh);
  86462. };
  86463. /**
  86464. * Effect Name of the layer.
  86465. */
  86466. GlowLayer.EffectName = "GlowLayer";
  86467. /**
  86468. * The default blur kernel size used for the glow.
  86469. */
  86470. GlowLayer.DefaultBlurKernelSize = 32;
  86471. /**
  86472. * The default texture size ratio used for the glow.
  86473. */
  86474. GlowLayer.DefaultTextureRatio = 0.5;
  86475. return GlowLayer;
  86476. }(BABYLON.EffectLayer));
  86477. BABYLON.GlowLayer = GlowLayer;
  86478. })(BABYLON || (BABYLON = {}));
  86479. //# sourceMappingURL=babylon.glowLayer.js.map
  86480. var BABYLON;
  86481. (function (BABYLON) {
  86482. /**
  86483. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  86484. */
  86485. var AssetTaskState;
  86486. (function (AssetTaskState) {
  86487. /**
  86488. * Initialization
  86489. */
  86490. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  86491. /**
  86492. * Running
  86493. */
  86494. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  86495. /**
  86496. * Done
  86497. */
  86498. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  86499. /**
  86500. * Error
  86501. */
  86502. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  86503. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  86504. /**
  86505. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  86506. */
  86507. var AbstractAssetTask = /** @class */ (function () {
  86508. /**
  86509. * Creates a new {BABYLON.AssetsManager}
  86510. * @param name defines the name of the task
  86511. */
  86512. function AbstractAssetTask(
  86513. /**
  86514. * Task name
  86515. */ name) {
  86516. this.name = name;
  86517. this._isCompleted = false;
  86518. this._taskState = AssetTaskState.INIT;
  86519. }
  86520. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  86521. /**
  86522. * Get if the task is completed
  86523. */
  86524. get: function () {
  86525. return this._isCompleted;
  86526. },
  86527. enumerable: true,
  86528. configurable: true
  86529. });
  86530. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  86531. /**
  86532. * Gets the current state of the task
  86533. */
  86534. get: function () {
  86535. return this._taskState;
  86536. },
  86537. enumerable: true,
  86538. configurable: true
  86539. });
  86540. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  86541. /**
  86542. * Gets the current error object (if task is in error)
  86543. */
  86544. get: function () {
  86545. return this._errorObject;
  86546. },
  86547. enumerable: true,
  86548. configurable: true
  86549. });
  86550. /**
  86551. * Internal only
  86552. * @ignore
  86553. */
  86554. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  86555. if (this._errorObject) {
  86556. return;
  86557. }
  86558. this._errorObject = {
  86559. message: message,
  86560. exception: exception
  86561. };
  86562. };
  86563. /**
  86564. * Execute the current task
  86565. * @param scene defines the scene where you want your assets to be loaded
  86566. * @param onSuccess is a callback called when the task is successfully executed
  86567. * @param onError is a callback called if an error occurs
  86568. */
  86569. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  86570. var _this = this;
  86571. this._taskState = AssetTaskState.RUNNING;
  86572. this.runTask(scene, function () {
  86573. _this.onDoneCallback(onSuccess, onError);
  86574. }, function (msg, exception) {
  86575. _this.onErrorCallback(onError, msg, exception);
  86576. });
  86577. };
  86578. /**
  86579. * Execute the current task
  86580. * @param scene defines the scene where you want your assets to be loaded
  86581. * @param onSuccess is a callback called when the task is successfully executed
  86582. * @param onError is a callback called if an error occurs
  86583. */
  86584. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  86585. throw new Error("runTask is not implemented");
  86586. };
  86587. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  86588. this._taskState = AssetTaskState.ERROR;
  86589. this._errorObject = {
  86590. message: message,
  86591. exception: exception
  86592. };
  86593. if (this.onError) {
  86594. this.onError(this, message, exception);
  86595. }
  86596. onError();
  86597. };
  86598. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  86599. try {
  86600. this._taskState = AssetTaskState.DONE;
  86601. this._isCompleted = true;
  86602. if (this.onSuccess) {
  86603. this.onSuccess(this);
  86604. }
  86605. onSuccess();
  86606. }
  86607. catch (e) {
  86608. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  86609. }
  86610. };
  86611. return AbstractAssetTask;
  86612. }());
  86613. BABYLON.AbstractAssetTask = AbstractAssetTask;
  86614. /**
  86615. * Class used to share progress information about assets loading
  86616. */
  86617. var AssetsProgressEvent = /** @class */ (function () {
  86618. /**
  86619. * Creates a {BABYLON.AssetsProgressEvent}
  86620. * @param remainingCount defines the number of remaining tasks to process
  86621. * @param totalCount defines the total number of tasks
  86622. * @param task defines the task that was just processed
  86623. */
  86624. function AssetsProgressEvent(remainingCount, totalCount, task) {
  86625. this.remainingCount = remainingCount;
  86626. this.totalCount = totalCount;
  86627. this.task = task;
  86628. }
  86629. return AssetsProgressEvent;
  86630. }());
  86631. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  86632. /**
  86633. * Define a task used by {BABYLON.AssetsManager} to load meshes
  86634. */
  86635. var MeshAssetTask = /** @class */ (function (_super) {
  86636. __extends(MeshAssetTask, _super);
  86637. /**
  86638. * Creates a new {BABYLON.MeshAssetTask}
  86639. * @param name defines the name of the task
  86640. * @param meshesNames defines the list of mesh's names you want to load
  86641. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  86642. * @param sceneFilename defines the filename of the scene to load from
  86643. */
  86644. function MeshAssetTask(
  86645. /**
  86646. * Defines the name of the task
  86647. */
  86648. name,
  86649. /**
  86650. * Defines the list of mesh's names you want to load
  86651. */
  86652. meshesNames,
  86653. /**
  86654. * Defines the root url to use as a base to load your meshes and associated resources
  86655. */
  86656. rootUrl,
  86657. /**
  86658. * Defines the filename of the scene to load from
  86659. */
  86660. sceneFilename) {
  86661. var _this = _super.call(this, name) || this;
  86662. _this.name = name;
  86663. _this.meshesNames = meshesNames;
  86664. _this.rootUrl = rootUrl;
  86665. _this.sceneFilename = sceneFilename;
  86666. return _this;
  86667. }
  86668. /**
  86669. * Execute the current task
  86670. * @param scene defines the scene where you want your assets to be loaded
  86671. * @param onSuccess is a callback called when the task is successfully executed
  86672. * @param onError is a callback called if an error occurs
  86673. */
  86674. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  86675. var _this = this;
  86676. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  86677. _this.loadedMeshes = meshes;
  86678. _this.loadedParticleSystems = particleSystems;
  86679. _this.loadedSkeletons = skeletons;
  86680. onSuccess();
  86681. }, null, function (scene, message, exception) {
  86682. onError(message, exception);
  86683. });
  86684. };
  86685. return MeshAssetTask;
  86686. }(AbstractAssetTask));
  86687. BABYLON.MeshAssetTask = MeshAssetTask;
  86688. /**
  86689. * Define a task used by {BABYLON.AssetsManager} to load text content
  86690. */
  86691. var TextFileAssetTask = /** @class */ (function (_super) {
  86692. __extends(TextFileAssetTask, _super);
  86693. /**
  86694. * Creates a new TextFileAssetTask object
  86695. * @param name defines the name of the task
  86696. * @param url defines the location of the file to load
  86697. */
  86698. function TextFileAssetTask(
  86699. /**
  86700. * Defines the name of the task
  86701. */
  86702. name,
  86703. /**
  86704. * Defines the location of the file to load
  86705. */
  86706. url) {
  86707. var _this = _super.call(this, name) || this;
  86708. _this.name = name;
  86709. _this.url = url;
  86710. return _this;
  86711. }
  86712. /**
  86713. * Execute the current task
  86714. * @param scene defines the scene where you want your assets to be loaded
  86715. * @param onSuccess is a callback called when the task is successfully executed
  86716. * @param onError is a callback called if an error occurs
  86717. */
  86718. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  86719. var _this = this;
  86720. scene._loadFile(this.url, function (data) {
  86721. _this.text = data;
  86722. onSuccess();
  86723. }, undefined, false, false, function (request, exception) {
  86724. if (request) {
  86725. onError(request.status + " " + request.statusText, exception);
  86726. }
  86727. });
  86728. };
  86729. return TextFileAssetTask;
  86730. }(AbstractAssetTask));
  86731. BABYLON.TextFileAssetTask = TextFileAssetTask;
  86732. /**
  86733. * Define a task used by {BABYLON.AssetsManager} to load binary data
  86734. */
  86735. var BinaryFileAssetTask = /** @class */ (function (_super) {
  86736. __extends(BinaryFileAssetTask, _super);
  86737. /**
  86738. * Creates a new BinaryFileAssetTask object
  86739. * @param name defines the name of the new task
  86740. * @param url defines the location of the file to load
  86741. */
  86742. function BinaryFileAssetTask(
  86743. /**
  86744. * Defines the name of the task
  86745. */
  86746. name,
  86747. /**
  86748. * Defines the location of the file to load
  86749. */
  86750. url) {
  86751. var _this = _super.call(this, name) || this;
  86752. _this.name = name;
  86753. _this.url = url;
  86754. return _this;
  86755. }
  86756. /**
  86757. * Execute the current task
  86758. * @param scene defines the scene where you want your assets to be loaded
  86759. * @param onSuccess is a callback called when the task is successfully executed
  86760. * @param onError is a callback called if an error occurs
  86761. */
  86762. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  86763. var _this = this;
  86764. scene._loadFile(this.url, function (data) {
  86765. _this.data = data;
  86766. onSuccess();
  86767. }, undefined, true, true, function (request, exception) {
  86768. if (request) {
  86769. onError(request.status + " " + request.statusText, exception);
  86770. }
  86771. });
  86772. };
  86773. return BinaryFileAssetTask;
  86774. }(AbstractAssetTask));
  86775. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  86776. /**
  86777. * Define a task used by {BABYLON.AssetsManager} to load images
  86778. */
  86779. var ImageAssetTask = /** @class */ (function (_super) {
  86780. __extends(ImageAssetTask, _super);
  86781. /**
  86782. * Creates a new ImageAssetTask
  86783. * @param name defines the name of the task
  86784. * @param url defines the location of the image to load
  86785. */
  86786. function ImageAssetTask(
  86787. /**
  86788. * Defines the name of the task
  86789. */
  86790. name,
  86791. /**
  86792. * Defines the location of the image to load
  86793. */
  86794. url) {
  86795. var _this = _super.call(this, name) || this;
  86796. _this.name = name;
  86797. _this.url = url;
  86798. return _this;
  86799. }
  86800. /**
  86801. * Execute the current task
  86802. * @param scene defines the scene where you want your assets to be loaded
  86803. * @param onSuccess is a callback called when the task is successfully executed
  86804. * @param onError is a callback called if an error occurs
  86805. */
  86806. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  86807. var _this = this;
  86808. var img = new Image();
  86809. BABYLON.Tools.SetCorsBehavior(this.url, img);
  86810. img.onload = function () {
  86811. _this.image = img;
  86812. onSuccess();
  86813. };
  86814. img.onerror = function (err) {
  86815. onError("Error loading image", err);
  86816. };
  86817. img.src = this.url;
  86818. };
  86819. return ImageAssetTask;
  86820. }(AbstractAssetTask));
  86821. BABYLON.ImageAssetTask = ImageAssetTask;
  86822. /**
  86823. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  86824. */
  86825. var TextureAssetTask = /** @class */ (function (_super) {
  86826. __extends(TextureAssetTask, _super);
  86827. /**
  86828. * Creates a new TextureAssetTask object
  86829. * @param name defines the name of the task
  86830. * @param url defines the location of the file to load
  86831. * @param noMipmap defines if mipmap should not be generated (default is false)
  86832. * @param invertY defines if texture must be inverted on Y axis (default is false)
  86833. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  86834. */
  86835. function TextureAssetTask(
  86836. /**
  86837. * Defines the name of the task
  86838. */
  86839. name,
  86840. /**
  86841. * Defines the location of the file to load
  86842. */
  86843. url,
  86844. /**
  86845. * Defines if mipmap should not be generated (default is false)
  86846. */
  86847. noMipmap,
  86848. /**
  86849. * Defines if texture must be inverted on Y axis (default is false)
  86850. */
  86851. invertY,
  86852. /**
  86853. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  86854. */
  86855. samplingMode) {
  86856. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  86857. var _this = _super.call(this, name) || this;
  86858. _this.name = name;
  86859. _this.url = url;
  86860. _this.noMipmap = noMipmap;
  86861. _this.invertY = invertY;
  86862. _this.samplingMode = samplingMode;
  86863. return _this;
  86864. }
  86865. /**
  86866. * Execute the current task
  86867. * @param scene defines the scene where you want your assets to be loaded
  86868. * @param onSuccess is a callback called when the task is successfully executed
  86869. * @param onError is a callback called if an error occurs
  86870. */
  86871. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  86872. var onload = function () {
  86873. onSuccess();
  86874. };
  86875. var onerror = function (message, exception) {
  86876. onError(message, exception);
  86877. };
  86878. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  86879. };
  86880. return TextureAssetTask;
  86881. }(AbstractAssetTask));
  86882. BABYLON.TextureAssetTask = TextureAssetTask;
  86883. /**
  86884. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  86885. */
  86886. var CubeTextureAssetTask = /** @class */ (function (_super) {
  86887. __extends(CubeTextureAssetTask, _super);
  86888. /**
  86889. * Creates a new CubeTextureAssetTask
  86890. * @param name defines the name of the task
  86891. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  86892. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  86893. * @param noMipmap defines if mipmaps should not be generated (default is false)
  86894. * @param files defines the explicit list of files (undefined by default)
  86895. */
  86896. function CubeTextureAssetTask(
  86897. /**
  86898. * Defines the name of the task
  86899. */
  86900. name,
  86901. /**
  86902. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  86903. */
  86904. url,
  86905. /**
  86906. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  86907. */
  86908. extensions,
  86909. /**
  86910. * Defines if mipmaps should not be generated (default is false)
  86911. */
  86912. noMipmap,
  86913. /**
  86914. * Defines the explicit list of files (undefined by default)
  86915. */
  86916. files) {
  86917. var _this = _super.call(this, name) || this;
  86918. _this.name = name;
  86919. _this.url = url;
  86920. _this.extensions = extensions;
  86921. _this.noMipmap = noMipmap;
  86922. _this.files = files;
  86923. return _this;
  86924. }
  86925. /**
  86926. * Execute the current task
  86927. * @param scene defines the scene where you want your assets to be loaded
  86928. * @param onSuccess is a callback called when the task is successfully executed
  86929. * @param onError is a callback called if an error occurs
  86930. */
  86931. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  86932. var onload = function () {
  86933. onSuccess();
  86934. };
  86935. var onerror = function (message, exception) {
  86936. onError(message, exception);
  86937. };
  86938. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  86939. };
  86940. return CubeTextureAssetTask;
  86941. }(AbstractAssetTask));
  86942. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  86943. /**
  86944. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  86945. */
  86946. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  86947. __extends(HDRCubeTextureAssetTask, _super);
  86948. /**
  86949. * Creates a new HDRCubeTextureAssetTask object
  86950. * @param name defines the name of the task
  86951. * @param url defines the location of the file to load
  86952. * @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.
  86953. * @param noMipmap defines if mipmaps should not be generated (default is false)
  86954. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  86955. * @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)
  86956. * @param usePMREMGenerator specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  86957. */
  86958. function HDRCubeTextureAssetTask(
  86959. /**
  86960. * Defines the name of the task
  86961. */
  86962. name,
  86963. /**
  86964. * Defines the location of the file to load
  86965. */
  86966. url,
  86967. /**
  86968. * 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.
  86969. */
  86970. size,
  86971. /**
  86972. * Defines if mipmaps should not be generated (default is false)
  86973. */
  86974. noMipmap,
  86975. /**
  86976. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  86977. */
  86978. generateHarmonics,
  86979. /**
  86980. * 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)
  86981. */
  86982. useInGammaSpace,
  86983. /**
  86984. * Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  86985. */
  86986. usePMREMGenerator) {
  86987. if (noMipmap === void 0) { noMipmap = false; }
  86988. if (generateHarmonics === void 0) { generateHarmonics = true; }
  86989. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  86990. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  86991. var _this = _super.call(this, name) || this;
  86992. _this.name = name;
  86993. _this.url = url;
  86994. _this.size = size;
  86995. _this.noMipmap = noMipmap;
  86996. _this.generateHarmonics = generateHarmonics;
  86997. _this.useInGammaSpace = useInGammaSpace;
  86998. _this.usePMREMGenerator = usePMREMGenerator;
  86999. return _this;
  87000. }
  87001. /**
  87002. * Execute the current task
  87003. * @param scene defines the scene where you want your assets to be loaded
  87004. * @param onSuccess is a callback called when the task is successfully executed
  87005. * @param onError is a callback called if an error occurs
  87006. */
  87007. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  87008. var onload = function () {
  87009. onSuccess();
  87010. };
  87011. var onerror = function (message, exception) {
  87012. onError(message, exception);
  87013. };
  87014. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.useInGammaSpace, this.usePMREMGenerator, onload, onerror);
  87015. };
  87016. return HDRCubeTextureAssetTask;
  87017. }(AbstractAssetTask));
  87018. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  87019. /**
  87020. * This class can be used to easily import assets into a scene
  87021. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  87022. */
  87023. var AssetsManager = /** @class */ (function () {
  87024. /**
  87025. * Creates a new AssetsManager
  87026. * @param scene defines the scene to work on
  87027. */
  87028. function AssetsManager(scene) {
  87029. this._isLoading = false;
  87030. this._tasks = new Array();
  87031. this._waitingTasksCount = 0;
  87032. this._totalTasksCount = 0;
  87033. /**
  87034. * Observable called when all tasks are processed
  87035. */
  87036. this.onTaskSuccessObservable = new BABYLON.Observable();
  87037. /**
  87038. * Observable called when a task had an error
  87039. */
  87040. this.onTaskErrorObservable = new BABYLON.Observable();
  87041. /**
  87042. * Observable called when a task is successful
  87043. */
  87044. this.onTasksDoneObservable = new BABYLON.Observable();
  87045. /**
  87046. * Observable called when a task is done (whatever the result is)
  87047. */
  87048. this.onProgressObservable = new BABYLON.Observable();
  87049. /**
  87050. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  87051. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  87052. */
  87053. this.useDefaultLoadingScreen = true;
  87054. this._scene = scene;
  87055. }
  87056. /**
  87057. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  87058. * @param taskName defines the name of the new task
  87059. * @param meshesNames defines the name of meshes to load
  87060. * @param rootUrl defines the root url to use to locate files
  87061. * @param sceneFilename defines the filename of the scene file
  87062. * @returns a new {BABYLON.MeshAssetTask} object
  87063. */
  87064. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  87065. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  87066. this._tasks.push(task);
  87067. return task;
  87068. };
  87069. /**
  87070. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  87071. * @param taskName defines the name of the new task
  87072. * @param url defines the url of the file to load
  87073. * @returns a new {BABYLON.TextFileAssetTask} object
  87074. */
  87075. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  87076. var task = new TextFileAssetTask(taskName, url);
  87077. this._tasks.push(task);
  87078. return task;
  87079. };
  87080. /**
  87081. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  87082. * @param taskName defines the name of the new task
  87083. * @param url defines the url of the file to load
  87084. * @returns a new {BABYLON.BinaryFileAssetTask} object
  87085. */
  87086. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  87087. var task = new BinaryFileAssetTask(taskName, url);
  87088. this._tasks.push(task);
  87089. return task;
  87090. };
  87091. /**
  87092. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  87093. * @param taskName defines the name of the new task
  87094. * @param url defines the url of the file to load
  87095. * @returns a new {BABYLON.ImageAssetTask} object
  87096. */
  87097. AssetsManager.prototype.addImageTask = function (taskName, url) {
  87098. var task = new ImageAssetTask(taskName, url);
  87099. this._tasks.push(task);
  87100. return task;
  87101. };
  87102. /**
  87103. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  87104. * @param taskName defines the name of the new task
  87105. * @param url defines the url of the file to load
  87106. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  87107. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  87108. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  87109. * @returns a new {BABYLON.TextureAssetTask} object
  87110. */
  87111. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  87112. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  87113. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  87114. this._tasks.push(task);
  87115. return task;
  87116. };
  87117. /**
  87118. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  87119. * @param taskName defines the name of the new task
  87120. * @param url defines the url of the file to load
  87121. * @param extensions defines the extension to use to load the cube map (can be null)
  87122. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  87123. * @param files defines the list of files to load (can be null)
  87124. * @returns a new {BABYLON.CubeTextureAssetTask} object
  87125. */
  87126. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  87127. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  87128. this._tasks.push(task);
  87129. return task;
  87130. };
  87131. /**
  87132. *
  87133. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  87134. * @param taskName defines the name of the new task
  87135. * @param url defines the url of the file to load
  87136. * @param size defines the size you want for the cubemap (can be null)
  87137. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  87138. * @param generateHarmonics defines if you want to automatically generate (true by default)
  87139. * @param useInGammaSpace defines if the texture must be considered in gamma space (false by default)
  87140. * @param usePMREMGenerator is a reserved parameter and must be set to false or ignored
  87141. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  87142. */
  87143. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  87144. if (noMipmap === void 0) { noMipmap = false; }
  87145. if (generateHarmonics === void 0) { generateHarmonics = true; }
  87146. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  87147. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  87148. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator);
  87149. this._tasks.push(task);
  87150. return task;
  87151. };
  87152. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  87153. var _this = this;
  87154. this._waitingTasksCount--;
  87155. try {
  87156. if (task.taskState === AssetTaskState.DONE) {
  87157. // Let's remove successfull tasks
  87158. BABYLON.Tools.SetImmediate(function () {
  87159. var index = _this._tasks.indexOf(task);
  87160. if (index > -1) {
  87161. _this._tasks.splice(index, 1);
  87162. }
  87163. });
  87164. }
  87165. if (this.onProgress) {
  87166. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  87167. }
  87168. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  87169. }
  87170. catch (e) {
  87171. BABYLON.Tools.Error("Error running progress callbacks.");
  87172. console.log(e);
  87173. }
  87174. if (this._waitingTasksCount === 0) {
  87175. try {
  87176. if (this.onFinish) {
  87177. this.onFinish(this._tasks);
  87178. }
  87179. this.onTasksDoneObservable.notifyObservers(this._tasks);
  87180. }
  87181. catch (e) {
  87182. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  87183. console.log(e);
  87184. }
  87185. this._isLoading = false;
  87186. this._scene.getEngine().hideLoadingUI();
  87187. }
  87188. };
  87189. AssetsManager.prototype._runTask = function (task) {
  87190. var _this = this;
  87191. var done = function () {
  87192. try {
  87193. if (_this.onTaskSuccess) {
  87194. _this.onTaskSuccess(task);
  87195. }
  87196. _this.onTaskSuccessObservable.notifyObservers(task);
  87197. _this._decreaseWaitingTasksCount(task);
  87198. }
  87199. catch (e) {
  87200. error("Error executing task success callbacks", e);
  87201. }
  87202. };
  87203. var error = function (message, exception) {
  87204. task._setErrorObject(message, exception);
  87205. if (_this.onTaskError) {
  87206. _this.onTaskError(task);
  87207. }
  87208. _this.onTaskErrorObservable.notifyObservers(task);
  87209. _this._decreaseWaitingTasksCount(task);
  87210. };
  87211. task.run(this._scene, done, error);
  87212. };
  87213. /**
  87214. * Reset the {BABYLON.AssetsManager} and remove all tasks
  87215. * @return the current instance of the {BABYLON.AssetsManager}
  87216. */
  87217. AssetsManager.prototype.reset = function () {
  87218. this._isLoading = false;
  87219. this._tasks = new Array();
  87220. return this;
  87221. };
  87222. /**
  87223. * Start the loading process
  87224. * @return the current instance of the {BABYLON.AssetsManager}
  87225. */
  87226. AssetsManager.prototype.load = function () {
  87227. if (this._isLoading) {
  87228. return this;
  87229. }
  87230. this._isLoading = true;
  87231. this._waitingTasksCount = this._tasks.length;
  87232. this._totalTasksCount = this._tasks.length;
  87233. if (this._waitingTasksCount === 0) {
  87234. this._isLoading = false;
  87235. if (this.onFinish) {
  87236. this.onFinish(this._tasks);
  87237. }
  87238. this.onTasksDoneObservable.notifyObservers(this._tasks);
  87239. return this;
  87240. }
  87241. if (this.useDefaultLoadingScreen) {
  87242. this._scene.getEngine().displayLoadingUI();
  87243. }
  87244. for (var index = 0; index < this._tasks.length; index++) {
  87245. var task = this._tasks[index];
  87246. this._runTask(task);
  87247. }
  87248. return this;
  87249. };
  87250. return AssetsManager;
  87251. }());
  87252. BABYLON.AssetsManager = AssetsManager;
  87253. })(BABYLON || (BABYLON = {}));
  87254. //# sourceMappingURL=babylon.assetsManager.js.map
  87255. var BABYLON;
  87256. (function (BABYLON) {
  87257. var serializedGeometries = [];
  87258. var serializeGeometry = function (geometry, serializationGeometries) {
  87259. if (serializedGeometries[geometry.id]) {
  87260. return;
  87261. }
  87262. if (geometry.doNotSerialize) {
  87263. return;
  87264. }
  87265. if (geometry instanceof BABYLON.BoxGeometry) {
  87266. serializationGeometries.boxes.push(geometry.serialize());
  87267. }
  87268. else if (geometry instanceof BABYLON.SphereGeometry) {
  87269. serializationGeometries.spheres.push(geometry.serialize());
  87270. }
  87271. else if (geometry instanceof BABYLON.CylinderGeometry) {
  87272. serializationGeometries.cylinders.push(geometry.serialize());
  87273. }
  87274. else if (geometry instanceof BABYLON.TorusGeometry) {
  87275. serializationGeometries.toruses.push(geometry.serialize());
  87276. }
  87277. else if (geometry instanceof BABYLON.GroundGeometry) {
  87278. serializationGeometries.grounds.push(geometry.serialize());
  87279. }
  87280. else if (geometry instanceof BABYLON.Plane) {
  87281. serializationGeometries.planes.push(geometry.serialize());
  87282. }
  87283. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  87284. serializationGeometries.torusKnots.push(geometry.serialize());
  87285. }
  87286. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  87287. throw new Error("Unknown primitive type");
  87288. }
  87289. else {
  87290. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  87291. }
  87292. serializedGeometries[geometry.id] = true;
  87293. };
  87294. var serializeMesh = function (mesh, serializationScene) {
  87295. var serializationObject = {};
  87296. // Geometry
  87297. var geometry = mesh._geometry;
  87298. if (geometry) {
  87299. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  87300. // 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
  87301. serializeGeometry(geometry, serializationScene.geometries);
  87302. }
  87303. }
  87304. // Custom
  87305. if (mesh.serialize) {
  87306. mesh.serialize(serializationObject);
  87307. }
  87308. return serializationObject;
  87309. };
  87310. var finalizeSingleMesh = function (mesh, serializationObject) {
  87311. //only works if the mesh is already loaded
  87312. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  87313. //serialize material
  87314. if (mesh.material) {
  87315. if (mesh.material instanceof BABYLON.StandardMaterial) {
  87316. serializationObject.materials = serializationObject.materials || [];
  87317. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  87318. serializationObject.materials.push(mesh.material.serialize());
  87319. }
  87320. }
  87321. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  87322. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  87323. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  87324. serializationObject.multiMaterials.push(mesh.material.serialize());
  87325. }
  87326. }
  87327. }
  87328. //serialize geometry
  87329. var geometry = mesh._geometry;
  87330. if (geometry) {
  87331. if (!serializationObject.geometries) {
  87332. serializationObject.geometries = {};
  87333. serializationObject.geometries.boxes = [];
  87334. serializationObject.geometries.spheres = [];
  87335. serializationObject.geometries.cylinders = [];
  87336. serializationObject.geometries.toruses = [];
  87337. serializationObject.geometries.grounds = [];
  87338. serializationObject.geometries.planes = [];
  87339. serializationObject.geometries.torusKnots = [];
  87340. serializationObject.geometries.vertexData = [];
  87341. }
  87342. serializeGeometry(geometry, serializationObject.geometries);
  87343. }
  87344. // Skeletons
  87345. if (mesh.skeleton) {
  87346. serializationObject.skeletons = serializationObject.skeletons || [];
  87347. serializationObject.skeletons.push(mesh.skeleton.serialize());
  87348. }
  87349. //serialize the actual mesh
  87350. serializationObject.meshes = serializationObject.meshes || [];
  87351. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  87352. }
  87353. };
  87354. var SceneSerializer = /** @class */ (function () {
  87355. function SceneSerializer() {
  87356. }
  87357. SceneSerializer.ClearCache = function () {
  87358. serializedGeometries = [];
  87359. };
  87360. SceneSerializer.Serialize = function (scene) {
  87361. var serializationObject = {};
  87362. SceneSerializer.ClearCache();
  87363. // Scene
  87364. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  87365. serializationObject.autoClear = scene.autoClear;
  87366. serializationObject.clearColor = scene.clearColor.asArray();
  87367. serializationObject.ambientColor = scene.ambientColor.asArray();
  87368. serializationObject.gravity = scene.gravity.asArray();
  87369. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  87370. serializationObject.workerCollisions = scene.workerCollisions;
  87371. // Fog
  87372. if (scene.fogMode && scene.fogMode !== 0) {
  87373. serializationObject.fogMode = scene.fogMode;
  87374. serializationObject.fogColor = scene.fogColor.asArray();
  87375. serializationObject.fogStart = scene.fogStart;
  87376. serializationObject.fogEnd = scene.fogEnd;
  87377. serializationObject.fogDensity = scene.fogDensity;
  87378. }
  87379. //Physics
  87380. if (scene.isPhysicsEnabled()) {
  87381. var physicEngine = scene.getPhysicsEngine();
  87382. if (physicEngine) {
  87383. serializationObject.physicsEnabled = true;
  87384. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  87385. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  87386. }
  87387. }
  87388. // Metadata
  87389. if (scene.metadata) {
  87390. serializationObject.metadata = scene.metadata;
  87391. }
  87392. // Morph targets
  87393. serializationObject.morphTargetManagers = [];
  87394. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  87395. var abstractMesh = _a[_i];
  87396. var manager = abstractMesh.morphTargetManager;
  87397. if (manager) {
  87398. serializationObject.morphTargetManagers.push(manager.serialize());
  87399. }
  87400. }
  87401. // Lights
  87402. serializationObject.lights = [];
  87403. var index;
  87404. var light;
  87405. for (index = 0; index < scene.lights.length; index++) {
  87406. light = scene.lights[index];
  87407. if (!light.doNotSerialize) {
  87408. serializationObject.lights.push(light.serialize());
  87409. }
  87410. }
  87411. // Cameras
  87412. serializationObject.cameras = [];
  87413. for (index = 0; index < scene.cameras.length; index++) {
  87414. var camera = scene.cameras[index];
  87415. if (!camera.doNotSerialize) {
  87416. serializationObject.cameras.push(camera.serialize());
  87417. }
  87418. }
  87419. if (scene.activeCamera) {
  87420. serializationObject.activeCameraID = scene.activeCamera.id;
  87421. }
  87422. // Animations
  87423. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  87424. // Materials
  87425. serializationObject.materials = [];
  87426. serializationObject.multiMaterials = [];
  87427. var material;
  87428. for (index = 0; index < scene.materials.length; index++) {
  87429. material = scene.materials[index];
  87430. if (!material.doNotSerialize) {
  87431. serializationObject.materials.push(material.serialize());
  87432. }
  87433. }
  87434. // MultiMaterials
  87435. serializationObject.multiMaterials = [];
  87436. for (index = 0; index < scene.multiMaterials.length; index++) {
  87437. var multiMaterial = scene.multiMaterials[index];
  87438. serializationObject.multiMaterials.push(multiMaterial.serialize());
  87439. }
  87440. // Environment texture
  87441. if (scene.environmentTexture) {
  87442. serializationObject.environmentTexture = scene.environmentTexture.name;
  87443. }
  87444. // Skeletons
  87445. serializationObject.skeletons = [];
  87446. for (index = 0; index < scene.skeletons.length; index++) {
  87447. var skeleton = scene.skeletons[index];
  87448. if (!skeleton.doNotSerialize) {
  87449. serializationObject.skeletons.push(skeleton.serialize());
  87450. }
  87451. }
  87452. // Transform nodes
  87453. serializationObject.transformNodes = [];
  87454. for (index = 0; index < scene.transformNodes.length; index++) {
  87455. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  87456. }
  87457. // Geometries
  87458. serializationObject.geometries = {};
  87459. serializationObject.geometries.boxes = [];
  87460. serializationObject.geometries.spheres = [];
  87461. serializationObject.geometries.cylinders = [];
  87462. serializationObject.geometries.toruses = [];
  87463. serializationObject.geometries.grounds = [];
  87464. serializationObject.geometries.planes = [];
  87465. serializationObject.geometries.torusKnots = [];
  87466. serializationObject.geometries.vertexData = [];
  87467. serializedGeometries = [];
  87468. var geometries = scene.getGeometries();
  87469. for (index = 0; index < geometries.length; index++) {
  87470. var geometry = geometries[index];
  87471. if (geometry.isReady()) {
  87472. serializeGeometry(geometry, serializationObject.geometries);
  87473. }
  87474. }
  87475. // Meshes
  87476. serializationObject.meshes = [];
  87477. for (index = 0; index < scene.meshes.length; index++) {
  87478. var abstractMesh = scene.meshes[index];
  87479. if (abstractMesh instanceof BABYLON.Mesh) {
  87480. var mesh = abstractMesh;
  87481. if (!mesh.doNotSerialize) {
  87482. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  87483. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  87484. }
  87485. }
  87486. }
  87487. }
  87488. // Particles Systems
  87489. serializationObject.particleSystems = [];
  87490. for (index = 0; index < scene.particleSystems.length; index++) {
  87491. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  87492. }
  87493. // Lens flares
  87494. serializationObject.lensFlareSystems = [];
  87495. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  87496. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  87497. }
  87498. // Shadows
  87499. serializationObject.shadowGenerators = [];
  87500. for (index = 0; index < scene.lights.length; index++) {
  87501. light = scene.lights[index];
  87502. var shadowGenerator = light.getShadowGenerator();
  87503. if (shadowGenerator) {
  87504. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  87505. }
  87506. }
  87507. // Action Manager
  87508. if (scene.actionManager) {
  87509. serializationObject.actions = scene.actionManager.serialize("scene");
  87510. }
  87511. // Audio
  87512. serializationObject.sounds = [];
  87513. for (index = 0; index < scene.soundTracks.length; index++) {
  87514. var soundtrack = scene.soundTracks[index];
  87515. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  87516. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  87517. }
  87518. }
  87519. return serializationObject;
  87520. };
  87521. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  87522. if (withParents === void 0) { withParents = false; }
  87523. if (withChildren === void 0) { withChildren = false; }
  87524. var serializationObject = {};
  87525. SceneSerializer.ClearCache();
  87526. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  87527. if (withParents || withChildren) {
  87528. //deliberate for loop! not for each, appended should be processed as well.
  87529. for (var i = 0; i < toSerialize.length; ++i) {
  87530. if (withChildren) {
  87531. toSerialize[i].getDescendants().forEach(function (node) {
  87532. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  87533. toSerialize.push(node);
  87534. }
  87535. });
  87536. }
  87537. //make sure the array doesn't contain the object already
  87538. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  87539. toSerialize.push(toSerialize[i].parent);
  87540. }
  87541. }
  87542. }
  87543. toSerialize.forEach(function (mesh) {
  87544. finalizeSingleMesh(mesh, serializationObject);
  87545. });
  87546. return serializationObject;
  87547. };
  87548. return SceneSerializer;
  87549. }());
  87550. BABYLON.SceneSerializer = SceneSerializer;
  87551. })(BABYLON || (BABYLON = {}));
  87552. //# sourceMappingURL=babylon.sceneSerializer.js.map
  87553. var BABYLON;
  87554. (function (BABYLON) {
  87555. var ReflectionProbe = /** @class */ (function () {
  87556. function ReflectionProbe(name, size, scene, generateMipMaps) {
  87557. if (generateMipMaps === void 0) { generateMipMaps = true; }
  87558. var _this = this;
  87559. this.name = name;
  87560. this._viewMatrix = BABYLON.Matrix.Identity();
  87561. this._target = BABYLON.Vector3.Zero();
  87562. this._add = BABYLON.Vector3.Zero();
  87563. this._invertYAxis = false;
  87564. this.position = BABYLON.Vector3.Zero();
  87565. this._scene = scene;
  87566. this._scene.reflectionProbes.push(this);
  87567. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  87568. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  87569. switch (faceIndex) {
  87570. case 0:
  87571. _this._add.copyFromFloats(1, 0, 0);
  87572. break;
  87573. case 1:
  87574. _this._add.copyFromFloats(-1, 0, 0);
  87575. break;
  87576. case 2:
  87577. _this._add.copyFromFloats(0, _this._invertYAxis ? 1 : -1, 0);
  87578. break;
  87579. case 3:
  87580. _this._add.copyFromFloats(0, _this._invertYAxis ? -1 : 1, 0);
  87581. break;
  87582. case 4:
  87583. _this._add.copyFromFloats(0, 0, 1);
  87584. break;
  87585. case 5:
  87586. _this._add.copyFromFloats(0, 0, -1);
  87587. break;
  87588. }
  87589. if (_this._attachedMesh) {
  87590. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  87591. }
  87592. _this.position.addToRef(_this._add, _this._target);
  87593. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  87594. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  87595. scene._forcedViewPosition = _this.position;
  87596. });
  87597. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  87598. scene._forcedViewPosition = null;
  87599. scene.updateTransformMatrix(true);
  87600. });
  87601. if (scene.activeCamera) {
  87602. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  87603. }
  87604. }
  87605. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  87606. get: function () {
  87607. return this._renderTargetTexture.samples;
  87608. },
  87609. set: function (value) {
  87610. this._renderTargetTexture.samples = value;
  87611. },
  87612. enumerable: true,
  87613. configurable: true
  87614. });
  87615. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  87616. get: function () {
  87617. return this._renderTargetTexture.refreshRate;
  87618. },
  87619. set: function (value) {
  87620. this._renderTargetTexture.refreshRate = value;
  87621. },
  87622. enumerable: true,
  87623. configurable: true
  87624. });
  87625. ReflectionProbe.prototype.getScene = function () {
  87626. return this._scene;
  87627. };
  87628. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  87629. get: function () {
  87630. return this._renderTargetTexture;
  87631. },
  87632. enumerable: true,
  87633. configurable: true
  87634. });
  87635. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  87636. get: function () {
  87637. return this._renderTargetTexture.renderList;
  87638. },
  87639. enumerable: true,
  87640. configurable: true
  87641. });
  87642. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  87643. this._attachedMesh = mesh;
  87644. };
  87645. /**
  87646. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  87647. *
  87648. * @param renderingGroupId The rendering group id corresponding to its index
  87649. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  87650. */
  87651. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  87652. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  87653. };
  87654. ReflectionProbe.prototype.dispose = function () {
  87655. var index = this._scene.reflectionProbes.indexOf(this);
  87656. if (index !== -1) {
  87657. // Remove from the scene if found
  87658. this._scene.reflectionProbes.splice(index, 1);
  87659. }
  87660. if (this._renderTargetTexture) {
  87661. this._renderTargetTexture.dispose();
  87662. this._renderTargetTexture = null;
  87663. }
  87664. };
  87665. return ReflectionProbe;
  87666. }());
  87667. BABYLON.ReflectionProbe = ReflectionProbe;
  87668. })(BABYLON || (BABYLON = {}));
  87669. //# sourceMappingURL=babylon.reflectionProbe.js.map
  87670. var BABYLON;
  87671. (function (BABYLON) {
  87672. var Layer = /** @class */ (function () {
  87673. function Layer(name, imgUrl, scene, isBackground, color) {
  87674. this.name = name;
  87675. this.scale = new BABYLON.Vector2(1, 1);
  87676. this.offset = new BABYLON.Vector2(0, 0);
  87677. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  87678. this.layerMask = 0x0FFFFFFF;
  87679. this._vertexBuffers = {};
  87680. // Events
  87681. /**
  87682. * An event triggered when the layer is disposed.
  87683. * @type {BABYLON.Observable}
  87684. */
  87685. this.onDisposeObservable = new BABYLON.Observable();
  87686. /**
  87687. * An event triggered before rendering the scene
  87688. * @type {BABYLON.Observable}
  87689. */
  87690. this.onBeforeRenderObservable = new BABYLON.Observable();
  87691. /**
  87692. * An event triggered after rendering the scene
  87693. * @type {BABYLON.Observable}
  87694. */
  87695. this.onAfterRenderObservable = new BABYLON.Observable();
  87696. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  87697. this.isBackground = isBackground === undefined ? true : isBackground;
  87698. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  87699. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  87700. this._scene.layers.push(this);
  87701. var engine = this._scene.getEngine();
  87702. // VBO
  87703. var vertices = [];
  87704. vertices.push(1, 1);
  87705. vertices.push(-1, 1);
  87706. vertices.push(-1, -1);
  87707. vertices.push(1, -1);
  87708. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  87709. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  87710. this._createIndexBuffer();
  87711. // Effects
  87712. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  87713. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  87714. }
  87715. Object.defineProperty(Layer.prototype, "onDispose", {
  87716. set: function (callback) {
  87717. if (this._onDisposeObserver) {
  87718. this.onDisposeObservable.remove(this._onDisposeObserver);
  87719. }
  87720. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  87721. },
  87722. enumerable: true,
  87723. configurable: true
  87724. });
  87725. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  87726. set: function (callback) {
  87727. if (this._onBeforeRenderObserver) {
  87728. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  87729. }
  87730. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  87731. },
  87732. enumerable: true,
  87733. configurable: true
  87734. });
  87735. Object.defineProperty(Layer.prototype, "onAfterRender", {
  87736. set: function (callback) {
  87737. if (this._onAfterRenderObserver) {
  87738. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  87739. }
  87740. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  87741. },
  87742. enumerable: true,
  87743. configurable: true
  87744. });
  87745. Layer.prototype._createIndexBuffer = function () {
  87746. var engine = this._scene.getEngine();
  87747. // Indices
  87748. var indices = [];
  87749. indices.push(0);
  87750. indices.push(1);
  87751. indices.push(2);
  87752. indices.push(0);
  87753. indices.push(2);
  87754. indices.push(3);
  87755. this._indexBuffer = engine.createIndexBuffer(indices);
  87756. };
  87757. Layer.prototype._rebuild = function () {
  87758. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  87759. if (vb) {
  87760. vb._rebuild();
  87761. }
  87762. this._createIndexBuffer();
  87763. };
  87764. Layer.prototype.render = function () {
  87765. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  87766. // Check
  87767. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  87768. return;
  87769. var engine = this._scene.getEngine();
  87770. this.onBeforeRenderObservable.notifyObservers(this);
  87771. // Render
  87772. engine.enableEffect(currentEffect);
  87773. engine.setState(false);
  87774. // Texture
  87775. currentEffect.setTexture("textureSampler", this.texture);
  87776. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  87777. // Color
  87778. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  87779. // Scale / offset
  87780. currentEffect.setVector2("offset", this.offset);
  87781. currentEffect.setVector2("scale", this.scale);
  87782. // VBOs
  87783. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  87784. // Draw order
  87785. if (!this.alphaTest) {
  87786. engine.setAlphaMode(this.alphaBlendingMode);
  87787. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  87788. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  87789. }
  87790. else {
  87791. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  87792. }
  87793. this.onAfterRenderObservable.notifyObservers(this);
  87794. };
  87795. Layer.prototype.dispose = function () {
  87796. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  87797. if (vertexBuffer) {
  87798. vertexBuffer.dispose();
  87799. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  87800. }
  87801. if (this._indexBuffer) {
  87802. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  87803. this._indexBuffer = null;
  87804. }
  87805. if (this.texture) {
  87806. this.texture.dispose();
  87807. this.texture = null;
  87808. }
  87809. // Remove from scene
  87810. var index = this._scene.layers.indexOf(this);
  87811. this._scene.layers.splice(index, 1);
  87812. // Callback
  87813. this.onDisposeObservable.notifyObservers(this);
  87814. this.onDisposeObservable.clear();
  87815. this.onAfterRenderObservable.clear();
  87816. this.onBeforeRenderObservable.clear();
  87817. };
  87818. return Layer;
  87819. }());
  87820. BABYLON.Layer = Layer;
  87821. })(BABYLON || (BABYLON = {}));
  87822. //# sourceMappingURL=babylon.layer.js.map
  87823. var BABYLON;
  87824. (function (BABYLON) {
  87825. var TextureTools = /** @class */ (function () {
  87826. function TextureTools() {
  87827. }
  87828. /**
  87829. * Uses the GPU to create a copy texture rescaled at a given size
  87830. * @param texture Texture to copy from
  87831. * @param width Desired width
  87832. * @param height Desired height
  87833. * @return Generated texture
  87834. */
  87835. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  87836. if (useBilinearMode === void 0) { useBilinearMode = true; }
  87837. var scene = texture.getScene();
  87838. var engine = scene.getEngine();
  87839. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  87840. rtt.wrapU = texture.wrapU;
  87841. rtt.wrapV = texture.wrapV;
  87842. rtt.uOffset = texture.uOffset;
  87843. rtt.vOffset = texture.vOffset;
  87844. rtt.uScale = texture.uScale;
  87845. rtt.vScale = texture.vScale;
  87846. rtt.uAng = texture.uAng;
  87847. rtt.vAng = texture.vAng;
  87848. rtt.wAng = texture.wAng;
  87849. rtt.coordinatesIndex = texture.coordinatesIndex;
  87850. rtt.level = texture.level;
  87851. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  87852. rtt._texture.isReady = false;
  87853. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  87854. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  87855. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  87856. passPostProcess.getEffect().executeWhenCompiled(function () {
  87857. passPostProcess.onApply = function (effect) {
  87858. effect.setTexture("textureSampler", texture);
  87859. };
  87860. var internalTexture = rtt.getInternalTexture();
  87861. if (internalTexture) {
  87862. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  87863. engine.unBindFramebuffer(internalTexture);
  87864. rtt.disposeFramebufferObjects();
  87865. passPostProcess.dispose();
  87866. internalTexture.isReady = true;
  87867. }
  87868. });
  87869. return rtt;
  87870. };
  87871. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  87872. if (!scene._environmentBRDFTexture) {
  87873. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  87874. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  87875. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  87876. scene._environmentBRDFTexture = texture;
  87877. }
  87878. return scene._environmentBRDFTexture;
  87879. };
  87880. 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=";
  87881. return TextureTools;
  87882. }());
  87883. BABYLON.TextureTools = TextureTools;
  87884. })(BABYLON || (BABYLON = {}));
  87885. //# sourceMappingURL=babylon.textureTools.js.map
  87886. var BABYLON;
  87887. (function (BABYLON) {
  87888. var FramingBehavior = /** @class */ (function () {
  87889. function FramingBehavior() {
  87890. this._mode = FramingBehavior.FitFrustumSidesMode;
  87891. this._radiusScale = 1.0;
  87892. this._positionScale = 0.5;
  87893. this._defaultElevation = 0.3;
  87894. this._elevationReturnTime = 1500;
  87895. this._elevationReturnWaitTime = 1000;
  87896. this._zoomStopsAnimation = false;
  87897. this._framingTime = 1500;
  87898. this._isPointerDown = false;
  87899. this._lastInteractionTime = -Infinity;
  87900. // Framing control
  87901. this._animatables = new Array();
  87902. this._betaIsAnimating = false;
  87903. }
  87904. Object.defineProperty(FramingBehavior.prototype, "name", {
  87905. get: function () {
  87906. return "Framing";
  87907. },
  87908. enumerable: true,
  87909. configurable: true
  87910. });
  87911. Object.defineProperty(FramingBehavior.prototype, "mode", {
  87912. /**
  87913. * Gets current mode used by the behavior.
  87914. */
  87915. get: function () {
  87916. return this._mode;
  87917. },
  87918. /**
  87919. * Sets the current mode used by the behavior
  87920. */
  87921. set: function (mode) {
  87922. this._mode = mode;
  87923. },
  87924. enumerable: true,
  87925. configurable: true
  87926. });
  87927. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  87928. /**
  87929. * Gets the scale applied to the radius
  87930. */
  87931. get: function () {
  87932. return this._radiusScale;
  87933. },
  87934. /**
  87935. * Sets the scale applied to the radius (1 by default)
  87936. */
  87937. set: function (radius) {
  87938. this._radiusScale = radius;
  87939. },
  87940. enumerable: true,
  87941. configurable: true
  87942. });
  87943. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  87944. /**
  87945. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  87946. */
  87947. get: function () {
  87948. return this._positionScale;
  87949. },
  87950. /**
  87951. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  87952. */
  87953. set: function (scale) {
  87954. this._positionScale = scale;
  87955. },
  87956. enumerable: true,
  87957. configurable: true
  87958. });
  87959. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  87960. /**
  87961. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  87962. * behaviour is triggered, in radians.
  87963. */
  87964. get: function () {
  87965. return this._defaultElevation;
  87966. },
  87967. /**
  87968. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  87969. * behaviour is triggered, in radians.
  87970. */
  87971. set: function (elevation) {
  87972. this._defaultElevation = elevation;
  87973. },
  87974. enumerable: true,
  87975. configurable: true
  87976. });
  87977. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  87978. /**
  87979. * Gets the time (in milliseconds) taken to return to the default beta position.
  87980. * Negative value indicates camera should not return to default.
  87981. */
  87982. get: function () {
  87983. return this._elevationReturnTime;
  87984. },
  87985. /**
  87986. * Sets the time (in milliseconds) taken to return to the default beta position.
  87987. * Negative value indicates camera should not return to default.
  87988. */
  87989. set: function (speed) {
  87990. this._elevationReturnTime = speed;
  87991. },
  87992. enumerable: true,
  87993. configurable: true
  87994. });
  87995. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  87996. /**
  87997. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  87998. */
  87999. get: function () {
  88000. return this._elevationReturnWaitTime;
  88001. },
  88002. /**
  88003. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  88004. */
  88005. set: function (time) {
  88006. this._elevationReturnWaitTime = time;
  88007. },
  88008. enumerable: true,
  88009. configurable: true
  88010. });
  88011. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  88012. /**
  88013. * Gets the flag that indicates if user zooming should stop animation.
  88014. */
  88015. get: function () {
  88016. return this._zoomStopsAnimation;
  88017. },
  88018. /**
  88019. * Sets the flag that indicates if user zooming should stop animation.
  88020. */
  88021. set: function (flag) {
  88022. this._zoomStopsAnimation = flag;
  88023. },
  88024. enumerable: true,
  88025. configurable: true
  88026. });
  88027. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  88028. /**
  88029. * Gets the transition time when framing the mesh, in milliseconds
  88030. */
  88031. get: function () {
  88032. return this._framingTime;
  88033. },
  88034. /**
  88035. * Sets the transition time when framing the mesh, in milliseconds
  88036. */
  88037. set: function (time) {
  88038. this._framingTime = time;
  88039. },
  88040. enumerable: true,
  88041. configurable: true
  88042. });
  88043. FramingBehavior.prototype.init = function () {
  88044. // Do notihng
  88045. };
  88046. FramingBehavior.prototype.attach = function (camera) {
  88047. var _this = this;
  88048. this._attachedCamera = camera;
  88049. var scene = this._attachedCamera.getScene();
  88050. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  88051. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  88052. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  88053. _this._isPointerDown = true;
  88054. return;
  88055. }
  88056. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  88057. _this._isPointerDown = false;
  88058. }
  88059. });
  88060. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  88061. if (mesh) {
  88062. _this.zoomOnMesh(mesh);
  88063. }
  88064. });
  88065. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  88066. // Stop the animation if there is user interaction and the animation should stop for this interaction
  88067. _this._applyUserInteraction();
  88068. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  88069. // back to the default position after a given timeout
  88070. _this._maintainCameraAboveGround();
  88071. });
  88072. };
  88073. FramingBehavior.prototype.detach = function () {
  88074. if (!this._attachedCamera) {
  88075. return;
  88076. }
  88077. var scene = this._attachedCamera.getScene();
  88078. if (this._onPrePointerObservableObserver) {
  88079. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  88080. }
  88081. if (this._onAfterCheckInputsObserver) {
  88082. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  88083. }
  88084. if (this._onMeshTargetChangedObserver) {
  88085. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  88086. }
  88087. this._attachedCamera = null;
  88088. };
  88089. /**
  88090. * Targets the given mesh and updates zoom level accordingly.
  88091. * @param mesh The mesh to target.
  88092. * @param radius Optional. If a cached radius position already exists, overrides default.
  88093. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  88094. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  88095. * @param onAnimationEnd Callback triggered at the end of the framing animation
  88096. */
  88097. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  88098. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  88099. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  88100. mesh.computeWorldMatrix(true);
  88101. var boundingBox = mesh.getBoundingInfo().boundingBox;
  88102. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  88103. };
  88104. /**
  88105. * Targets the given mesh with its children and updates zoom level accordingly.
  88106. * @param mesh The mesh to target.
  88107. * @param radius Optional. If a cached radius position already exists, overrides default.
  88108. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  88109. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  88110. * @param onAnimationEnd Callback triggered at the end of the framing animation
  88111. */
  88112. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  88113. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  88114. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  88115. mesh.computeWorldMatrix(true);
  88116. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  88117. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  88118. };
  88119. /**
  88120. * Targets the given meshes with their children and updates zoom level accordingly.
  88121. * @param meshes The mesh to target.
  88122. * @param radius Optional. If a cached radius position already exists, overrides default.
  88123. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  88124. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  88125. * @param onAnimationEnd Callback triggered at the end of the framing animation
  88126. */
  88127. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  88128. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  88129. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  88130. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  88131. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  88132. for (var i = 0; i < meshes.length; i++) {
  88133. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  88134. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  88135. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  88136. }
  88137. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  88138. };
  88139. /**
  88140. * Targets the given mesh and updates zoom level accordingly.
  88141. * @param mesh The mesh to target.
  88142. * @param radius Optional. If a cached radius position already exists, overrides default.
  88143. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  88144. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  88145. * @param onAnimationEnd Callback triggered at the end of the framing animation
  88146. */
  88147. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  88148. var _this = this;
  88149. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  88150. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  88151. var zoomTarget;
  88152. if (!this._attachedCamera) {
  88153. return;
  88154. }
  88155. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  88156. var bottom = minimumWorld.y;
  88157. var top = maximumWorld.y;
  88158. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  88159. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  88160. if (focusOnOriginXZ) {
  88161. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  88162. }
  88163. else {
  88164. var centerWorld = minimumWorld.add(radiusWorld);
  88165. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  88166. }
  88167. if (!this._vectorTransition) {
  88168. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  88169. }
  88170. this._betaIsAnimating = true;
  88171. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  88172. if (animatable) {
  88173. this._animatables.push(animatable);
  88174. }
  88175. // sets the radius and lower radius bounds
  88176. // Small delta ensures camera is not always at lower zoom limit.
  88177. var radius = 0;
  88178. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  88179. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  88180. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  88181. radius = position;
  88182. }
  88183. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  88184. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  88185. if (this._attachedCamera.lowerRadiusLimit === null) {
  88186. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  88187. }
  88188. }
  88189. // Set sensibilities
  88190. var extend = maximumWorld.subtract(minimumWorld).length();
  88191. this._attachedCamera.panningSensibility = 5000 / extend;
  88192. this._attachedCamera.wheelPrecision = 100 / radius;
  88193. // transition to new radius
  88194. if (!this._radiusTransition) {
  88195. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  88196. }
  88197. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  88198. _this.stopAllAnimations();
  88199. if (onAnimationEnd) {
  88200. onAnimationEnd();
  88201. }
  88202. if (_this._attachedCamera) {
  88203. _this._attachedCamera.storeState();
  88204. }
  88205. });
  88206. if (animatable) {
  88207. this._animatables.push(animatable);
  88208. }
  88209. };
  88210. /**
  88211. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  88212. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  88213. * frustum width.
  88214. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  88215. * to fully enclose the mesh in the viewing frustum.
  88216. */
  88217. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  88218. var size = maximumWorld.subtract(minimumWorld);
  88219. var boxVectorGlobalDiagonal = size.length();
  88220. var frustumSlope = this._getFrustumSlope();
  88221. // Formula for setting distance
  88222. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  88223. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  88224. // Horizon distance
  88225. var radius = radiusWithoutFraming * this._radiusScale;
  88226. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  88227. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  88228. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  88229. var camera = this._attachedCamera;
  88230. if (!camera) {
  88231. return 0;
  88232. }
  88233. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  88234. // Don't exceed the requested limit
  88235. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  88236. }
  88237. // Don't exceed the upper radius limit
  88238. if (camera.upperRadiusLimit) {
  88239. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  88240. }
  88241. return distance;
  88242. };
  88243. /**
  88244. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  88245. * is automatically returned to its default position (expected to be above ground plane).
  88246. */
  88247. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  88248. var _this = this;
  88249. if (this._elevationReturnTime < 0) {
  88250. return;
  88251. }
  88252. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  88253. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  88254. var limitBeta = Math.PI * 0.5;
  88255. // Bring the camera back up if below the ground plane
  88256. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  88257. this._betaIsAnimating = true;
  88258. //Transition to new position
  88259. this.stopAllAnimations();
  88260. if (!this._betaTransition) {
  88261. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  88262. }
  88263. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  88264. _this._clearAnimationLocks();
  88265. _this.stopAllAnimations();
  88266. });
  88267. if (animatabe) {
  88268. this._animatables.push(animatabe);
  88269. }
  88270. }
  88271. };
  88272. /**
  88273. * Returns the frustum slope based on the canvas ratio and camera FOV
  88274. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  88275. */
  88276. FramingBehavior.prototype._getFrustumSlope = function () {
  88277. // Calculate the viewport ratio
  88278. // Aspect Ratio is Height/Width.
  88279. var camera = this._attachedCamera;
  88280. if (!camera) {
  88281. return BABYLON.Vector2.Zero();
  88282. }
  88283. var engine = camera.getScene().getEngine();
  88284. var aspectRatio = engine.getAspectRatio(camera);
  88285. // Camera FOV is the vertical field of view (top-bottom) in radians.
  88286. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  88287. var frustumSlopeY = Math.tan(camera.fov / 2);
  88288. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  88289. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  88290. // along the forward vector.
  88291. var frustumSlopeX = frustumSlopeY * aspectRatio;
  88292. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  88293. };
  88294. /**
  88295. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  88296. */
  88297. FramingBehavior.prototype._clearAnimationLocks = function () {
  88298. this._betaIsAnimating = false;
  88299. };
  88300. /**
  88301. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  88302. */
  88303. FramingBehavior.prototype._applyUserInteraction = function () {
  88304. if (this.isUserIsMoving) {
  88305. this._lastInteractionTime = BABYLON.Tools.Now;
  88306. this.stopAllAnimations();
  88307. this._clearAnimationLocks();
  88308. }
  88309. };
  88310. /**
  88311. * Stops and removes all animations that have been applied to the camera
  88312. */
  88313. FramingBehavior.prototype.stopAllAnimations = function () {
  88314. if (this._attachedCamera) {
  88315. this._attachedCamera.animations = [];
  88316. }
  88317. while (this._animatables.length) {
  88318. if (this._animatables[0]) {
  88319. this._animatables[0].onAnimationEnd = null;
  88320. this._animatables[0].stop();
  88321. }
  88322. this._animatables.shift();
  88323. }
  88324. };
  88325. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  88326. /**
  88327. * Gets a value indicating if the user is moving the camera
  88328. */
  88329. get: function () {
  88330. if (!this._attachedCamera) {
  88331. return false;
  88332. }
  88333. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  88334. this._attachedCamera.inertialBetaOffset !== 0 ||
  88335. this._attachedCamera.inertialRadiusOffset !== 0 ||
  88336. this._attachedCamera.inertialPanningX !== 0 ||
  88337. this._attachedCamera.inertialPanningY !== 0 ||
  88338. this._isPointerDown;
  88339. },
  88340. enumerable: true,
  88341. configurable: true
  88342. });
  88343. /**
  88344. * The easing function used by animations
  88345. */
  88346. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  88347. /**
  88348. * The easing mode used by animations
  88349. */
  88350. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  88351. // Statics
  88352. /**
  88353. * The camera can move all the way towards the mesh.
  88354. */
  88355. FramingBehavior.IgnoreBoundsSizeMode = 0;
  88356. /**
  88357. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  88358. */
  88359. FramingBehavior.FitFrustumSidesMode = 1;
  88360. return FramingBehavior;
  88361. }());
  88362. BABYLON.FramingBehavior = FramingBehavior;
  88363. })(BABYLON || (BABYLON = {}));
  88364. //# sourceMappingURL=babylon.framingBehavior.js.map
  88365. var BABYLON;
  88366. (function (BABYLON) {
  88367. /**
  88368. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  88369. */
  88370. var BouncingBehavior = /** @class */ (function () {
  88371. function BouncingBehavior() {
  88372. /**
  88373. * The duration of the animation, in milliseconds
  88374. */
  88375. this.transitionDuration = 450;
  88376. /**
  88377. * Length of the distance animated by the transition when lower radius is reached
  88378. */
  88379. this.lowerRadiusTransitionRange = 2;
  88380. /**
  88381. * Length of the distance animated by the transition when upper radius is reached
  88382. */
  88383. this.upperRadiusTransitionRange = -2;
  88384. this._autoTransitionRange = false;
  88385. // Animations
  88386. this._radiusIsAnimating = false;
  88387. this._radiusBounceTransition = null;
  88388. this._animatables = new Array();
  88389. }
  88390. Object.defineProperty(BouncingBehavior.prototype, "name", {
  88391. get: function () {
  88392. return "Bouncing";
  88393. },
  88394. enumerable: true,
  88395. configurable: true
  88396. });
  88397. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  88398. /**
  88399. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  88400. */
  88401. get: function () {
  88402. return this._autoTransitionRange;
  88403. },
  88404. /**
  88405. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  88406. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  88407. */
  88408. set: function (value) {
  88409. var _this = this;
  88410. if (this._autoTransitionRange === value) {
  88411. return;
  88412. }
  88413. this._autoTransitionRange = value;
  88414. var camera = this._attachedCamera;
  88415. if (!camera) {
  88416. return;
  88417. }
  88418. if (value) {
  88419. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  88420. if (!mesh) {
  88421. return;
  88422. }
  88423. mesh.computeWorldMatrix(true);
  88424. var diagonal = mesh.getBoundingInfo().diagonalLength;
  88425. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  88426. _this.upperRadiusTransitionRange = diagonal * 0.05;
  88427. });
  88428. }
  88429. else if (this._onMeshTargetChangedObserver) {
  88430. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  88431. }
  88432. },
  88433. enumerable: true,
  88434. configurable: true
  88435. });
  88436. BouncingBehavior.prototype.init = function () {
  88437. // Do notihng
  88438. };
  88439. BouncingBehavior.prototype.attach = function (camera) {
  88440. var _this = this;
  88441. this._attachedCamera = camera;
  88442. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  88443. if (!_this._attachedCamera) {
  88444. return;
  88445. }
  88446. // Add the bounce animation to the lower radius limit
  88447. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  88448. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  88449. }
  88450. // Add the bounce animation to the upper radius limit
  88451. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  88452. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  88453. }
  88454. });
  88455. };
  88456. BouncingBehavior.prototype.detach = function () {
  88457. if (!this._attachedCamera) {
  88458. return;
  88459. }
  88460. if (this._onAfterCheckInputsObserver) {
  88461. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  88462. }
  88463. if (this._onMeshTargetChangedObserver) {
  88464. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  88465. }
  88466. this._attachedCamera = null;
  88467. };
  88468. /**
  88469. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  88470. * @param radiusLimit The limit to check against.
  88471. * @return Bool to indicate if at limit.
  88472. */
  88473. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  88474. if (!this._attachedCamera) {
  88475. return false;
  88476. }
  88477. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  88478. return true;
  88479. }
  88480. return false;
  88481. };
  88482. /**
  88483. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  88484. * @param radiusDelta The delta by which to animate to. Can be negative.
  88485. */
  88486. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  88487. var _this = this;
  88488. if (!this._attachedCamera) {
  88489. return;
  88490. }
  88491. if (!this._radiusBounceTransition) {
  88492. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  88493. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  88494. }
  88495. // Prevent zoom until bounce has completed
  88496. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  88497. this._attachedCamera.wheelPrecision = Infinity;
  88498. this._attachedCamera.inertialRadiusOffset = 0;
  88499. // Animate to the radius limit
  88500. this.stopAllAnimations();
  88501. this._radiusIsAnimating = true;
  88502. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  88503. if (animatable) {
  88504. this._animatables.push(animatable);
  88505. }
  88506. };
  88507. /**
  88508. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  88509. */
  88510. BouncingBehavior.prototype._clearAnimationLocks = function () {
  88511. this._radiusIsAnimating = false;
  88512. if (this._attachedCamera) {
  88513. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  88514. }
  88515. };
  88516. /**
  88517. * Stops and removes all animations that have been applied to the camera
  88518. */
  88519. BouncingBehavior.prototype.stopAllAnimations = function () {
  88520. if (this._attachedCamera) {
  88521. this._attachedCamera.animations = [];
  88522. }
  88523. while (this._animatables.length) {
  88524. this._animatables[0].onAnimationEnd = null;
  88525. this._animatables[0].stop();
  88526. this._animatables.shift();
  88527. }
  88528. };
  88529. /**
  88530. * The easing function used by animations
  88531. */
  88532. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  88533. /**
  88534. * The easing mode used by animations
  88535. */
  88536. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  88537. return BouncingBehavior;
  88538. }());
  88539. BABYLON.BouncingBehavior = BouncingBehavior;
  88540. })(BABYLON || (BABYLON = {}));
  88541. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  88542. var BABYLON;
  88543. (function (BABYLON) {
  88544. var AutoRotationBehavior = /** @class */ (function () {
  88545. function AutoRotationBehavior() {
  88546. this._zoomStopsAnimation = false;
  88547. this._idleRotationSpeed = 0.05;
  88548. this._idleRotationWaitTime = 2000;
  88549. this._idleRotationSpinupTime = 2000;
  88550. this._isPointerDown = false;
  88551. this._lastFrameTime = null;
  88552. this._lastInteractionTime = -Infinity;
  88553. this._cameraRotationSpeed = 0;
  88554. this._lastFrameRadius = 0;
  88555. }
  88556. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  88557. get: function () {
  88558. return "AutoRotation";
  88559. },
  88560. enumerable: true,
  88561. configurable: true
  88562. });
  88563. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  88564. /**
  88565. * Gets the flag that indicates if user zooming should stop animation.
  88566. */
  88567. get: function () {
  88568. return this._zoomStopsAnimation;
  88569. },
  88570. /**
  88571. * Sets the flag that indicates if user zooming should stop animation.
  88572. */
  88573. set: function (flag) {
  88574. this._zoomStopsAnimation = flag;
  88575. },
  88576. enumerable: true,
  88577. configurable: true
  88578. });
  88579. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  88580. /**
  88581. * Gets the default speed at which the camera rotates around the model.
  88582. */
  88583. get: function () {
  88584. return this._idleRotationSpeed;
  88585. },
  88586. /**
  88587. * Sets the default speed at which the camera rotates around the model.
  88588. */
  88589. set: function (speed) {
  88590. this._idleRotationSpeed = speed;
  88591. },
  88592. enumerable: true,
  88593. configurable: true
  88594. });
  88595. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  88596. /**
  88597. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  88598. */
  88599. get: function () {
  88600. return this._idleRotationWaitTime;
  88601. },
  88602. /**
  88603. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  88604. */
  88605. set: function (time) {
  88606. this._idleRotationWaitTime = time;
  88607. },
  88608. enumerable: true,
  88609. configurable: true
  88610. });
  88611. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  88612. /**
  88613. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  88614. */
  88615. get: function () {
  88616. return this._idleRotationSpinupTime;
  88617. },
  88618. /**
  88619. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  88620. */
  88621. set: function (time) {
  88622. this._idleRotationSpinupTime = time;
  88623. },
  88624. enumerable: true,
  88625. configurable: true
  88626. });
  88627. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  88628. /**
  88629. * Gets a value indicating if the camera is currently rotating because of this behavior
  88630. */
  88631. get: function () {
  88632. return Math.abs(this._cameraRotationSpeed) > 0;
  88633. },
  88634. enumerable: true,
  88635. configurable: true
  88636. });
  88637. AutoRotationBehavior.prototype.init = function () {
  88638. // Do notihng
  88639. };
  88640. AutoRotationBehavior.prototype.attach = function (camera) {
  88641. var _this = this;
  88642. this._attachedCamera = camera;
  88643. var scene = this._attachedCamera.getScene();
  88644. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  88645. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  88646. _this._isPointerDown = true;
  88647. return;
  88648. }
  88649. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  88650. _this._isPointerDown = false;
  88651. }
  88652. });
  88653. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  88654. var now = BABYLON.Tools.Now;
  88655. var dt = 0;
  88656. if (_this._lastFrameTime != null) {
  88657. dt = now - _this._lastFrameTime;
  88658. }
  88659. _this._lastFrameTime = now;
  88660. // Stop the animation if there is user interaction and the animation should stop for this interaction
  88661. _this._applyUserInteraction();
  88662. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  88663. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  88664. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  88665. // Step camera rotation by rotation speed
  88666. if (_this._attachedCamera) {
  88667. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  88668. }
  88669. });
  88670. };
  88671. AutoRotationBehavior.prototype.detach = function () {
  88672. if (!this._attachedCamera) {
  88673. return;
  88674. }
  88675. var scene = this._attachedCamera.getScene();
  88676. if (this._onPrePointerObservableObserver) {
  88677. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  88678. }
  88679. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  88680. this._attachedCamera = null;
  88681. };
  88682. /**
  88683. * Returns true if user is scrolling.
  88684. * @return true if user is scrolling.
  88685. */
  88686. AutoRotationBehavior.prototype._userIsZooming = function () {
  88687. if (!this._attachedCamera) {
  88688. return false;
  88689. }
  88690. return this._attachedCamera.inertialRadiusOffset !== 0;
  88691. };
  88692. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  88693. if (!this._attachedCamera) {
  88694. return false;
  88695. }
  88696. var zoomHasHitLimit = false;
  88697. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  88698. zoomHasHitLimit = true;
  88699. }
  88700. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  88701. this._lastFrameRadius = this._attachedCamera.radius;
  88702. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  88703. };
  88704. /**
  88705. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  88706. */
  88707. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  88708. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  88709. this._lastInteractionTime = BABYLON.Tools.Now;
  88710. }
  88711. };
  88712. // Tools
  88713. AutoRotationBehavior.prototype._userIsMoving = function () {
  88714. if (!this._attachedCamera) {
  88715. return false;
  88716. }
  88717. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  88718. this._attachedCamera.inertialBetaOffset !== 0 ||
  88719. this._attachedCamera.inertialRadiusOffset !== 0 ||
  88720. this._attachedCamera.inertialPanningX !== 0 ||
  88721. this._attachedCamera.inertialPanningY !== 0 ||
  88722. this._isPointerDown;
  88723. };
  88724. return AutoRotationBehavior;
  88725. }());
  88726. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  88727. })(BABYLON || (BABYLON = {}));
  88728. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  88729. var BABYLON;
  88730. (function (BABYLON) {
  88731. var NullEngineOptions = /** @class */ (function () {
  88732. function NullEngineOptions() {
  88733. this.renderWidth = 512;
  88734. this.renderHeight = 256;
  88735. this.textureSize = 512;
  88736. this.deterministicLockstep = false;
  88737. this.lockstepMaxSteps = 4;
  88738. }
  88739. return NullEngineOptions;
  88740. }());
  88741. BABYLON.NullEngineOptions = NullEngineOptions;
  88742. /**
  88743. * The null engine class provides support for headless version of babylon.js.
  88744. * This can be used in server side scenario or for testing purposes
  88745. */
  88746. var NullEngine = /** @class */ (function (_super) {
  88747. __extends(NullEngine, _super);
  88748. function NullEngine(options) {
  88749. if (options === void 0) { options = new NullEngineOptions(); }
  88750. var _this = _super.call(this, null) || this;
  88751. if (options.deterministicLockstep === undefined) {
  88752. options.deterministicLockstep = false;
  88753. }
  88754. if (options.lockstepMaxSteps === undefined) {
  88755. options.lockstepMaxSteps = 4;
  88756. }
  88757. _this._options = options;
  88758. // Init caps
  88759. // We consider we are on a webgl1 capable device
  88760. _this._caps = new BABYLON.EngineCapabilities();
  88761. _this._caps.maxTexturesImageUnits = 16;
  88762. _this._caps.maxVertexTextureImageUnits = 16;
  88763. _this._caps.maxTextureSize = 512;
  88764. _this._caps.maxCubemapTextureSize = 512;
  88765. _this._caps.maxRenderTextureSize = 512;
  88766. _this._caps.maxVertexAttribs = 16;
  88767. _this._caps.maxVaryingVectors = 16;
  88768. _this._caps.maxFragmentUniformVectors = 16;
  88769. _this._caps.maxVertexUniformVectors = 16;
  88770. // Extensions
  88771. _this._caps.standardDerivatives = false;
  88772. _this._caps.astc = null;
  88773. _this._caps.s3tc = null;
  88774. _this._caps.pvrtc = null;
  88775. _this._caps.etc1 = null;
  88776. _this._caps.etc2 = null;
  88777. _this._caps.textureAnisotropicFilterExtension = null;
  88778. _this._caps.maxAnisotropy = 0;
  88779. _this._caps.uintIndices = false;
  88780. _this._caps.fragmentDepthSupported = false;
  88781. _this._caps.highPrecisionShaderSupported = true;
  88782. _this._caps.colorBufferFloat = false;
  88783. _this._caps.textureFloat = false;
  88784. _this._caps.textureFloatLinearFiltering = false;
  88785. _this._caps.textureFloatRender = false;
  88786. _this._caps.textureHalfFloat = false;
  88787. _this._caps.textureHalfFloatLinearFiltering = false;
  88788. _this._caps.textureHalfFloatRender = false;
  88789. _this._caps.textureLOD = false;
  88790. _this._caps.drawBuffersExtension = false;
  88791. _this._caps.depthTextureExtension = false;
  88792. _this._caps.vertexArrayObject = false;
  88793. _this._caps.instancedArrays = false;
  88794. BABYLON.Tools.Log("Babylon.js null engine (v" + BABYLON.Engine.Version + ") launched");
  88795. // Wrappers
  88796. if (typeof URL === "undefined") {
  88797. URL = {
  88798. createObjectURL: function () { },
  88799. revokeObjectURL: function () { }
  88800. };
  88801. }
  88802. if (typeof Blob === "undefined") {
  88803. Blob = function () { };
  88804. }
  88805. return _this;
  88806. }
  88807. NullEngine.prototype.isDeterministicLockStep = function () {
  88808. return this._options.deterministicLockstep;
  88809. };
  88810. NullEngine.prototype.getLockstepMaxSteps = function () {
  88811. return this._options.lockstepMaxSteps;
  88812. };
  88813. NullEngine.prototype.getHardwareScalingLevel = function () {
  88814. return 1.0;
  88815. };
  88816. NullEngine.prototype.createVertexBuffer = function (vertices) {
  88817. return {
  88818. capacity: 0,
  88819. references: 1,
  88820. is32Bits: false
  88821. };
  88822. };
  88823. NullEngine.prototype.createIndexBuffer = function (indices) {
  88824. return {
  88825. capacity: 0,
  88826. references: 1,
  88827. is32Bits: false
  88828. };
  88829. };
  88830. NullEngine.prototype.clear = function (color, backBuffer, depth, stencil) {
  88831. if (stencil === void 0) { stencil = false; }
  88832. };
  88833. NullEngine.prototype.getRenderWidth = function (useScreen) {
  88834. if (useScreen === void 0) { useScreen = false; }
  88835. if (!useScreen && this._currentRenderTarget) {
  88836. return this._currentRenderTarget.width;
  88837. }
  88838. return this._options.renderWidth;
  88839. };
  88840. NullEngine.prototype.getRenderHeight = function (useScreen) {
  88841. if (useScreen === void 0) { useScreen = false; }
  88842. if (!useScreen && this._currentRenderTarget) {
  88843. return this._currentRenderTarget.height;
  88844. }
  88845. return this._options.renderHeight;
  88846. };
  88847. NullEngine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  88848. this._cachedViewport = viewport;
  88849. };
  88850. NullEngine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  88851. return {
  88852. transformFeedback: null,
  88853. __SPECTOR_rebuildProgram: null
  88854. };
  88855. };
  88856. NullEngine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  88857. return [];
  88858. };
  88859. NullEngine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  88860. return [];
  88861. };
  88862. NullEngine.prototype.bindSamplers = function (effect) {
  88863. this._currentEffect = null;
  88864. };
  88865. NullEngine.prototype.enableEffect = function (effect) {
  88866. this._currentEffect = effect;
  88867. if (effect.onBind) {
  88868. effect.onBind(effect);
  88869. }
  88870. effect.onBindObservable.notifyObservers(effect);
  88871. };
  88872. NullEngine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  88873. if (zOffset === void 0) { zOffset = 0; }
  88874. if (reverseSide === void 0) { reverseSide = false; }
  88875. };
  88876. NullEngine.prototype.setIntArray = function (uniform, array) {
  88877. };
  88878. NullEngine.prototype.setIntArray2 = function (uniform, array) {
  88879. };
  88880. NullEngine.prototype.setIntArray3 = function (uniform, array) {
  88881. };
  88882. NullEngine.prototype.setIntArray4 = function (uniform, array) {
  88883. };
  88884. NullEngine.prototype.setFloatArray = function (uniform, array) {
  88885. };
  88886. NullEngine.prototype.setFloatArray2 = function (uniform, array) {
  88887. };
  88888. NullEngine.prototype.setFloatArray3 = function (uniform, array) {
  88889. };
  88890. NullEngine.prototype.setFloatArray4 = function (uniform, array) {
  88891. };
  88892. NullEngine.prototype.setArray = function (uniform, array) {
  88893. };
  88894. NullEngine.prototype.setArray2 = function (uniform, array) {
  88895. };
  88896. NullEngine.prototype.setArray3 = function (uniform, array) {
  88897. };
  88898. NullEngine.prototype.setArray4 = function (uniform, array) {
  88899. };
  88900. NullEngine.prototype.setMatrices = function (uniform, matrices) {
  88901. };
  88902. NullEngine.prototype.setMatrix = function (uniform, matrix) {
  88903. };
  88904. NullEngine.prototype.setMatrix3x3 = function (uniform, matrix) {
  88905. };
  88906. NullEngine.prototype.setMatrix2x2 = function (uniform, matrix) {
  88907. };
  88908. NullEngine.prototype.setFloat = function (uniform, value) {
  88909. };
  88910. NullEngine.prototype.setFloat2 = function (uniform, x, y) {
  88911. };
  88912. NullEngine.prototype.setFloat3 = function (uniform, x, y, z) {
  88913. };
  88914. NullEngine.prototype.setBool = function (uniform, bool) {
  88915. };
  88916. NullEngine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  88917. };
  88918. NullEngine.prototype.setColor3 = function (uniform, color3) {
  88919. };
  88920. NullEngine.prototype.setColor4 = function (uniform, color3, alpha) {
  88921. };
  88922. NullEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  88923. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  88924. if (this._alphaMode === mode) {
  88925. return;
  88926. }
  88927. this._alphaState.alphaBlend = (mode !== BABYLON.Engine.ALPHA_DISABLE);
  88928. if (!noDepthWriteChange) {
  88929. this.setDepthWrite(mode === BABYLON.Engine.ALPHA_DISABLE);
  88930. }
  88931. this._alphaMode = mode;
  88932. };
  88933. NullEngine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  88934. };
  88935. NullEngine.prototype.wipeCaches = function (bruteForce) {
  88936. if (this.preventCacheWipeBetweenFrames) {
  88937. return;
  88938. }
  88939. this.resetTextureCache();
  88940. this._currentEffect = null;
  88941. if (bruteForce) {
  88942. this._currentProgram = null;
  88943. this._stencilState.reset();
  88944. this._depthCullingState.reset();
  88945. this._alphaState.reset();
  88946. }
  88947. this._cachedVertexBuffers = null;
  88948. this._cachedIndexBuffer = null;
  88949. this._cachedEffectForVertexBuffers = null;
  88950. };
  88951. NullEngine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  88952. };
  88953. NullEngine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  88954. };
  88955. NullEngine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  88956. };
  88957. NullEngine.prototype._createTexture = function () {
  88958. return {};
  88959. };
  88960. NullEngine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  88961. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  88962. if (onLoad === void 0) { onLoad = null; }
  88963. if (onError === void 0) { onError = null; }
  88964. if (buffer === void 0) { buffer = null; }
  88965. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  88966. var url = String(urlArg);
  88967. texture.url = url;
  88968. texture.generateMipMaps = !noMipmap;
  88969. texture.samplingMode = samplingMode;
  88970. texture.invertY = invertY;
  88971. texture.baseWidth = this._options.textureSize;
  88972. texture.baseHeight = this._options.textureSize;
  88973. texture.width = this._options.textureSize;
  88974. texture.height = this._options.textureSize;
  88975. if (format) {
  88976. texture.format = format;
  88977. }
  88978. texture.isReady = true;
  88979. if (onLoad) {
  88980. onLoad();
  88981. }
  88982. return texture;
  88983. };
  88984. NullEngine.prototype.createRenderTargetTexture = function (size, options) {
  88985. var fullOptions = new BABYLON.RenderTargetCreationOptions();
  88986. if (options !== undefined && typeof options === "object") {
  88987. fullOptions.generateMipMaps = options.generateMipMaps;
  88988. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  88989. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  88990. fullOptions.type = options.type === undefined ? BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  88991. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  88992. }
  88993. else {
  88994. fullOptions.generateMipMaps = options;
  88995. fullOptions.generateDepthBuffer = true;
  88996. fullOptions.generateStencilBuffer = false;
  88997. fullOptions.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  88998. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  88999. }
  89000. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  89001. var width = size.width || size;
  89002. var height = size.height || size;
  89003. texture._depthStencilBuffer = {};
  89004. texture._framebuffer = {};
  89005. texture.baseWidth = width;
  89006. texture.baseHeight = height;
  89007. texture.width = width;
  89008. texture.height = height;
  89009. texture.isReady = true;
  89010. texture.samples = 1;
  89011. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  89012. texture.samplingMode = fullOptions.samplingMode;
  89013. texture.type = fullOptions.type;
  89014. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  89015. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  89016. return texture;
  89017. };
  89018. NullEngine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  89019. texture.samplingMode = samplingMode;
  89020. };
  89021. NullEngine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  89022. if (this._currentRenderTarget) {
  89023. this.unBindFramebuffer(this._currentRenderTarget);
  89024. }
  89025. this._currentRenderTarget = texture;
  89026. this._currentFramebuffer = texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer;
  89027. if (this._cachedViewport && !forceFullscreenViewport) {
  89028. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  89029. }
  89030. };
  89031. NullEngine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  89032. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  89033. this._currentRenderTarget = null;
  89034. if (onBeforeUnbind) {
  89035. if (texture._MSAAFramebuffer) {
  89036. this._currentFramebuffer = texture._framebuffer;
  89037. }
  89038. onBeforeUnbind();
  89039. }
  89040. this._currentFramebuffer = null;
  89041. };
  89042. NullEngine.prototype.createDynamicVertexBuffer = function (vertices) {
  89043. var vbo = {
  89044. capacity: 1,
  89045. references: 1,
  89046. is32Bits: false
  89047. };
  89048. return vbo;
  89049. };
  89050. NullEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  89051. if (offset === void 0) { offset = 0; }
  89052. };
  89053. NullEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  89054. };
  89055. NullEngine.prototype._bindTextureDirectly = function (target, texture) {
  89056. if (this._boundTexturesCache[this._activeChannel] !== texture) {
  89057. this._boundTexturesCache[this._activeChannel] = texture;
  89058. }
  89059. };
  89060. NullEngine.prototype._bindTexture = function (channel, texture) {
  89061. if (channel < 0) {
  89062. return;
  89063. }
  89064. this._bindTextureDirectly(0, texture);
  89065. };
  89066. NullEngine.prototype._releaseBuffer = function (buffer) {
  89067. buffer.references--;
  89068. if (buffer.references === 0) {
  89069. return true;
  89070. }
  89071. return false;
  89072. };
  89073. return NullEngine;
  89074. }(BABYLON.Engine));
  89075. BABYLON.NullEngine = NullEngine;
  89076. })(BABYLON || (BABYLON = {}));
  89077. //# sourceMappingURL=babylon.nullEngine.js.map
  89078. var BABYLON;
  89079. (function (BABYLON) {
  89080. /**
  89081. * This class can be used to get instrumentation data from a Babylon engine
  89082. */
  89083. var EngineInstrumentation = /** @class */ (function () {
  89084. function EngineInstrumentation(engine) {
  89085. this.engine = engine;
  89086. this._captureGPUFrameTime = false;
  89087. this._gpuFrameTime = new BABYLON.PerfCounter();
  89088. this._captureShaderCompilationTime = false;
  89089. this._shaderCompilationTime = new BABYLON.PerfCounter();
  89090. // Observers
  89091. this._onBeginFrameObserver = null;
  89092. this._onEndFrameObserver = null;
  89093. this._onBeforeShaderCompilationObserver = null;
  89094. this._onAfterShaderCompilationObserver = null;
  89095. }
  89096. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  89097. // Properties
  89098. /**
  89099. * Gets the perf counter used for GPU frame time
  89100. */
  89101. get: function () {
  89102. return this._gpuFrameTime;
  89103. },
  89104. enumerable: true,
  89105. configurable: true
  89106. });
  89107. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  89108. /**
  89109. * Gets the GPU frame time capture status
  89110. */
  89111. get: function () {
  89112. return this._captureGPUFrameTime;
  89113. },
  89114. /**
  89115. * Enable or disable the GPU frame time capture
  89116. */
  89117. set: function (value) {
  89118. var _this = this;
  89119. if (value === this._captureGPUFrameTime) {
  89120. return;
  89121. }
  89122. this._captureGPUFrameTime = value;
  89123. if (value) {
  89124. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  89125. if (!_this._gpuFrameTimeToken) {
  89126. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  89127. }
  89128. });
  89129. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  89130. if (!_this._gpuFrameTimeToken) {
  89131. return;
  89132. }
  89133. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  89134. if (time > -1) {
  89135. _this._gpuFrameTimeToken = null;
  89136. _this._gpuFrameTime.fetchNewFrame();
  89137. _this._gpuFrameTime.addCount(time, true);
  89138. }
  89139. });
  89140. }
  89141. else {
  89142. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  89143. this._onBeginFrameObserver = null;
  89144. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  89145. this._onEndFrameObserver = null;
  89146. }
  89147. },
  89148. enumerable: true,
  89149. configurable: true
  89150. });
  89151. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  89152. /**
  89153. * Gets the perf counter used for shader compilation time
  89154. */
  89155. get: function () {
  89156. return this._shaderCompilationTime;
  89157. },
  89158. enumerable: true,
  89159. configurable: true
  89160. });
  89161. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  89162. /**
  89163. * Gets the shader compilation time capture status
  89164. */
  89165. get: function () {
  89166. return this._captureShaderCompilationTime;
  89167. },
  89168. /**
  89169. * Enable or disable the shader compilation time capture
  89170. */
  89171. set: function (value) {
  89172. var _this = this;
  89173. if (value === this._captureShaderCompilationTime) {
  89174. return;
  89175. }
  89176. this._captureShaderCompilationTime = value;
  89177. if (value) {
  89178. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  89179. _this._shaderCompilationTime.fetchNewFrame();
  89180. _this._shaderCompilationTime.beginMonitoring();
  89181. });
  89182. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  89183. _this._shaderCompilationTime.endMonitoring();
  89184. });
  89185. }
  89186. else {
  89187. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  89188. this._onBeforeShaderCompilationObserver = null;
  89189. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  89190. this._onAfterShaderCompilationObserver = null;
  89191. }
  89192. },
  89193. enumerable: true,
  89194. configurable: true
  89195. });
  89196. EngineInstrumentation.prototype.dispose = function () {
  89197. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  89198. this._onBeginFrameObserver = null;
  89199. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  89200. this._onEndFrameObserver = null;
  89201. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  89202. this._onBeforeShaderCompilationObserver = null;
  89203. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  89204. this._onAfterShaderCompilationObserver = null;
  89205. this.engine = null;
  89206. };
  89207. return EngineInstrumentation;
  89208. }());
  89209. BABYLON.EngineInstrumentation = EngineInstrumentation;
  89210. })(BABYLON || (BABYLON = {}));
  89211. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  89212. var BABYLON;
  89213. (function (BABYLON) {
  89214. /**
  89215. * This class can be used to get instrumentation data from a Babylon engine
  89216. */
  89217. var SceneInstrumentation = /** @class */ (function () {
  89218. function SceneInstrumentation(scene) {
  89219. var _this = this;
  89220. this.scene = scene;
  89221. this._captureActiveMeshesEvaluationTime = false;
  89222. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  89223. this._captureRenderTargetsRenderTime = false;
  89224. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  89225. this._captureFrameTime = false;
  89226. this._frameTime = new BABYLON.PerfCounter();
  89227. this._captureRenderTime = false;
  89228. this._renderTime = new BABYLON.PerfCounter();
  89229. this._captureInterFrameTime = false;
  89230. this._interFrameTime = new BABYLON.PerfCounter();
  89231. this._captureParticlesRenderTime = false;
  89232. this._particlesRenderTime = new BABYLON.PerfCounter();
  89233. this._captureSpritesRenderTime = false;
  89234. this._spritesRenderTime = new BABYLON.PerfCounter();
  89235. this._capturePhysicsTime = false;
  89236. this._physicsTime = new BABYLON.PerfCounter();
  89237. this._captureAnimationsTime = false;
  89238. this._animationsTime = new BABYLON.PerfCounter();
  89239. // Observers
  89240. this._onBeforeActiveMeshesEvaluationObserver = null;
  89241. this._onAfterActiveMeshesEvaluationObserver = null;
  89242. this._onBeforeRenderTargetsRenderObserver = null;
  89243. this._onAfterRenderTargetsRenderObserver = null;
  89244. this._onAfterRenderObserver = null;
  89245. this._onBeforeDrawPhaseObserver = null;
  89246. this._onAfterDrawPhaseObserver = null;
  89247. this._onBeforeAnimationsObserver = null;
  89248. this._onBeforeParticlesRenderingObserver = null;
  89249. this._onAfterParticlesRenderingObserver = null;
  89250. this._onBeforeSpritesRenderingObserver = null;
  89251. this._onAfterSpritesRenderingObserver = null;
  89252. this._onBeforePhysicsObserver = null;
  89253. this._onAfterPhysicsObserver = null;
  89254. this._onAfterAnimationsObserver = null;
  89255. // Before render
  89256. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  89257. if (_this._captureActiveMeshesEvaluationTime) {
  89258. _this._activeMeshesEvaluationTime.fetchNewFrame();
  89259. }
  89260. if (_this._captureRenderTargetsRenderTime) {
  89261. _this._renderTargetsRenderTime.fetchNewFrame();
  89262. }
  89263. if (_this._captureFrameTime) {
  89264. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  89265. _this._frameTime.beginMonitoring();
  89266. }
  89267. if (_this._captureInterFrameTime) {
  89268. _this._interFrameTime.endMonitoring();
  89269. }
  89270. if (_this._captureParticlesRenderTime) {
  89271. _this._particlesRenderTime.fetchNewFrame();
  89272. }
  89273. if (_this._captureSpritesRenderTime) {
  89274. _this._spritesRenderTime.fetchNewFrame();
  89275. }
  89276. if (_this._captureAnimationsTime) {
  89277. _this._animationsTime.beginMonitoring();
  89278. }
  89279. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  89280. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  89281. });
  89282. // After render
  89283. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  89284. if (_this._captureFrameTime) {
  89285. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  89286. _this._frameTime.endMonitoring();
  89287. }
  89288. if (_this._captureRenderTime) {
  89289. _this._renderTime.endMonitoring(false);
  89290. }
  89291. if (_this._captureInterFrameTime) {
  89292. _this._interFrameTime.beginMonitoring();
  89293. }
  89294. });
  89295. }
  89296. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  89297. // Properties
  89298. /**
  89299. * Gets the perf counter used for active meshes evaluation time
  89300. */
  89301. get: function () {
  89302. return this._activeMeshesEvaluationTime;
  89303. },
  89304. enumerable: true,
  89305. configurable: true
  89306. });
  89307. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  89308. /**
  89309. * Gets the active meshes evaluation time capture status
  89310. */
  89311. get: function () {
  89312. return this._captureActiveMeshesEvaluationTime;
  89313. },
  89314. /**
  89315. * Enable or disable the active meshes evaluation time capture
  89316. */
  89317. set: function (value) {
  89318. var _this = this;
  89319. if (value === this._captureActiveMeshesEvaluationTime) {
  89320. return;
  89321. }
  89322. this._captureActiveMeshesEvaluationTime = value;
  89323. if (value) {
  89324. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  89325. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  89326. _this._activeMeshesEvaluationTime.beginMonitoring();
  89327. });
  89328. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  89329. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  89330. _this._activeMeshesEvaluationTime.endMonitoring();
  89331. });
  89332. }
  89333. else {
  89334. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  89335. this._onBeforeActiveMeshesEvaluationObserver = null;
  89336. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  89337. this._onAfterActiveMeshesEvaluationObserver = null;
  89338. }
  89339. },
  89340. enumerable: true,
  89341. configurable: true
  89342. });
  89343. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  89344. /**
  89345. * Gets the perf counter used for render targets render time
  89346. */
  89347. get: function () {
  89348. return this._renderTargetsRenderTime;
  89349. },
  89350. enumerable: true,
  89351. configurable: true
  89352. });
  89353. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  89354. /**
  89355. * Gets the render targets render time capture status
  89356. */
  89357. get: function () {
  89358. return this._captureRenderTargetsRenderTime;
  89359. },
  89360. /**
  89361. * Enable or disable the render targets render time capture
  89362. */
  89363. set: function (value) {
  89364. var _this = this;
  89365. if (value === this._captureRenderTargetsRenderTime) {
  89366. return;
  89367. }
  89368. this._captureRenderTargetsRenderTime = value;
  89369. if (value) {
  89370. this._onBeforeRenderTargetsRenderObserver = this.scene.OnBeforeRenderTargetsRenderObservable.add(function () {
  89371. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  89372. _this._renderTargetsRenderTime.beginMonitoring();
  89373. });
  89374. this._onAfterRenderTargetsRenderObserver = this.scene.OnAfterRenderTargetsRenderObservable.add(function () {
  89375. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  89376. _this._renderTargetsRenderTime.endMonitoring(false);
  89377. });
  89378. }
  89379. else {
  89380. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  89381. this._onBeforeRenderTargetsRenderObserver = null;
  89382. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  89383. this._onAfterRenderTargetsRenderObserver = null;
  89384. }
  89385. },
  89386. enumerable: true,
  89387. configurable: true
  89388. });
  89389. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  89390. /**
  89391. * Gets the perf counter used for particles render time
  89392. */
  89393. get: function () {
  89394. return this._particlesRenderTime;
  89395. },
  89396. enumerable: true,
  89397. configurable: true
  89398. });
  89399. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  89400. /**
  89401. * Gets the particles render time capture status
  89402. */
  89403. get: function () {
  89404. return this._captureParticlesRenderTime;
  89405. },
  89406. /**
  89407. * Enable or disable the particles render time capture
  89408. */
  89409. set: function (value) {
  89410. var _this = this;
  89411. if (value === this._captureParticlesRenderTime) {
  89412. return;
  89413. }
  89414. this._captureParticlesRenderTime = value;
  89415. if (value) {
  89416. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  89417. BABYLON.Tools.StartPerformanceCounter("Particles");
  89418. _this._particlesRenderTime.beginMonitoring();
  89419. });
  89420. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  89421. BABYLON.Tools.EndPerformanceCounter("Particles");
  89422. _this._particlesRenderTime.endMonitoring(false);
  89423. });
  89424. }
  89425. else {
  89426. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  89427. this._onBeforeParticlesRenderingObserver = null;
  89428. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  89429. this._onAfterParticlesRenderingObserver = null;
  89430. }
  89431. },
  89432. enumerable: true,
  89433. configurable: true
  89434. });
  89435. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  89436. /**
  89437. * Gets the perf counter used for sprites render time
  89438. */
  89439. get: function () {
  89440. return this._spritesRenderTime;
  89441. },
  89442. enumerable: true,
  89443. configurable: true
  89444. });
  89445. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  89446. /**
  89447. * Gets the sprites render time capture status
  89448. */
  89449. get: function () {
  89450. return this._captureSpritesRenderTime;
  89451. },
  89452. /**
  89453. * Enable or disable the sprites render time capture
  89454. */
  89455. set: function (value) {
  89456. var _this = this;
  89457. if (value === this._captureSpritesRenderTime) {
  89458. return;
  89459. }
  89460. this._captureSpritesRenderTime = value;
  89461. if (value) {
  89462. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  89463. BABYLON.Tools.StartPerformanceCounter("Sprites");
  89464. _this._spritesRenderTime.beginMonitoring();
  89465. });
  89466. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  89467. BABYLON.Tools.EndPerformanceCounter("Sprites");
  89468. _this._spritesRenderTime.endMonitoring(false);
  89469. });
  89470. }
  89471. else {
  89472. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  89473. this._onBeforeSpritesRenderingObserver = null;
  89474. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  89475. this._onAfterSpritesRenderingObserver = null;
  89476. }
  89477. },
  89478. enumerable: true,
  89479. configurable: true
  89480. });
  89481. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  89482. /**
  89483. * Gets the perf counter used for physics time
  89484. */
  89485. get: function () {
  89486. return this._physicsTime;
  89487. },
  89488. enumerable: true,
  89489. configurable: true
  89490. });
  89491. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  89492. /**
  89493. * Gets the physics time capture status
  89494. */
  89495. get: function () {
  89496. return this._capturePhysicsTime;
  89497. },
  89498. /**
  89499. * Enable or disable the physics time capture
  89500. */
  89501. set: function (value) {
  89502. var _this = this;
  89503. if (value === this._capturePhysicsTime) {
  89504. return;
  89505. }
  89506. this._capturePhysicsTime = value;
  89507. if (value) {
  89508. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  89509. BABYLON.Tools.StartPerformanceCounter("Physics");
  89510. _this._physicsTime.beginMonitoring();
  89511. });
  89512. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  89513. BABYLON.Tools.EndPerformanceCounter("Physics");
  89514. _this._physicsTime.endMonitoring();
  89515. });
  89516. }
  89517. else {
  89518. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  89519. this._onBeforePhysicsObserver = null;
  89520. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  89521. this._onAfterPhysicsObserver = null;
  89522. }
  89523. },
  89524. enumerable: true,
  89525. configurable: true
  89526. });
  89527. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  89528. /**
  89529. * Gets the perf counter used for animations time
  89530. */
  89531. get: function () {
  89532. return this._animationsTime;
  89533. },
  89534. enumerable: true,
  89535. configurable: true
  89536. });
  89537. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  89538. /**
  89539. * Gets the animations time capture status
  89540. */
  89541. get: function () {
  89542. return this._captureAnimationsTime;
  89543. },
  89544. /**
  89545. * Enable or disable the animations time capture
  89546. */
  89547. set: function (value) {
  89548. var _this = this;
  89549. if (value === this._captureAnimationsTime) {
  89550. return;
  89551. }
  89552. this._captureAnimationsTime = value;
  89553. if (value) {
  89554. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  89555. _this._animationsTime.endMonitoring();
  89556. });
  89557. }
  89558. else {
  89559. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  89560. this._onAfterAnimationsObserver = null;
  89561. }
  89562. },
  89563. enumerable: true,
  89564. configurable: true
  89565. });
  89566. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  89567. /**
  89568. * Gets the perf counter used for frame time capture
  89569. */
  89570. get: function () {
  89571. return this._frameTime;
  89572. },
  89573. enumerable: true,
  89574. configurable: true
  89575. });
  89576. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  89577. /**
  89578. * Gets the frame time capture status
  89579. */
  89580. get: function () {
  89581. return this._captureFrameTime;
  89582. },
  89583. /**
  89584. * Enable or disable the frame time capture
  89585. */
  89586. set: function (value) {
  89587. this._captureFrameTime = value;
  89588. },
  89589. enumerable: true,
  89590. configurable: true
  89591. });
  89592. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  89593. /**
  89594. * Gets the perf counter used for inter-frames time capture
  89595. */
  89596. get: function () {
  89597. return this._interFrameTime;
  89598. },
  89599. enumerable: true,
  89600. configurable: true
  89601. });
  89602. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  89603. /**
  89604. * Gets the inter-frames time capture status
  89605. */
  89606. get: function () {
  89607. return this._captureInterFrameTime;
  89608. },
  89609. /**
  89610. * Enable or disable the inter-frames time capture
  89611. */
  89612. set: function (value) {
  89613. this._captureInterFrameTime = value;
  89614. },
  89615. enumerable: true,
  89616. configurable: true
  89617. });
  89618. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  89619. /**
  89620. * Gets the perf counter used for render time capture
  89621. */
  89622. get: function () {
  89623. return this._renderTime;
  89624. },
  89625. enumerable: true,
  89626. configurable: true
  89627. });
  89628. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  89629. /**
  89630. * Gets the render time capture status
  89631. */
  89632. get: function () {
  89633. return this._captureRenderTime;
  89634. },
  89635. /**
  89636. * Enable or disable the render time capture
  89637. */
  89638. set: function (value) {
  89639. var _this = this;
  89640. if (value === this._captureRenderTime) {
  89641. return;
  89642. }
  89643. this._captureRenderTime = value;
  89644. if (value) {
  89645. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  89646. _this._renderTime.beginMonitoring();
  89647. BABYLON.Tools.StartPerformanceCounter("Main render");
  89648. });
  89649. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  89650. _this._renderTime.endMonitoring(false);
  89651. BABYLON.Tools.EndPerformanceCounter("Main render");
  89652. });
  89653. }
  89654. else {
  89655. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  89656. this._onBeforeDrawPhaseObserver = null;
  89657. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  89658. this._onAfterDrawPhaseObserver = null;
  89659. }
  89660. },
  89661. enumerable: true,
  89662. configurable: true
  89663. });
  89664. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  89665. /**
  89666. * Gets the perf counter used for draw calls
  89667. */
  89668. get: function () {
  89669. return this.scene.getEngine()._drawCalls;
  89670. },
  89671. enumerable: true,
  89672. configurable: true
  89673. });
  89674. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  89675. /**
  89676. * Gets the perf counter used for texture collisions
  89677. */
  89678. get: function () {
  89679. return this.scene.getEngine()._textureCollisions;
  89680. },
  89681. enumerable: true,
  89682. configurable: true
  89683. });
  89684. SceneInstrumentation.prototype.dispose = function () {
  89685. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  89686. this._onAfterRenderObserver = null;
  89687. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  89688. this._onBeforeActiveMeshesEvaluationObserver = null;
  89689. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  89690. this._onAfterActiveMeshesEvaluationObserver = null;
  89691. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  89692. this._onBeforeRenderTargetsRenderObserver = null;
  89693. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  89694. this._onAfterRenderTargetsRenderObserver = null;
  89695. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  89696. this._onBeforeAnimationsObserver = null;
  89697. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  89698. this._onBeforeParticlesRenderingObserver = null;
  89699. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  89700. this._onAfterParticlesRenderingObserver = null;
  89701. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  89702. this._onBeforeSpritesRenderingObserver = null;
  89703. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  89704. this._onAfterSpritesRenderingObserver = null;
  89705. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  89706. this._onBeforeDrawPhaseObserver = null;
  89707. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  89708. this._onAfterDrawPhaseObserver = null;
  89709. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  89710. this._onBeforePhysicsObserver = null;
  89711. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  89712. this._onAfterPhysicsObserver = null;
  89713. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  89714. this._onAfterAnimationsObserver = null;
  89715. this.scene = null;
  89716. };
  89717. return SceneInstrumentation;
  89718. }());
  89719. BABYLON.SceneInstrumentation = SceneInstrumentation;
  89720. })(BABYLON || (BABYLON = {}));
  89721. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  89722. var BABYLON;
  89723. (function (BABYLON) {
  89724. var _TimeToken = /** @class */ (function () {
  89725. function _TimeToken() {
  89726. this._timeElapsedQueryEnded = false;
  89727. }
  89728. return _TimeToken;
  89729. }());
  89730. BABYLON._TimeToken = _TimeToken;
  89731. })(BABYLON || (BABYLON = {}));
  89732. //# sourceMappingURL=babylon.timeToken.js.map
  89733. var BABYLON;
  89734. (function (BABYLON) {
  89735. /**
  89736. * Background material defines definition.
  89737. * @ignore Mainly internal Use
  89738. */
  89739. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  89740. __extends(BackgroundMaterialDefines, _super);
  89741. /**
  89742. * Constructor of the defines.
  89743. */
  89744. function BackgroundMaterialDefines() {
  89745. var _this = _super.call(this) || this;
  89746. /**
  89747. * True if the diffuse texture is in use.
  89748. */
  89749. _this.DIFFUSE = false;
  89750. /**
  89751. * The direct UV channel to use.
  89752. */
  89753. _this.DIFFUSEDIRECTUV = 0;
  89754. /**
  89755. * True if the diffuse texture is in gamma space.
  89756. */
  89757. _this.GAMMADIFFUSE = false;
  89758. /**
  89759. * True if the diffuse texture has opacity in the alpha channel.
  89760. */
  89761. _this.DIFFUSEHASALPHA = false;
  89762. /**
  89763. * True if you want the material to fade to transparent at grazing angle.
  89764. */
  89765. _this.OPACITYFRESNEL = false;
  89766. /**
  89767. * True if an extra blur needs to be added in the reflection.
  89768. */
  89769. _this.REFLECTIONBLUR = false;
  89770. /**
  89771. * True if you want the material to fade to reflection at grazing angle.
  89772. */
  89773. _this.REFLECTIONFRESNEL = false;
  89774. /**
  89775. * True if you want the material to falloff as far as you move away from the scene center.
  89776. */
  89777. _this.REFLECTIONFALLOFF = false;
  89778. /**
  89779. * False if the current Webgl implementation does not support the texture lod extension.
  89780. */
  89781. _this.TEXTURELODSUPPORT = false;
  89782. /**
  89783. * True to ensure the data are premultiplied.
  89784. */
  89785. _this.PREMULTIPLYALPHA = false;
  89786. /**
  89787. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  89788. */
  89789. _this.USERGBCOLOR = false;
  89790. /**
  89791. * True to add noise in order to reduce the banding effect.
  89792. */
  89793. _this.NOISE = false;
  89794. /**
  89795. * is the reflection texture in BGR color scheme?
  89796. * Mainly used to solve a bug in ios10 video tag
  89797. */
  89798. _this.REFLECTIONBGR = false;
  89799. _this.IMAGEPROCESSING = false;
  89800. _this.VIGNETTE = false;
  89801. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  89802. _this.VIGNETTEBLENDMODEOPAQUE = false;
  89803. _this.TONEMAPPING = false;
  89804. _this.CONTRAST = false;
  89805. _this.COLORCURVES = false;
  89806. _this.COLORGRADING = false;
  89807. _this.COLORGRADING3D = false;
  89808. _this.SAMPLER3DGREENDEPTH = false;
  89809. _this.SAMPLER3DBGRMAP = false;
  89810. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  89811. _this.EXPOSURE = false;
  89812. _this.GRAIN = false;
  89813. // Reflection.
  89814. _this.REFLECTION = false;
  89815. _this.REFLECTIONMAP_3D = false;
  89816. _this.REFLECTIONMAP_SPHERICAL = false;
  89817. _this.REFLECTIONMAP_PLANAR = false;
  89818. _this.REFLECTIONMAP_CUBIC = false;
  89819. _this.REFLECTIONMAP_PROJECTION = false;
  89820. _this.REFLECTIONMAP_SKYBOX = false;
  89821. _this.REFLECTIONMAP_EXPLICIT = false;
  89822. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  89823. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  89824. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  89825. _this.INVERTCUBICMAP = false;
  89826. _this.REFLECTIONMAP_OPPOSITEZ = false;
  89827. _this.LODINREFLECTIONALPHA = false;
  89828. _this.GAMMAREFLECTION = false;
  89829. _this.EQUIRECTANGULAR_RELFECTION_FOV = false;
  89830. // Default BJS.
  89831. _this.MAINUV1 = false;
  89832. _this.MAINUV2 = false;
  89833. _this.UV1 = false;
  89834. _this.UV2 = false;
  89835. _this.CLIPPLANE = false;
  89836. _this.POINTSIZE = false;
  89837. _this.FOG = false;
  89838. _this.NORMAL = false;
  89839. _this.NUM_BONE_INFLUENCERS = 0;
  89840. _this.BonesPerMesh = 0;
  89841. _this.INSTANCES = false;
  89842. _this.SHADOWFLOAT = false;
  89843. _this.rebuild();
  89844. return _this;
  89845. }
  89846. return BackgroundMaterialDefines;
  89847. }(BABYLON.MaterialDefines));
  89848. /**
  89849. * Background material used to create an efficient environement around your scene.
  89850. */
  89851. var BackgroundMaterial = /** @class */ (function (_super) {
  89852. __extends(BackgroundMaterial, _super);
  89853. /**
  89854. * Instantiates a Background Material in the given scene
  89855. * @param name The friendly name of the material
  89856. * @param scene The scene to add the material to
  89857. */
  89858. function BackgroundMaterial(name, scene) {
  89859. var _this = _super.call(this, name, scene) || this;
  89860. /**
  89861. * Key light Color (multiply against the R channel of the environement texture)
  89862. */
  89863. _this.primaryColor = BABYLON.Color3.White();
  89864. /**
  89865. * Key light Level (allowing HDR output of the background)
  89866. */
  89867. _this.primaryLevel = 1;
  89868. /**
  89869. * Secondary light Color (multiply against the G channel of the environement texture)
  89870. */
  89871. _this.secondaryColor = BABYLON.Color3.Gray();
  89872. /**
  89873. * Secondary light Level (allowing HDR output of the background)
  89874. */
  89875. _this.secondaryLevel = 1;
  89876. /**
  89877. * Tertiary light Color (multiply against the B channel of the environement texture)
  89878. */
  89879. _this.tertiaryColor = BABYLON.Color3.Black();
  89880. /**
  89881. * Tertiary light Level (allowing HDR output of the background)
  89882. */
  89883. _this.tertiaryLevel = 1;
  89884. /**
  89885. * Reflection Texture used in the material.
  89886. * Should be author in a specific way for the best result (refer to the documentation).
  89887. */
  89888. _this.reflectionTexture = null;
  89889. /**
  89890. * Reflection Texture level of blur.
  89891. *
  89892. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  89893. * texture twice.
  89894. */
  89895. _this.reflectionBlur = 0;
  89896. /**
  89897. * Diffuse Texture used in the material.
  89898. * Should be author in a specific way for the best result (refer to the documentation).
  89899. */
  89900. _this.diffuseTexture = null;
  89901. _this._shadowLights = null;
  89902. /**
  89903. * Specify the list of lights casting shadow on the material.
  89904. * All scene shadow lights will be included if null.
  89905. */
  89906. _this.shadowLights = null;
  89907. /**
  89908. * For the lights having a blurred shadow generator, this can add a second blur pass in order to reach
  89909. * soft lighting on the background.
  89910. */
  89911. _this.shadowBlurScale = 1;
  89912. /**
  89913. * Helps adjusting the shadow to a softer level if required.
  89914. * 0 means black shadows and 1 means no shadows.
  89915. */
  89916. _this.shadowLevel = 0;
  89917. /**
  89918. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  89919. * It is usually zero but might be interesting to modify according to your setup.
  89920. */
  89921. _this.sceneCenter = BABYLON.Vector3.Zero();
  89922. /**
  89923. * This helps specifying that the material is falling off to the sky box at grazing angle.
  89924. * This helps ensuring a nice transition when the camera goes under the ground.
  89925. */
  89926. _this.opacityFresnel = true;
  89927. /**
  89928. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  89929. * This helps adding a mirror texture on the ground.
  89930. */
  89931. _this.reflectionFresnel = false;
  89932. /**
  89933. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  89934. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  89935. */
  89936. _this.reflectionFalloffDistance = 0.0;
  89937. /**
  89938. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  89939. */
  89940. _this.reflectionAmount = 1.0;
  89941. /**
  89942. * This specifies the weight of the reflection at grazing angle.
  89943. */
  89944. _this.reflectionReflectance0 = 0.05;
  89945. /**
  89946. * This specifies the weight of the reflection at a perpendicular point of view.
  89947. */
  89948. _this.reflectionReflectance90 = 0.5;
  89949. /**
  89950. * Helps to directly use the maps channels instead of their level.
  89951. */
  89952. _this.useRGBColor = true;
  89953. /**
  89954. * This helps reducing the banding effect that could occur on the background.
  89955. */
  89956. _this.enableNoise = false;
  89957. _this._fovMultiplier = 1.0;
  89958. /**
  89959. * Enable the FOV adjustment feature controlled by fovMultiplier.
  89960. * @type {boolean}
  89961. */
  89962. _this.useEquirectangularFOV = false;
  89963. _this._maxSimultaneousLights = 4;
  89964. /**
  89965. * Number of Simultaneous lights allowed on the material.
  89966. */
  89967. _this.maxSimultaneousLights = 4;
  89968. /**
  89969. * Keep track of the image processing observer to allow dispose and replace.
  89970. */
  89971. _this._imageProcessingObserver = null;
  89972. /**
  89973. * Due to a bug in iOS10, video tags (which are using the background material) are in BGR and not RGB.
  89974. * Setting this flag to true (not done automatically!) will convert it back to RGB.
  89975. */
  89976. _this.switchToBGR = false;
  89977. // Temp values kept as cache in the material.
  89978. _this._renderTargets = new BABYLON.SmartArray(16);
  89979. _this._reflectionControls = BABYLON.Vector4.Zero();
  89980. // Setup the default processing configuration to the scene.
  89981. _this._attachImageProcessingConfiguration(null);
  89982. _this.getRenderTargetTextures = function () {
  89983. _this._renderTargets.reset();
  89984. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  89985. _this._renderTargets.push(_this._diffuseTexture);
  89986. }
  89987. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  89988. _this._renderTargets.push(_this._reflectionTexture);
  89989. }
  89990. return _this._renderTargets;
  89991. };
  89992. return _this;
  89993. }
  89994. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  89995. /**
  89996. * Sets the reflection reflectance fresnel values according to the default standard
  89997. * empirically know to work well :-)
  89998. */
  89999. set: function (value) {
  90000. var reflectionWeight = value;
  90001. if (reflectionWeight < 0.5) {
  90002. reflectionWeight = reflectionWeight * 2.0;
  90003. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  90004. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  90005. }
  90006. else {
  90007. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  90008. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  90009. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  90010. }
  90011. },
  90012. enumerable: true,
  90013. configurable: true
  90014. });
  90015. Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", {
  90016. /**
  90017. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  90018. * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
  90019. * Recommended to be keep at 1.0 except for special cases.
  90020. */
  90021. get: function () {
  90022. return this._fovMultiplier;
  90023. },
  90024. set: function (value) {
  90025. if (isNaN(value)) {
  90026. value = 1.0;
  90027. }
  90028. this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
  90029. },
  90030. enumerable: true,
  90031. configurable: true
  90032. });
  90033. /**
  90034. * Attaches a new image processing configuration to the PBR Material.
  90035. * @param configuration (if null the scene configuration will be use)
  90036. */
  90037. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  90038. var _this = this;
  90039. if (configuration === this._imageProcessingConfiguration) {
  90040. return;
  90041. }
  90042. // Detaches observer.
  90043. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  90044. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  90045. }
  90046. // Pick the scene configuration if needed.
  90047. if (!configuration) {
  90048. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  90049. }
  90050. else {
  90051. this._imageProcessingConfiguration = configuration;
  90052. }
  90053. // Attaches observer.
  90054. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  90055. _this._markAllSubMeshesAsImageProcessingDirty();
  90056. });
  90057. };
  90058. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  90059. /**
  90060. * Gets the image processing configuration used either in this material.
  90061. */
  90062. get: function () {
  90063. return this._imageProcessingConfiguration;
  90064. },
  90065. /**
  90066. * Sets the Default image processing configuration used either in the this material.
  90067. *
  90068. * If sets to null, the scene one is in use.
  90069. */
  90070. set: function (value) {
  90071. this._attachImageProcessingConfiguration(value);
  90072. // Ensure the effect will be rebuilt.
  90073. this._markAllSubMeshesAsTexturesDirty();
  90074. },
  90075. enumerable: true,
  90076. configurable: true
  90077. });
  90078. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  90079. /**
  90080. * Gets wether the color curves effect is enabled.
  90081. */
  90082. get: function () {
  90083. return this.imageProcessingConfiguration.colorCurvesEnabled;
  90084. },
  90085. /**
  90086. * Sets wether the color curves effect is enabled.
  90087. */
  90088. set: function (value) {
  90089. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  90090. },
  90091. enumerable: true,
  90092. configurable: true
  90093. });
  90094. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  90095. /**
  90096. * Gets wether the color grading effect is enabled.
  90097. */
  90098. get: function () {
  90099. return this.imageProcessingConfiguration.colorGradingEnabled;
  90100. },
  90101. /**
  90102. * Gets wether the color grading effect is enabled.
  90103. */
  90104. set: function (value) {
  90105. this.imageProcessingConfiguration.colorGradingEnabled = value;
  90106. },
  90107. enumerable: true,
  90108. configurable: true
  90109. });
  90110. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  90111. /**
  90112. * Gets wether tonemapping is enabled or not.
  90113. */
  90114. get: function () {
  90115. return this._imageProcessingConfiguration.toneMappingEnabled;
  90116. },
  90117. /**
  90118. * Sets wether tonemapping is enabled or not
  90119. */
  90120. set: function (value) {
  90121. this._imageProcessingConfiguration.toneMappingEnabled = value;
  90122. },
  90123. enumerable: true,
  90124. configurable: true
  90125. });
  90126. ;
  90127. ;
  90128. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  90129. /**
  90130. * The camera exposure used on this material.
  90131. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  90132. * This corresponds to a photographic exposure.
  90133. */
  90134. get: function () {
  90135. return this._imageProcessingConfiguration.exposure;
  90136. },
  90137. /**
  90138. * The camera exposure used on this material.
  90139. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  90140. * This corresponds to a photographic exposure.
  90141. */
  90142. set: function (value) {
  90143. this._imageProcessingConfiguration.exposure = value;
  90144. },
  90145. enumerable: true,
  90146. configurable: true
  90147. });
  90148. ;
  90149. ;
  90150. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  90151. /**
  90152. * Gets The camera contrast used on this material.
  90153. */
  90154. get: function () {
  90155. return this._imageProcessingConfiguration.contrast;
  90156. },
  90157. /**
  90158. * Sets The camera contrast used on this material.
  90159. */
  90160. set: function (value) {
  90161. this._imageProcessingConfiguration.contrast = value;
  90162. },
  90163. enumerable: true,
  90164. configurable: true
  90165. });
  90166. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  90167. /**
  90168. * Gets the Color Grading 2D Lookup Texture.
  90169. */
  90170. get: function () {
  90171. return this._imageProcessingConfiguration.colorGradingTexture;
  90172. },
  90173. /**
  90174. * Sets the Color Grading 2D Lookup Texture.
  90175. */
  90176. set: function (value) {
  90177. this.imageProcessingConfiguration.colorGradingTexture = value;
  90178. },
  90179. enumerable: true,
  90180. configurable: true
  90181. });
  90182. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  90183. /**
  90184. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  90185. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  90186. * 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;
  90187. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  90188. */
  90189. get: function () {
  90190. return this.imageProcessingConfiguration.colorCurves;
  90191. },
  90192. /**
  90193. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  90194. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  90195. * 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;
  90196. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  90197. */
  90198. set: function (value) {
  90199. this.imageProcessingConfiguration.colorCurves = value;
  90200. },
  90201. enumerable: true,
  90202. configurable: true
  90203. });
  90204. /**
  90205. * The entire material has been created in order to prevent overdraw.
  90206. * @returns false
  90207. */
  90208. BackgroundMaterial.prototype.needAlphaTesting = function () {
  90209. return true;
  90210. };
  90211. /**
  90212. * The entire material has been created in order to prevent overdraw.
  90213. * @returns true if blending is enable
  90214. */
  90215. BackgroundMaterial.prototype.needAlphaBlending = function () {
  90216. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  90217. };
  90218. /**
  90219. * Checks wether the material is ready to be rendered for a given mesh.
  90220. * @param mesh The mesh to render
  90221. * @param subMesh The submesh to check against
  90222. * @param useInstances Specify wether or not the material is used with instances
  90223. * @returns true if all the dependencies are ready (Textures, Effects...)
  90224. */
  90225. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  90226. var _this = this;
  90227. if (useInstances === void 0) { useInstances = false; }
  90228. if (subMesh.effect && this.isFrozen) {
  90229. if (this._wasPreviouslyReady) {
  90230. return true;
  90231. }
  90232. }
  90233. if (!subMesh._materialDefines) {
  90234. subMesh._materialDefines = new BackgroundMaterialDefines();
  90235. }
  90236. var scene = this.getScene();
  90237. var defines = subMesh._materialDefines;
  90238. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  90239. if (defines._renderId === scene.getRenderId()) {
  90240. return true;
  90241. }
  90242. }
  90243. var engine = scene.getEngine();
  90244. // Lights
  90245. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  90246. defines._needNormals = true;
  90247. // Textures
  90248. if (defines._areTexturesDirty) {
  90249. defines._needUVs = false;
  90250. if (scene.texturesEnabled) {
  90251. if (scene.getEngine().getCaps().textureLOD) {
  90252. defines.TEXTURELODSUPPORT = true;
  90253. }
  90254. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  90255. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  90256. return false;
  90257. }
  90258. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  90259. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  90260. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  90261. defines.OPACITYFRESNEL = this._opacityFresnel;
  90262. }
  90263. else {
  90264. defines.DIFFUSE = false;
  90265. defines.DIFFUSEHASALPHA = false;
  90266. defines.GAMMADIFFUSE = false;
  90267. defines.OPACITYFRESNEL = false;
  90268. }
  90269. var reflectionTexture = this._reflectionTexture;
  90270. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  90271. if (!reflectionTexture.isReadyOrNotBlocking()) {
  90272. return false;
  90273. }
  90274. defines.REFLECTION = true;
  90275. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  90276. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  90277. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  90278. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  90279. defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
  90280. defines.REFLECTIONBGR = this.switchToBGR;
  90281. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  90282. defines.INVERTCUBICMAP = true;
  90283. }
  90284. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  90285. switch (reflectionTexture.coordinatesMode) {
  90286. case BABYLON.Texture.CUBIC_MODE:
  90287. case BABYLON.Texture.INVCUBIC_MODE:
  90288. defines.REFLECTIONMAP_CUBIC = true;
  90289. break;
  90290. case BABYLON.Texture.EXPLICIT_MODE:
  90291. defines.REFLECTIONMAP_EXPLICIT = true;
  90292. break;
  90293. case BABYLON.Texture.PLANAR_MODE:
  90294. defines.REFLECTIONMAP_PLANAR = true;
  90295. break;
  90296. case BABYLON.Texture.PROJECTION_MODE:
  90297. defines.REFLECTIONMAP_PROJECTION = true;
  90298. break;
  90299. case BABYLON.Texture.SKYBOX_MODE:
  90300. defines.REFLECTIONMAP_SKYBOX = true;
  90301. break;
  90302. case BABYLON.Texture.SPHERICAL_MODE:
  90303. defines.REFLECTIONMAP_SPHERICAL = true;
  90304. break;
  90305. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  90306. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  90307. break;
  90308. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  90309. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  90310. break;
  90311. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  90312. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  90313. break;
  90314. }
  90315. if (this.reflectionFresnel) {
  90316. defines.REFLECTIONFRESNEL = true;
  90317. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  90318. this._reflectionControls.x = this.reflectionAmount;
  90319. this._reflectionControls.y = this.reflectionReflectance0;
  90320. this._reflectionControls.z = this.reflectionReflectance90;
  90321. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  90322. }
  90323. else {
  90324. defines.REFLECTIONFRESNEL = false;
  90325. defines.REFLECTIONFALLOFF = false;
  90326. }
  90327. }
  90328. else {
  90329. defines.REFLECTION = false;
  90330. defines.REFLECTIONFALLOFF = false;
  90331. defines.REFLECTIONBLUR = false;
  90332. defines.REFLECTIONMAP_3D = false;
  90333. defines.REFLECTIONMAP_SPHERICAL = false;
  90334. defines.REFLECTIONMAP_PLANAR = false;
  90335. defines.REFLECTIONMAP_CUBIC = false;
  90336. defines.REFLECTIONMAP_PROJECTION = false;
  90337. defines.REFLECTIONMAP_SKYBOX = false;
  90338. defines.REFLECTIONMAP_EXPLICIT = false;
  90339. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  90340. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  90341. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  90342. defines.INVERTCUBICMAP = false;
  90343. defines.REFLECTIONMAP_OPPOSITEZ = false;
  90344. defines.LODINREFLECTIONALPHA = false;
  90345. defines.GAMMAREFLECTION = false;
  90346. }
  90347. }
  90348. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  90349. defines.USERGBCOLOR = this._useRGBColor;
  90350. defines.NOISE = this._enableNoise;
  90351. }
  90352. if (defines._areImageProcessingDirty) {
  90353. if (!this._imageProcessingConfiguration.isReady()) {
  90354. return false;
  90355. }
  90356. this._imageProcessingConfiguration.prepareDefines(defines);
  90357. }
  90358. // Misc.
  90359. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  90360. // Values that need to be evaluated on every frame
  90361. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  90362. // Attribs
  90363. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  90364. if (mesh) {
  90365. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  90366. mesh.createNormals(true);
  90367. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  90368. }
  90369. }
  90370. }
  90371. // Get correct effect
  90372. if (defines.isDirty) {
  90373. defines.markAsProcessed();
  90374. scene.resetCachedMaterial();
  90375. // Fallbacks
  90376. var fallbacks = new BABYLON.EffectFallbacks();
  90377. if (defines.FOG) {
  90378. fallbacks.addFallback(0, "FOG");
  90379. }
  90380. if (defines.POINTSIZE) {
  90381. fallbacks.addFallback(1, "POINTSIZE");
  90382. }
  90383. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  90384. if (defines.NUM_BONE_INFLUENCERS > 0) {
  90385. fallbacks.addCPUSkinningFallback(0, mesh);
  90386. }
  90387. //Attributes
  90388. var attribs = [BABYLON.VertexBuffer.PositionKind];
  90389. if (defines.NORMAL) {
  90390. attribs.push(BABYLON.VertexBuffer.NormalKind);
  90391. }
  90392. if (defines.UV1) {
  90393. attribs.push(BABYLON.VertexBuffer.UVKind);
  90394. }
  90395. if (defines.UV2) {
  90396. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  90397. }
  90398. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  90399. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  90400. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  90401. "vFogInfos", "vFogColor", "pointSize",
  90402. "vClipPlane", "mBones",
  90403. "vPrimaryColor", "vSecondaryColor", "vTertiaryColor",
  90404. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier",
  90405. "shadowLevel", "alpha",
  90406. "vBackgroundCenter", "vReflectionControl",
  90407. "vDiffuseInfos", "diffuseMatrix",
  90408. ];
  90409. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  90410. var uniformBuffers = ["Material", "Scene"];
  90411. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  90412. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  90413. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  90414. uniformsNames: uniforms,
  90415. uniformBuffersNames: uniformBuffers,
  90416. samplers: samplers,
  90417. defines: defines,
  90418. maxSimultaneousLights: this._maxSimultaneousLights
  90419. });
  90420. var onCompiled = function (effect) {
  90421. if (_this.onCompiled) {
  90422. _this.onCompiled(effect);
  90423. }
  90424. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  90425. };
  90426. var join = defines.toString();
  90427. subMesh.setEffect(scene.getEngine().createEffect("background", {
  90428. attributes: attribs,
  90429. uniformsNames: uniforms,
  90430. uniformBuffersNames: uniformBuffers,
  90431. samplers: samplers,
  90432. defines: join,
  90433. fallbacks: fallbacks,
  90434. onCompiled: onCompiled,
  90435. onError: this.onError,
  90436. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  90437. }, engine), defines);
  90438. this.buildUniformLayout();
  90439. }
  90440. if (!subMesh.effect || !subMesh.effect.isReady()) {
  90441. return false;
  90442. }
  90443. defines._renderId = scene.getRenderId();
  90444. this._wasPreviouslyReady = true;
  90445. return true;
  90446. };
  90447. /**
  90448. * Build the uniform buffer used in the material.
  90449. */
  90450. BackgroundMaterial.prototype.buildUniformLayout = function () {
  90451. // Order is important !
  90452. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  90453. this._uniformBuffer.addUniform("vSecondaryColor", 4);
  90454. this._uniformBuffer.addUniform("vTertiaryColor", 4);
  90455. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  90456. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  90457. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  90458. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  90459. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  90460. this._uniformBuffer.addUniform("fFovMultiplier", 1);
  90461. this._uniformBuffer.addUniform("pointSize", 1);
  90462. this._uniformBuffer.addUniform("shadowLevel", 1);
  90463. this._uniformBuffer.addUniform("alpha", 1);
  90464. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  90465. this._uniformBuffer.addUniform("vReflectionControl", 4);
  90466. this._uniformBuffer.create();
  90467. };
  90468. /**
  90469. * Unbind the material.
  90470. */
  90471. BackgroundMaterial.prototype.unbind = function () {
  90472. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  90473. this._uniformBuffer.setTexture("diffuseSampler", null);
  90474. }
  90475. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  90476. this._uniformBuffer.setTexture("reflectionSampler", null);
  90477. }
  90478. _super.prototype.unbind.call(this);
  90479. };
  90480. /**
  90481. * Bind only the world matrix to the material.
  90482. * @param world The world matrix to bind.
  90483. */
  90484. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  90485. this._activeEffect.setMatrix("world", world);
  90486. };
  90487. /**
  90488. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  90489. * @param world The world matrix to bind.
  90490. * @param subMesh The submesh to bind for.
  90491. */
  90492. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  90493. var scene = this.getScene();
  90494. var defines = subMesh._materialDefines;
  90495. if (!defines) {
  90496. return;
  90497. }
  90498. var effect = subMesh.effect;
  90499. if (!effect) {
  90500. return;
  90501. }
  90502. this._activeEffect = effect;
  90503. // Matrices
  90504. this.bindOnlyWorldMatrix(world);
  90505. // Bones
  90506. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  90507. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  90508. if (mustRebind) {
  90509. this._uniformBuffer.bindToEffect(effect, "Material");
  90510. this.bindViewProjection(effect);
  90511. var reflectionTexture = this._reflectionTexture;
  90512. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  90513. // Texture uniforms
  90514. if (scene.texturesEnabled) {
  90515. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  90516. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  90517. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  90518. }
  90519. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  90520. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  90521. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  90522. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  90523. }
  90524. }
  90525. if (this.shadowLevel > 0) {
  90526. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  90527. }
  90528. this._uniformBuffer.updateFloat("alpha", this.alpha);
  90529. // Point size
  90530. if (this.pointsCloud) {
  90531. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  90532. }
  90533. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, this._primaryLevel);
  90534. this._uniformBuffer.updateColor4("vSecondaryColor", this._secondaryColor, this._secondaryLevel);
  90535. this._uniformBuffer.updateColor4("vTertiaryColor", this._tertiaryColor, this._tertiaryLevel);
  90536. }
  90537. this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
  90538. // Textures
  90539. if (scene.texturesEnabled) {
  90540. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  90541. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  90542. }
  90543. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  90544. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  90545. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  90546. }
  90547. else if (!defines.REFLECTIONBLUR) {
  90548. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  90549. }
  90550. else {
  90551. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  90552. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  90553. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  90554. }
  90555. if (defines.REFLECTIONFRESNEL) {
  90556. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  90557. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  90558. }
  90559. }
  90560. }
  90561. // Clip plane
  90562. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  90563. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  90564. }
  90565. if (mustRebind || !this.isFrozen) {
  90566. if (scene.lightsEnabled) {
  90567. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  90568. }
  90569. // View
  90570. this.bindView(effect);
  90571. // Fog
  90572. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  90573. // image processing
  90574. this._imageProcessingConfiguration.bind(this._activeEffect);
  90575. }
  90576. this._uniformBuffer.update();
  90577. this._afterBind(mesh);
  90578. };
  90579. /**
  90580. * Dispose the material.
  90581. * @param forceDisposeEffect Force disposal of the associated effect.
  90582. * @param forceDisposeTextures Force disposal of the associated textures.
  90583. */
  90584. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  90585. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  90586. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  90587. if (forceDisposeTextures) {
  90588. if (this.diffuseTexture) {
  90589. this.diffuseTexture.dispose();
  90590. }
  90591. if (this.reflectionTexture) {
  90592. this.reflectionTexture.dispose();
  90593. }
  90594. }
  90595. this._renderTargets.dispose();
  90596. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  90597. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  90598. }
  90599. _super.prototype.dispose.call(this, forceDisposeEffect);
  90600. };
  90601. /**
  90602. * Clones the material.
  90603. * @param name The cloned name.
  90604. * @returns The cloned material.
  90605. */
  90606. BackgroundMaterial.prototype.clone = function (name) {
  90607. var _this = this;
  90608. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  90609. };
  90610. /**
  90611. * Serializes the current material to its JSON representation.
  90612. * @returns The JSON representation.
  90613. */
  90614. BackgroundMaterial.prototype.serialize = function () {
  90615. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  90616. serializationObject.customType = "BABYLON.BackgroundMaterial";
  90617. return serializationObject;
  90618. };
  90619. /**
  90620. * Gets the class name of the material
  90621. * @returns "BackgroundMaterial"
  90622. */
  90623. BackgroundMaterial.prototype.getClassName = function () {
  90624. return "BackgroundMaterial";
  90625. };
  90626. /**
  90627. * Parse a JSON input to create back a background material.
  90628. * @param source The JSON data to parse
  90629. * @param scene The scene to create the parsed material in
  90630. * @param rootUrl The root url of the assets the material depends upon
  90631. * @returns the instantiated BackgroundMaterial.
  90632. */
  90633. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  90634. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  90635. };
  90636. /**
  90637. * Standard reflectance value at parallel view angle.
  90638. */
  90639. BackgroundMaterial.StandardReflectance0 = 0.05;
  90640. /**
  90641. * Standard reflectance value at grazing angle.
  90642. */
  90643. BackgroundMaterial.StandardReflectance90 = 0.5;
  90644. __decorate([
  90645. BABYLON.serializeAsColor3()
  90646. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  90647. __decorate([
  90648. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  90649. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  90650. __decorate([
  90651. BABYLON.serialize()
  90652. ], BackgroundMaterial.prototype, "_primaryLevel", void 0);
  90653. __decorate([
  90654. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  90655. ], BackgroundMaterial.prototype, "primaryLevel", void 0);
  90656. __decorate([
  90657. BABYLON.serializeAsColor3()
  90658. ], BackgroundMaterial.prototype, "_secondaryColor", void 0);
  90659. __decorate([
  90660. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  90661. ], BackgroundMaterial.prototype, "secondaryColor", void 0);
  90662. __decorate([
  90663. BABYLON.serialize()
  90664. ], BackgroundMaterial.prototype, "_secondaryLevel", void 0);
  90665. __decorate([
  90666. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  90667. ], BackgroundMaterial.prototype, "secondaryLevel", void 0);
  90668. __decorate([
  90669. BABYLON.serializeAsColor3()
  90670. ], BackgroundMaterial.prototype, "_tertiaryColor", void 0);
  90671. __decorate([
  90672. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  90673. ], BackgroundMaterial.prototype, "tertiaryColor", void 0);
  90674. __decorate([
  90675. BABYLON.serialize()
  90676. ], BackgroundMaterial.prototype, "_tertiaryLevel", void 0);
  90677. __decorate([
  90678. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  90679. ], BackgroundMaterial.prototype, "tertiaryLevel", void 0);
  90680. __decorate([
  90681. BABYLON.serializeAsTexture()
  90682. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  90683. __decorate([
  90684. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  90685. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  90686. __decorate([
  90687. BABYLON.serialize()
  90688. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  90689. __decorate([
  90690. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  90691. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  90692. __decorate([
  90693. BABYLON.serializeAsTexture()
  90694. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  90695. __decorate([
  90696. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  90697. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  90698. __decorate([
  90699. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  90700. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  90701. __decorate([
  90702. BABYLON.serialize()
  90703. ], BackgroundMaterial.prototype, "_shadowBlurScale", void 0);
  90704. __decorate([
  90705. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  90706. ], BackgroundMaterial.prototype, "shadowBlurScale", void 0);
  90707. __decorate([
  90708. BABYLON.serialize()
  90709. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  90710. __decorate([
  90711. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  90712. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  90713. __decorate([
  90714. BABYLON.serializeAsVector3()
  90715. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  90716. __decorate([
  90717. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  90718. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  90719. __decorate([
  90720. BABYLON.serialize()
  90721. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  90722. __decorate([
  90723. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  90724. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  90725. __decorate([
  90726. BABYLON.serialize()
  90727. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  90728. __decorate([
  90729. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  90730. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  90731. __decorate([
  90732. BABYLON.serialize()
  90733. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  90734. __decorate([
  90735. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  90736. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  90737. __decorate([
  90738. BABYLON.serialize()
  90739. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  90740. __decorate([
  90741. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  90742. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  90743. __decorate([
  90744. BABYLON.serialize()
  90745. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  90746. __decorate([
  90747. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  90748. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  90749. __decorate([
  90750. BABYLON.serialize()
  90751. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  90752. __decorate([
  90753. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  90754. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  90755. __decorate([
  90756. BABYLON.serialize()
  90757. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  90758. __decorate([
  90759. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  90760. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  90761. __decorate([
  90762. BABYLON.serialize()
  90763. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  90764. __decorate([
  90765. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  90766. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  90767. __decorate([
  90768. BABYLON.serialize()
  90769. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  90770. __decorate([
  90771. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  90772. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  90773. __decorate([
  90774. BABYLON.serializeAsImageProcessingConfiguration()
  90775. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  90776. return BackgroundMaterial;
  90777. }(BABYLON.PushMaterial));
  90778. BABYLON.BackgroundMaterial = BackgroundMaterial;
  90779. })(BABYLON || (BABYLON = {}));
  90780. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  90781. var __assign = (this && this.__assign) || Object.assign || function(t) {
  90782. for (var s, i = 1, n = arguments.length; i < n; i++) {
  90783. s = arguments[i];
  90784. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  90785. t[p] = s[p];
  90786. }
  90787. return t;
  90788. };
  90789. var BABYLON;
  90790. (function (BABYLON) {
  90791. /**
  90792. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  90793. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  90794. * It also helps with the default setup of your imageProcessing configuration.
  90795. */
  90796. var EnvironmentHelper = /** @class */ (function () {
  90797. /**
  90798. * constructor
  90799. * @param options
  90800. * @param scene The scene to add the material to
  90801. */
  90802. function EnvironmentHelper(options, scene) {
  90803. var _this = this;
  90804. this._errorHandler = function (message, exception) {
  90805. _this.onErrorObservable.notifyObservers({ message: message, exception: exception });
  90806. };
  90807. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  90808. this._scene = scene;
  90809. this.onErrorObservable = new BABYLON.Observable();
  90810. this._setupBackground();
  90811. this._setupImageProcessing();
  90812. }
  90813. /**
  90814. * Creates the default options for the helper.
  90815. */
  90816. EnvironmentHelper._getDefaultOptions = function () {
  90817. return {
  90818. createGround: true,
  90819. groundSize: 15,
  90820. groundTexture: this._groundTextureCDNUrl,
  90821. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  90822. groundOpacity: 0.9,
  90823. enableGroundShadow: true,
  90824. groundShadowLevel: 0.5,
  90825. enableGroundMirror: false,
  90826. groundMirrorSizeRatio: 0.3,
  90827. groundMirrorBlurKernel: 64,
  90828. groundMirrorAmount: 1,
  90829. groundMirrorFresnelWeight: 1,
  90830. groundMirrorFallOffDistance: 0,
  90831. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  90832. groundYBias: 0.00001,
  90833. createSkybox: true,
  90834. skyboxSize: 20,
  90835. skyboxTexture: this._skyboxTextureCDNUrl,
  90836. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  90837. backgroundYRotation: 0,
  90838. sizeAuto: true,
  90839. rootPosition: BABYLON.Vector3.Zero(),
  90840. setupImageProcessing: true,
  90841. environmentTexture: this._environmentTextureCDNUrl,
  90842. cameraExposure: 0.8,
  90843. cameraContrast: 1.2,
  90844. toneMappingEnabled: true,
  90845. };
  90846. };
  90847. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  90848. /**
  90849. * Gets the root mesh created by the helper.
  90850. */
  90851. get: function () {
  90852. return this._rootMesh;
  90853. },
  90854. enumerable: true,
  90855. configurable: true
  90856. });
  90857. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  90858. /**
  90859. * Gets the skybox created by the helper.
  90860. */
  90861. get: function () {
  90862. return this._skybox;
  90863. },
  90864. enumerable: true,
  90865. configurable: true
  90866. });
  90867. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  90868. /**
  90869. * Gets the skybox texture created by the helper.
  90870. */
  90871. get: function () {
  90872. return this._skyboxTexture;
  90873. },
  90874. enumerable: true,
  90875. configurable: true
  90876. });
  90877. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  90878. /**
  90879. * Gets the skybox material created by the helper.
  90880. */
  90881. get: function () {
  90882. return this._skyboxMaterial;
  90883. },
  90884. enumerable: true,
  90885. configurable: true
  90886. });
  90887. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  90888. /**
  90889. * Gets the ground mesh created by the helper.
  90890. */
  90891. get: function () {
  90892. return this._ground;
  90893. },
  90894. enumerable: true,
  90895. configurable: true
  90896. });
  90897. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  90898. /**
  90899. * Gets the ground texture created by the helper.
  90900. */
  90901. get: function () {
  90902. return this._groundTexture;
  90903. },
  90904. enumerable: true,
  90905. configurable: true
  90906. });
  90907. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  90908. /**
  90909. * Gets the ground mirror created by the helper.
  90910. */
  90911. get: function () {
  90912. return this._groundMirror;
  90913. },
  90914. enumerable: true,
  90915. configurable: true
  90916. });
  90917. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  90918. /**
  90919. * Gets the ground mirror render list to helps pushing the meshes
  90920. * you wish in the ground reflection.
  90921. */
  90922. get: function () {
  90923. if (this._groundMirror) {
  90924. return this._groundMirror.renderList;
  90925. }
  90926. return null;
  90927. },
  90928. enumerable: true,
  90929. configurable: true
  90930. });
  90931. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  90932. /**
  90933. * Gets the ground material created by the helper.
  90934. */
  90935. get: function () {
  90936. return this._groundMaterial;
  90937. },
  90938. enumerable: true,
  90939. configurable: true
  90940. });
  90941. /**
  90942. * Updates the background according to the new options
  90943. * @param options
  90944. */
  90945. EnvironmentHelper.prototype.updateOptions = function (options) {
  90946. var newOptions = __assign({}, this._options, options);
  90947. if (this._ground && !newOptions.createGround) {
  90948. this._ground.dispose();
  90949. this._ground = null;
  90950. }
  90951. if (this._groundMaterial && !newOptions.createGround) {
  90952. this._groundMaterial.dispose();
  90953. this._groundMaterial = null;
  90954. }
  90955. if (this._groundTexture) {
  90956. if (this._options.groundTexture != newOptions.groundTexture) {
  90957. this._groundTexture.dispose();
  90958. this._groundTexture = null;
  90959. }
  90960. }
  90961. if (this._skybox && !newOptions.createSkybox) {
  90962. this._skybox.dispose();
  90963. this._skybox = null;
  90964. }
  90965. if (this._skyboxMaterial && !newOptions.createSkybox) {
  90966. this._skyboxMaterial.dispose();
  90967. this._skyboxMaterial = null;
  90968. }
  90969. if (this._skyboxTexture) {
  90970. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  90971. this._skyboxTexture.dispose();
  90972. this._skyboxTexture = null;
  90973. }
  90974. }
  90975. if (this._groundMirror && !newOptions.enableGroundMirror) {
  90976. this._groundMirror.dispose();
  90977. this._groundMirror = null;
  90978. }
  90979. if (this._scene.environmentTexture) {
  90980. if (this._options.environmentTexture != newOptions.environmentTexture) {
  90981. this._scene.environmentTexture.dispose();
  90982. }
  90983. }
  90984. this._options = newOptions;
  90985. this._setupBackground();
  90986. this._setupImageProcessing();
  90987. };
  90988. /**
  90989. * Sets the primary color of all the available elements.
  90990. * @param color
  90991. */
  90992. EnvironmentHelper.prototype.setMainColor = function (color) {
  90993. if (this.groundMaterial) {
  90994. this.groundMaterial.primaryColor = color;
  90995. }
  90996. if (this.skyboxMaterial) {
  90997. this.skyboxMaterial.primaryColor = color;
  90998. }
  90999. if (this.groundMirror) {
  91000. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  91001. }
  91002. };
  91003. /**
  91004. * Setup the image processing according to the specified options.
  91005. */
  91006. EnvironmentHelper.prototype._setupImageProcessing = function () {
  91007. if (this._options.setupImageProcessing) {
  91008. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  91009. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  91010. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  91011. this._setupEnvironmentTexture();
  91012. }
  91013. };
  91014. /**
  91015. * Setup the environment texture according to the specified options.
  91016. */
  91017. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  91018. if (this._scene.environmentTexture) {
  91019. return;
  91020. }
  91021. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  91022. this._scene.environmentTexture = this._options.environmentTexture;
  91023. return;
  91024. }
  91025. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  91026. this._scene.environmentTexture = environmentTexture;
  91027. };
  91028. /**
  91029. * Setup the background according to the specified options.
  91030. */
  91031. EnvironmentHelper.prototype._setupBackground = function () {
  91032. if (!this._rootMesh) {
  91033. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  91034. }
  91035. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  91036. var sceneSize = this._getSceneSize();
  91037. if (this._options.createGround) {
  91038. this._setupGround(sceneSize);
  91039. this._setupGroundMaterial();
  91040. this._setupGroundDiffuseTexture();
  91041. if (this._options.enableGroundMirror) {
  91042. this._setupGroundMirrorTexture(sceneSize);
  91043. }
  91044. this._setupMirrorInGroundMaterial();
  91045. }
  91046. if (this._options.createSkybox) {
  91047. this._setupSkybox(sceneSize);
  91048. this._setupSkyboxMaterial();
  91049. this._setupSkyboxReflectionTexture();
  91050. }
  91051. this._rootMesh.position.x = sceneSize.rootPosition.x;
  91052. this._rootMesh.position.z = sceneSize.rootPosition.z;
  91053. this._rootMesh.position.y = sceneSize.rootPosition.y;
  91054. };
  91055. /**
  91056. * Get the scene sizes according to the setup.
  91057. */
  91058. EnvironmentHelper.prototype._getSceneSize = function () {
  91059. var _this = this;
  91060. var groundSize = this._options.groundSize;
  91061. var skyboxSize = this._options.skyboxSize;
  91062. var rootPosition = this._options.rootPosition;
  91063. if (!this._scene.meshes || this._scene.meshes.length === 1) {
  91064. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  91065. }
  91066. var sceneExtends = this._scene.getWorldExtends(function (mesh) {
  91067. return (mesh !== _this._ground && mesh !== _this._rootMesh && mesh !== _this._skybox);
  91068. });
  91069. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  91070. if (this._options.sizeAuto) {
  91071. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  91072. this._scene.activeCamera.upperRadiusLimit) {
  91073. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  91074. skyboxSize = groundSize;
  91075. }
  91076. var sceneDiagonalLenght = sceneDiagonal.length();
  91077. if (sceneDiagonalLenght > groundSize) {
  91078. groundSize = sceneDiagonalLenght * 2;
  91079. skyboxSize = groundSize;
  91080. }
  91081. // 10 % bigger.
  91082. groundSize *= 1.1;
  91083. skyboxSize *= 1.5;
  91084. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  91085. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  91086. }
  91087. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  91088. };
  91089. /**
  91090. * Setup the ground according to the specified options.
  91091. */
  91092. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  91093. var _this = this;
  91094. if (!this._ground) {
  91095. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  91096. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  91097. this._ground.parent = this._rootMesh;
  91098. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  91099. }
  91100. this._ground.receiveShadows = this._options.enableGroundShadow;
  91101. };
  91102. /**
  91103. * Setup the ground material according to the specified options.
  91104. */
  91105. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  91106. if (!this._groundMaterial) {
  91107. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  91108. }
  91109. this._groundMaterial.alpha = this._options.groundOpacity;
  91110. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  91111. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  91112. this._groundMaterial.primaryLevel = 1;
  91113. this._groundMaterial.primaryColor = this._options.groundColor;
  91114. this._groundMaterial.secondaryLevel = 0;
  91115. this._groundMaterial.tertiaryLevel = 0;
  91116. this._groundMaterial.useRGBColor = false;
  91117. this._groundMaterial.enableNoise = true;
  91118. if (this._ground) {
  91119. this._ground.material = this._groundMaterial;
  91120. }
  91121. };
  91122. /**
  91123. * Setup the ground diffuse texture according to the specified options.
  91124. */
  91125. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  91126. if (!this._groundMaterial) {
  91127. return;
  91128. }
  91129. if (this._groundTexture) {
  91130. return;
  91131. }
  91132. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  91133. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  91134. return;
  91135. }
  91136. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  91137. diffuseTexture.gammaSpace = false;
  91138. diffuseTexture.hasAlpha = true;
  91139. this._groundMaterial.diffuseTexture = diffuseTexture;
  91140. };
  91141. /**
  91142. * Setup the ground mirror texture according to the specified options.
  91143. */
  91144. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  91145. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  91146. if (!this._groundMirror) {
  91147. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  91148. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  91149. this._groundMirror.anisotropicFilteringLevel = 1;
  91150. this._groundMirror.wrapU = wrapping;
  91151. this._groundMirror.wrapV = wrapping;
  91152. this._groundMirror.gammaSpace = false;
  91153. if (this._groundMirror.renderList) {
  91154. for (var i = 0; i < this._scene.meshes.length; i++) {
  91155. var mesh = this._scene.meshes[i];
  91156. if (mesh !== this._ground &&
  91157. mesh !== this._skybox &&
  91158. mesh !== this._rootMesh) {
  91159. this._groundMirror.renderList.push(mesh);
  91160. }
  91161. }
  91162. }
  91163. }
  91164. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  91165. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  91166. };
  91167. /**
  91168. * Setup the ground to receive the mirror texture.
  91169. */
  91170. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  91171. if (this._groundMaterial) {
  91172. this._groundMaterial.reflectionTexture = this._groundMirror;
  91173. this._groundMaterial.reflectionFresnel = true;
  91174. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  91175. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  91176. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  91177. }
  91178. };
  91179. /**
  91180. * Setup the skybox according to the specified options.
  91181. */
  91182. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  91183. var _this = this;
  91184. if (!this._skybox) {
  91185. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  91186. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  91187. }
  91188. this._skybox.parent = this._rootMesh;
  91189. };
  91190. /**
  91191. * Setup the skybox material according to the specified options.
  91192. */
  91193. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  91194. if (!this._skybox) {
  91195. return;
  91196. }
  91197. if (!this._skyboxMaterial) {
  91198. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  91199. }
  91200. this._skyboxMaterial.useRGBColor = false;
  91201. this._skyboxMaterial.primaryLevel = 1;
  91202. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  91203. this._skyboxMaterial.secondaryLevel = 0;
  91204. this._skyboxMaterial.tertiaryLevel = 0;
  91205. this._skyboxMaterial.enableNoise = true;
  91206. this._skybox.material = this._skyboxMaterial;
  91207. };
  91208. /**
  91209. * Setup the skybox reflection texture according to the specified options.
  91210. */
  91211. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  91212. if (!this._skyboxMaterial) {
  91213. return;
  91214. }
  91215. if (this._skyboxTexture) {
  91216. return;
  91217. }
  91218. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  91219. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  91220. return;
  91221. }
  91222. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  91223. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  91224. this._skyboxTexture.gammaSpace = false;
  91225. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  91226. };
  91227. /**
  91228. * Dispose all the elements created by the Helper.
  91229. */
  91230. EnvironmentHelper.prototype.dispose = function () {
  91231. if (this._groundMaterial) {
  91232. this._groundMaterial.dispose(true, true);
  91233. }
  91234. if (this._skyboxMaterial) {
  91235. this._skyboxMaterial.dispose(true, true);
  91236. }
  91237. this._rootMesh.dispose(false);
  91238. };
  91239. /**
  91240. * Default ground texture URL.
  91241. */
  91242. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  91243. /**
  91244. * Default skybox texture URL.
  91245. */
  91246. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  91247. /**
  91248. * Default environment texture URL.
  91249. */
  91250. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.dds";
  91251. return EnvironmentHelper;
  91252. }());
  91253. BABYLON.EnvironmentHelper = EnvironmentHelper;
  91254. })(BABYLON || (BABYLON = {}));
  91255. //# sourceMappingURL=babylon.environmentHelper.js.map
  91256. var BABYLON;
  91257. (function (BABYLON) {
  91258. /**
  91259. * Display a 360 degree video on an approximately spherical surface, useful for VR applications or skyboxes.
  91260. * As a subclass of Node, this allow parenting to the camera or multiple videos with different locations in the scene.
  91261. * This class achieves its effect with a VideoTexture and a correctly configured BackgroundMaterial on an inverted sphere.
  91262. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  91263. */
  91264. var VideoDome = /** @class */ (function (_super) {
  91265. __extends(VideoDome, _super);
  91266. /**
  91267. * Create an instance of this class and pass through the parameters to the relevant classes, VideoTexture, StandardMaterial, and Mesh.
  91268. * @param name Element's name, child elements will append suffixes for their own names.
  91269. * @param urlsOrVideo
  91270. * @param options An object containing optional or exposed sub element properties:
  91271. * @param options **resolution=12** Integer, lower resolutions have more artifacts at extreme fovs
  91272. * @param options **clickToPlay=false** Add a click to play listener to the video, does not prevent autoplay.
  91273. * @param options **autoPlay=true** Automatically attempt to being playing the video.
  91274. * @param options **loop=true** Automatically loop video on end.
  91275. * @param options **size=1000** Physical radius to create the dome at, defaults to approximately half the far clip plane.
  91276. */
  91277. function VideoDome(name, urlsOrVideo, options, scene) {
  91278. var _this = _super.call(this, name, scene) || this;
  91279. // set defaults and manage values
  91280. name = name || "videoDome";
  91281. options.resolution = (Math.abs(options.resolution) | 0) || 12;
  91282. options.clickToPlay = Boolean(options.clickToPlay);
  91283. options.autoPlay = options.autoPlay === undefined ? true : Boolean(options.autoPlay);
  91284. options.loop = options.loop === undefined ? true : Boolean(options.loop);
  91285. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  91286. // create
  91287. var tempOptions = { loop: options.loop, autoPlay: options.autoPlay, autoUpdateTexture: true };
  91288. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  91289. var texture = _this._videoTexture = new BABYLON.VideoTexture(name + "_texture", urlsOrVideo, scene, false, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, tempOptions);
  91290. _this._mesh = BABYLON.MeshBuilder.CreateIcoSphere(name + "_mesh", {
  91291. flat: false,
  91292. radius: options.size,
  91293. subdivisions: options.resolution,
  91294. sideOrientation: BABYLON.Mesh.BACKSIDE // needs to be inside out
  91295. }, scene);
  91296. // configure material
  91297. texture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  91298. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE; // always clamp the up/down
  91299. material.reflectionTexture = _this._videoTexture;
  91300. material.useEquirectangularFOV = true;
  91301. material.fovMultiplier = 1.0;
  91302. // configure mesh
  91303. _this._mesh.material = material;
  91304. _this._mesh.parent = _this;
  91305. // optional configuration
  91306. if (options.clickToPlay) {
  91307. scene.onPointerUp = function () {
  91308. _this._videoTexture.video.play();
  91309. };
  91310. }
  91311. return _this;
  91312. }
  91313. Object.defineProperty(VideoDome.prototype, "fovMultiplier", {
  91314. /**
  91315. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  91316. * Also see the options.resolution property.
  91317. */
  91318. get: function () {
  91319. return this._material.fovMultiplier;
  91320. },
  91321. set: function (value) {
  91322. this._material.fovMultiplier = value;
  91323. },
  91324. enumerable: true,
  91325. configurable: true
  91326. });
  91327. /**
  91328. * Releases resources associated with this node.
  91329. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  91330. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  91331. */
  91332. VideoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  91333. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  91334. this._videoTexture.dispose();
  91335. this._mesh.dispose();
  91336. this._material.dispose();
  91337. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  91338. };
  91339. return VideoDome;
  91340. }(BABYLON.Node));
  91341. BABYLON.VideoDome = VideoDome;
  91342. })(BABYLON || (BABYLON = {}));
  91343. //# sourceMappingURL=babylon.videoDome.js.map
  91344. BABYLON.Effect.ShadersStore={"defaultVertexShader":"#include<__decl__defaultVertex>\n\n#define CUSTOM_VERTEX_BEGIN\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nvarying vec2 vSpecularUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvec3 positionUpdated=position;\n#ifdef NORMAL \nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#define CUSTOM_VERTEX_UPDATE_POSITION\n#define CUSTOM_VERTEX_UPDATE_NORMAL\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif\n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<bumpVertex>\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n#include<pointCloudVertex>\n#include<logDepthVertex>\n#define CUSTOM_VERTEX_MAIN_END\n}\n","defaultPixelShader":"#include<__decl__defaultFragment>\n#if defined(BUMP) || !defined(NORMAL)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#define CUSTOM_FRAGMENT_BEGIN\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n\n#define RECIPROCAL_PI2 0.15915494\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n\n#include<helperFunctions>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY \n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\n#if SPECULARDIRECTUV == 1\n#define vSpecularUV vMainUV1\n#elif SPECULARDIRECTUV == 2\n#define vSpecularUV vMainUV2\n#else\nvarying vec2 vSpecularUV;\n#endif\nuniform sampler2D specularSampler;\n#endif\n\n#include<fresnelFunction>\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#include<imageProcessingDeclaration>\n#include<imageProcessingFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n#include<fogFragmentDeclaration>\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n\nfloat alpha=vDiffuseColor.a;\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(-cross(dFdx(vPositionW),dFdy(vPositionW)));\n#endif\n#include<bumpFragment>\n#ifdef TWOSIDEDLIGHTING\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV+uvOffset);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#ifdef ALPHAFROMDIFFUSE\nalpha*=baseColor.a;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_ALPHA\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_DIFFUSE\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_LIGHTS\n\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;\nvec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nvec4 specularMapColor=texture2D(specularSampler,vSpecularUV+uvOffset);\nspecularColor=specularMapColor.rgb;\n#ifdef GLOSSINESS\nglossiness=glossiness*specularMapColor.a;\n#endif\n#endif\n#else\nfloat glossiness=0.;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\nfloat shadow=1.;\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\n#include<lightFragment>[0..maxSimultaneousLights]\n\nvec3 refractionColor=vec3(0.,0.,0.);\n#ifdef REFRACTION\nvec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y));\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0)\n{\nrefractionColor=textureCube(refractionCubeSampler,refractionVector).rgb*vRefractionInfos.x;\n}\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\nrefractionColor=texture2D(refraction2DSampler,refractionCoords).rgb*vRefractionInfos.x;\n#endif\n#endif\n\nvec3 reflectionColor=vec3(0.,0.,0.);\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_3D\n#ifdef ROUGHNESS\nfloat bias=vReflectionInfos.y;\n#ifdef SPECULARTERM\n#ifdef SPECULAR\n#ifdef GLOSSINESS\nbias*=(1.0-specularMapColor.a);\n#endif\n#endif\n#endif\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW,bias).rgb*vReflectionInfos.x;\n#else\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb*vReflectionInfos.x;\n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\nreflectionColor=texture2D(reflection2DSampler,coords).rgb*vReflectionInfos.x;\n#endif\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\n#ifdef REFLECTIONFRESNELFROMSPECULAR\n#ifdef SPECULARTERM\nreflectionColor*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n#endif\n#ifdef REFRACTIONFRESNEL\nfloat refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);\nrefractionColor*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 emissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor+=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nemissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);\ndiffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\n#ifdef LINKEMISSIVEWITHDIFFUSE\nvec3 finalDiffuse=clamp((diffuseBase+emissiveColor)*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#endif\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+dot(finalSpecular,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef REFLECTIONOVERALPHA\nalpha=clamp(alpha+dot(reflectionColor,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 color=vec4(clamp(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+emissiveColor+refractionColor,0.0,1.0),alpha);\n#else\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+refractionColor,alpha);\n#endif\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\ncolor.rgb*=lightmapColor;\n#else\ncolor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FOG\ncolor.rgb=max(color.rgb,0.);\n#include<logDepthFragment>\n#include<fogFragment>\n\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\ncolor.rgb=toLinearSpace(color.rgb);\n#else\n#ifdef IMAGEPROCESSING\ncolor.rgb=toLinearSpace(color.rgb);\ncolor=applyImageProcessing(color);\n#endif\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR\ngl_FragColor=color;\n}\n","pbrVertexShader":"precision highp float;\n#include<__decl__pbrVertex>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif \n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#if defined(ALBEDO) && ALBEDODIRECTUV == 0\nvarying vec2 vAlbedoUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0\nvarying vec2 vReflectivityUV;\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#include<harmonicsFunctions>\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\nvec3 positionUpdated=position;\n#ifdef NORMAL\nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvec3 reflectionVector=vec3(reflectionMatrix*vec4(vNormalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\nvEnvironmentIrradiance=environmentIrradianceJones(reflectionVector);\n#endif\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif \n#if defined(ALBEDO) && ALBEDODIRECTUV == 0 \nif (vAlbedoInfos.x == 0.)\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0 \nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0 \nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0 \nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0 \nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0 \nif (vReflectivityInfos.x == 0.)\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0 \nif (vMicroSurfaceSamplerInfos.x == 0.)\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0 \nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<bumpVertex>\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n\n#include<logDepthVertex>\n}","pbrPixelShader":"#if defined(BUMP) || !defined(NORMAL) || defined(FORCENORMALFORWARD)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LODBASEDMICROSFURACE\n#extension GL_EXT_shader_texture_lod : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nprecision highp float;\n#include<__decl__pbrFragment>\nuniform vec4 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vCameraInfos;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2;\n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n\n#ifdef ALBEDO\n#if ALBEDODIRECTUV == 1\n#define vAlbedoUV vMainUV1\n#elif ALBEDODIRECTUV == 2\n#define vAlbedoUV vMainUV2\n#else\nvarying vec2 vAlbedoUV;\n#endif\nuniform sampler2D albedoSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY\n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFLECTIVITY\n#if REFLECTIVITYDIRECTUV == 1\n#define vReflectivityUV vMainUV1\n#elif REFLECTIVITYDIRECTUV == 2\n#define vReflectivityUV vMainUV2\n#else\nvarying vec2 vReflectivityUV;\n#endif\nuniform sampler2D reflectivitySampler;\n#endif\n#ifdef MICROSURFACEMAP\n#if MICROSURFACEMAPDIRECTUV == 1\n#define vMicroSurfaceSamplerUV vMainUV1\n#elif MICROSURFACEMAPDIRECTUV == 2\n#define vMicroSurfaceSamplerUV vMainUV2\n#else\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\nuniform sampler2D microSurfaceSampler;\n#endif\n\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\n#define sampleRefraction(s,c) textureCube(s,c)\nuniform samplerCube refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#else\n#define sampleRefraction(s,c) texture2D(s,c)\nuniform sampler2D refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#endif\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#ifdef ENVIRONMENTBRDF\nuniform sampler2D environmentBrdfSampler;\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\n\n#include<shadowsFragmentFunctions>\n#include<pbrFunctions>\n#include<harmonicsFunctions>\n#include<pbrLightFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\n\n\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#endif\n#include<bumpFragment>\n#if defined(FORCENORMALFORWARD) && defined(NORMAL)\nvec3 faceNormal=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#if defined(TWOSIDEDLIGHTING)\nfaceNormal=gl_FrontFacing ? faceNormal : -faceNormal;\n#endif\nnormalW*=sign(dot(normalW,faceNormal));\n#endif\n#if defined(TWOSIDEDLIGHTING) && defined(NORMAL)\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n\n\nvec3 surfaceAlbedo=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nvec4 albedoTexture=texture2D(albedoSampler,vAlbedoUV+uvOffset);\n#if defined(ALPHAFROMALBEDO) || defined(ALPHATEST)\nalpha*=albedoTexture.a;\n#endif\nsurfaceAlbedo*=toLinearSpace(albedoTexture.rgb);\nsurfaceAlbedo*=vAlbedoInfos.y;\n#endif\n\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nalpha=getLuminance(opacityMap.rgb);\n#else\nalpha*=opacityMap.a;\n#endif\nalpha*=vOpacityInfos.y;\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#if !defined(LINKREFRACTIONTOTRANSPARENCY) && !defined(ALPHAFRESNEL)\n#ifdef ALPHATEST\nif (alpha<=ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nsurfaceAlbedo*=vColor.rgb;\n#endif\n\nvec3 ambientOcclusionColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nvec3 ambientOcclusionColorMap=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#ifdef AMBIENTINGRAYSCALE\nambientOcclusionColorMap=vec3(ambientOcclusionColorMap.r,ambientOcclusionColorMap.r,ambientOcclusionColorMap.r);\n#endif\nambientOcclusionColor=mix(ambientOcclusionColor,ambientOcclusionColorMap,vAmbientInfos.z);\n#endif\n\nfloat microSurface=vReflectivityColor.a;\nvec3 surfaceReflectivityColor=vReflectivityColor.rgb;\n#ifdef METALLICWORKFLOW\nvec2 metallicRoughness=surfaceReflectivityColor.rg;\n#ifdef REFLECTIVITY\nvec4 surfaceMetallicColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\n#ifdef AOSTOREINMETALMAPRED\nvec3 aoStoreInMetalMap=vec3(surfaceMetallicColorMap.r,surfaceMetallicColorMap.r,surfaceMetallicColorMap.r);\nambientOcclusionColor=mix(ambientOcclusionColor,aoStoreInMetalMap,vReflectivityInfos.z);\n#endif\n#ifdef METALLNESSSTOREINMETALMAPBLUE\nmetallicRoughness.r*=surfaceMetallicColorMap.b;\n#else\nmetallicRoughness.r*=surfaceMetallicColorMap.r;\n#endif\n#ifdef ROUGHNESSSTOREINMETALMAPALPHA\nmetallicRoughness.g*=surfaceMetallicColorMap.a;\n#else\n#ifdef ROUGHNESSSTOREINMETALMAPGREEN\nmetallicRoughness.g*=surfaceMetallicColorMap.g;\n#endif\n#endif\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmetallicRoughness.g*=microSurfaceTexel.r;\n#endif\n\nmicroSurface=1.0-metallicRoughness.g;\n\nvec3 baseColor=surfaceAlbedo;\n\n\nconst vec3 DefaultSpecularReflectanceDielectric=vec3(0.04,0.04,0.04);\n\nsurfaceAlbedo=mix(baseColor.rgb*(1.0-DefaultSpecularReflectanceDielectric.r),vec3(0.,0.,0.),metallicRoughness.r);\n\nsurfaceReflectivityColor=mix(DefaultSpecularReflectanceDielectric,baseColor,metallicRoughness.r);\n#else\n#ifdef REFLECTIVITY\nvec4 surfaceReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\nsurfaceReflectivityColor*=toLinearSpace(surfaceReflectivityColorMap.rgb);\nsurfaceReflectivityColor*=vReflectivityInfos.y;\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\nmicroSurface*=surfaceReflectivityColorMap.a;\nmicroSurface*=vReflectivityInfos.z;\n#else\n#ifdef MICROSURFACEAUTOMATIC\nmicroSurface*=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmicroSurface*=microSurfaceTexel.r;\n#endif\n#endif\n#endif\n#endif\n\nmicroSurface=clamp(microSurface,0.,1.);\n\nfloat roughness=1.-microSurface;\n\n#ifdef ALPHAFRESNEL\n#if defined(ALPHATEST) || defined(ALPHABLEND)\n\n\n\nfloat opacityPerceptual=alpha;\n#ifdef LINEARALPHAFRESNEL\nfloat opacity0=opacityPerceptual;\n#else\nfloat opacity0=opacityPerceptual*opacityPerceptual;\n#endif\nfloat opacity90=fresnelGrazingReflectance(opacity0);\nvec3 normalForward=faceforward(normalW,-viewDirectionW,normalW);\n\nalpha=fresnelSchlickEnvironmentGGX(clamp(dot(viewDirectionW,normalForward),0.0,1.0),vec3(opacity0),vec3(opacity90),sqrt(microSurface)).x;\n#ifdef ALPHATEST\nif (alpha<=ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#endif\n\n\nfloat NdotVUnclamped=dot(normalW,viewDirectionW);\nfloat NdotV=clamp(NdotVUnclamped,0.,1.)+0.00001;\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\n\n#ifdef REFRACTION\nvec3 environmentRefraction=vec3(0.,0.,0.);\nvec3 refractionVector=refract(-viewDirectionW,normalW,vRefractionInfos.y);\n#ifdef REFRACTIONMAP_OPPOSITEZ\nrefractionVector.z*=-1.0;\n#endif\n\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nvec3 refractionCoords=refractionVector;\nrefractionCoords=vec3(refractionMatrix*vec4(refractionCoords,0));\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\n#endif\n#ifdef LODINREFRACTIONALPHA\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,1.0);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nrefractionLOD=refractionLOD*vRefractionMicrosurfaceInfos.y+vRefractionMicrosurfaceInfos.z;\n#ifdef LODINREFRACTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticRefractionLOD=UNPACK_LOD(sampleRefraction(refractionSampler,refractionCoords).a);\nfloat requestedRefractionLOD=max(automaticRefractionLOD,refractionLOD);\n#else\nfloat requestedRefractionLOD=refractionLOD;\n#endif\nenvironmentRefraction=sampleRefractionLod(refractionSampler,refractionCoords,requestedRefractionLOD).rgb;\n#else\nfloat lodRefractionNormalized=clamp(refractionLOD/log2(vRefractionMicrosurfaceInfos.x),0.,1.);\nfloat lodRefractionNormalizedDoubled=lodRefractionNormalized*2.0;\nvec3 environmentRefractionMid=sampleRefraction(refractionSampler,refractionCoords).rgb;\nif(lodRefractionNormalizedDoubled<1.0){\nenvironmentRefraction=mix(\nsampleRefraction(refractionSamplerHigh,refractionCoords).rgb,\nenvironmentRefractionMid,\nlodRefractionNormalizedDoubled\n);\n}else{\nenvironmentRefraction=mix(\nenvironmentRefractionMid,\nsampleRefraction(refractionSamplerLow,refractionCoords).rgb,\nlodRefractionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFRACTION\nenvironmentRefraction=toLinearSpace(environmentRefraction.rgb);\n#endif\n\nenvironmentRefraction*=vRefractionInfos.x;\n#endif\n\n#ifdef REFLECTION\nvec3 environmentRadiance=vec3(0.,0.,0.);\nvec3 environmentIrradiance=vec3(0.,0.,0.);\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,1.);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nreflectionLOD=reflectionLOD*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\n#ifdef LODINREFLECTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticReflectionLOD=UNPACK_LOD(sampleReflection(reflectionSampler,reflectionCoords).a);\nfloat requestedReflectionLOD=max(automaticReflectionLOD,reflectionLOD);\n#else\nfloat requestedReflectionLOD=reflectionLOD;\n#endif\nenvironmentRadiance=sampleReflectionLod(reflectionSampler,reflectionCoords,requestedReflectionLOD).rgb;\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD/log2(vReflectionMicrosurfaceInfos.x),0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec3 environmentSpecularMid=sampleReflection(reflectionSampler,reflectionCoords).rgb;\nif(lodReflectionNormalizedDoubled<1.0){\nenvironmentRadiance=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords).rgb,\nenvironmentSpecularMid,\nlodReflectionNormalizedDoubled\n);\n}else{\nenvironmentRadiance=mix(\nenvironmentSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords).rgb,\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFLECTION\nenvironmentRadiance=toLinearSpace(environmentRadiance.rgb);\n#endif\n\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#if defined(NORMAL) && defined(USESPHERICALINVERTEX)\nenvironmentIrradiance=vEnvironmentIrradiance;\n#else\nvec3 irradianceVector=vec3(reflectionMatrix*vec4(normalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nirradianceVector.z*=-1.0;\n#endif\nenvironmentIrradiance=environmentIrradianceJones(irradianceVector);\n#endif\n#endif\n\nenvironmentRadiance*=vReflectionInfos.x;\nenvironmentRadiance*=vReflectionColor.rgb;\nenvironmentIrradiance*=vReflectionColor.rgb;\n#endif\n\n\n\nfloat reflectance=max(max(surfaceReflectivityColor.r,surfaceReflectivityColor.g),surfaceReflectivityColor.b);\nfloat reflectance90=fresnelGrazingReflectance(reflectance);\nvec3 specularEnvironmentR0=surfaceReflectivityColor.rgb;\nvec3 specularEnvironmentR90=vec3(1.0,1.0,1.0)*reflectance90;\n\nvec3 diffuseBase=vec3(0.,0.,0.);\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\n#ifdef LIGHTMAP\nvec3 lightmapColor=toLinearSpace(texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb)*vLightmapInfos.y;\n#endif\nlightingInfo info;\nfloat shadow=1.; \nfloat NdotL=-1.;\n#include<lightFragment>[0..maxSimultaneousLights]\n\n#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)\n\nvec2 brdfSamplerUV=vec2(NdotV,roughness);\n\nvec4 environmentBrdf=texture2D(environmentBrdfSampler,brdfSamplerUV);\nvec3 specularEnvironmentReflectance=specularEnvironmentR0*environmentBrdf.x+environmentBrdf.y;\n#ifdef RADIANCEOCCLUSION\n#ifdef AMBIENTINGRAYSCALE\nfloat ambientMonochrome=ambientOcclusionColor.r;\n#else\nfloat ambientMonochrome=getLuminance(ambientOcclusionColor);\n#endif\nfloat seo=environmentRadianceOcclusion(ambientMonochrome,NdotVUnclamped);\nspecularEnvironmentReflectance*=seo;\n#endif\n#ifdef HORIZONOCCLUSION\n#ifdef BUMP\n#ifdef REFLECTIONMAP_3D\nfloat eho=environmentHorizonOcclusion(reflectionCoords,normalW);\nspecularEnvironmentReflectance*=eho;\n#endif\n#endif\n#endif\n#else\n\nvec3 specularEnvironmentReflectance=fresnelSchlickEnvironmentGGX(NdotV,specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\n#endif\n\n#ifdef REFRACTION\nvec3 refractance=vec3(0.0,0.0,0.0);\nvec3 transmission=vec3(1.0,1.0,1.0);\n#ifdef LINKREFRACTIONTOTRANSPARENCY\n\ntransmission*=(1.0-alpha);\n\n\nvec3 mixedAlbedo=surfaceAlbedo;\nfloat maxChannel=max(max(mixedAlbedo.r,mixedAlbedo.g),mixedAlbedo.b);\nvec3 tint=clamp(maxChannel*mixedAlbedo,0.0,1.0);\n\nsurfaceAlbedo*=alpha;\n\nenvironmentIrradiance*=alpha;\n\nenvironmentRefraction*=tint;\n\nalpha=1.0;\n#endif\n\nvec3 bounceSpecularEnvironmentReflectance=(2.0*specularEnvironmentReflectance)/(1.0+specularEnvironmentReflectance);\nspecularEnvironmentReflectance=mix(bounceSpecularEnvironmentReflectance,specularEnvironmentReflectance,alpha);\n\ntransmission*=1.0-specularEnvironmentReflectance;\n\nrefractance=transmission;\n#endif\n\n\n\n\nsurfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb;\n\nvec3 finalDiffuse=diffuseBase;\nfinalDiffuse.rgb+=vAmbientColor;\nfinalDiffuse*=surfaceAlbedo.rgb;\nfinalDiffuse=max(finalDiffuse,0.0);\n\n#ifdef REFLECTION\nvec3 finalIrradiance=environmentIrradiance;\nfinalIrradiance*=surfaceAlbedo.rgb;\n#endif\n\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase;\nfinalSpecular=max(finalSpecular,0.0);\n\nvec3 finalSpecularScaled=finalSpecular*vLightingIntensity.x*vLightingIntensity.w;\n#endif\n\n#ifdef REFLECTION\nvec3 finalRadiance=environmentRadiance;\nfinalRadiance*=specularEnvironmentReflectance;\n\nvec3 finalRadianceScaled=finalRadiance*vLightingIntensity.z;\n#endif\n\n#ifdef REFRACTION\nvec3 finalRefraction=environmentRefraction;\nfinalRefraction*=refractance;\n#endif\n\nvec3 finalEmissive=vEmissiveColor;\n#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb;\nfinalEmissive*=toLinearSpace(emissiveColorTex.rgb);\nfinalEmissive*=vEmissiveInfos.y;\n#endif\n\n#ifdef ALPHABLEND\nfloat luminanceOverAlpha=0.0;\n#if defined(REFLECTION) && defined(RADIANCEOVERALPHA)\nluminanceOverAlpha+=getLuminance(finalRadianceScaled);\n#endif\n#if defined(SPECULARTERM) && defined(SPECULAROVERALPHA)\nluminanceOverAlpha+=getLuminance(finalSpecularScaled);\n#endif\n#if defined(RADIANCEOVERALPHA) || defined(SPECULAROVERALPHA)\nalpha=clamp(alpha+luminanceOverAlpha*luminanceOverAlpha,0.,1.);\n#endif\n#endif\n\n\n\nvec4 finalColor=vec4(finalDiffuse*ambientOcclusionColor*vLightingIntensity.x +\n#ifdef REFLECTION\nfinalIrradiance*ambientOcclusionColor*vLightingIntensity.z +\n#endif\n#ifdef SPECULARTERM\n\n\nfinalSpecularScaled +\n#endif\n#ifdef REFLECTION\n\n\nfinalRadianceScaled +\n#endif\n#ifdef REFRACTION\nfinalRefraction*vLightingIntensity.z +\n#endif\nfinalEmissive*vLightingIntensity.y,\nalpha);\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\nfinalColor.rgb*=lightmapColor;\n#else\nfinalColor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n\nfinalColor=max(finalColor,0.0);\n#include<logDepthFragment>\n#include<fogFragment>(color,finalColor)\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\nfinalColor.rgb=clamp(finalColor.rgb,0.,30.0);\n#else\n\nfinalColor=applyImageProcessing(finalColor);\n#endif\n#ifdef PREMULTIPLYALPHA\n\nfinalColor.rgb*=finalColor.a;\n#endif\ngl_FragColor=finalColor;\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n}","spritesVertexShader":"\nattribute vec4 position;\nattribute vec4 options;\nattribute vec4 cellInfo;\nattribute vec4 color;\n\nuniform vec2 textureInfos;\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#include<fogVertexDeclaration>\nvoid main(void) { \nvec3 viewPos=(view*vec4(position.xyz,1.0)).xyz; \nvec2 cornerPos;\nfloat angle=position.w;\nvec2 size=vec2(options.x,options.y);\nvec2 offset=options.zw;\nvec2 uvScale=textureInfos.xy;\ncornerPos=vec2(offset.x-0.5,offset.y-0.5)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \n\nvColor=color;\n\nvec2 uvOffset=vec2(abs(offset.x-cellInfo.x),1.0-abs(offset.y-cellInfo.y));\nvUV=(uvOffset+cellInfo.zw)*uvScale;\n\n#ifdef FOG\nvFogDistance=viewPos;\n#endif\n}","spritesPixelShader":"uniform bool alphaTest;\nvarying vec4 vColor;\n\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\nvec4 color=texture2D(diffuseSampler,vUV);\nif (alphaTest) \n{\nif (color.a<0.95)\ndiscard;\n}\ncolor*=vColor;\n#include<fogFragment>\ngl_FragColor=color;\n}","particlesVertexShader":"\nattribute vec3 position;\nattribute vec4 color;\nattribute vec4 options;\nattribute float cellIndex;\n\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec3 particlesInfos; \n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nvarying float fClipDistance;\n#endif\nvoid main(void) { \nvec3 viewPos=(view*vec4(position,1.0)).xyz; \nvec3 cornerPos;\nfloat size=options.y;\nfloat angle=options.x;\nvec2 offset=options.zw;\ncornerPos=vec3(offset.x-0.5,offset.y-0.5,0.)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \nvColor=color;\n#ifdef ANIMATESHEET\nfloat rowOffset=floor(cellIndex/particlesInfos.z);\nfloat columnOffset=cellIndex-rowOffset*particlesInfos.z;\nvec2 uvScale=particlesInfos.xy;\nvec2 uvOffset=vec2(offset.x ,1.0-offset.y);\nvUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;\n#else\nvUV=offset;\n#endif\n\n#ifdef CLIPPLANE\nvec4 worldPos=invView*vec4(viewPos,1.0);\nfClipDistance=dot(worldPos,vClipPlane);\n#endif\n}","particlesPixelShader":"\nvarying vec2 vUV;\nvarying vec4 vColor;\nuniform vec4 textureMask;\nuniform sampler2D diffuseSampler;\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\nvoid main(void) {\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif\nvec4 baseColor=texture2D(diffuseSampler,vUV);\ngl_FragColor=(baseColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor;\n}","gpuRenderParticlesVertexShader":"#version 300 es\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#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nuniform vec2 biasAndScale;\nuniform vec2 depthValues;\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 worldPos=finalWorld*vec4(position,1.0);\ngl_Position=viewProjection*worldPos;\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y))+biasAndScale.x;\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","shadowMapPixelShader":"#ifndef FLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nuniform vec2 biasAndScale;\nuniform vec2 depthValues;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\nfloat depth=vDepthMetric;\n#ifdef ESM\ndepth=clamp(exp(-min(87.,biasAndScale.y*depth)),0.,1.);\n#endif\n#ifdef FLOAT\ngl_FragColor=vec4(depth,1.0,1.0,1.0);\n#else\ngl_FragColor=pack(depth);\n#endif\n}","depthBoxBlurPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nvoid main(void)\n{\nvec4 colorDepth=vec4(0.0);\nfor (int x=-OFFSET; x<=OFFSET; x++)\nfor (int y=-OFFSET; y<=OFFSET; y++)\ncolorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);\ngl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));\n}","proceduralVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvPosition=position;\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","depthVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nuniform vec2 depthValues;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y));\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","depthPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(vDepthMetric,vDepthMetric*vDepthMetric,0.0,1.0);\n}","ssaoPixelShader":"\nuniform sampler2D textureSampler;\nvarying vec2 vUV;\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float radius;\nuniform float area;\nuniform float fallOff;\nuniform float base;\nvec3 normalFromDepth(float depth,vec2 coords)\n{\nvec2 offset1=vec2(0.0,radius);\nvec2 offset2=vec2(radius,0.0);\nfloat depth1=texture2D(textureSampler,coords+offset1).r;\nfloat depth2=texture2D(textureSampler,coords+offset2).r;\nvec3 p1=vec3(offset1,depth1-depth);\nvec3 p2=vec3(offset2,depth2-depth);\nvec3 normal=cross(p1,p2);\nnormal.z=-normal.z;\nreturn normalize(normal);\n}\nvoid main()\n{\nvec3 random=normalize(texture2D(randomSampler,vUV*randTextureTiles).rgb);\nfloat depth=texture2D(textureSampler,vUV).r;\nvec3 position=vec3(vUV,depth);\nvec3 normal=normalFromDepth(depth,vUV);\nfloat radiusDepth=radius/depth;\nfloat occlusion=0.0;\nvec3 ray;\nvec3 hemiRay;\nfloat occlusionDepth;\nfloat difference;\nfor (int i=0; i<SAMPLES; i++)\n{\nray=radiusDepth*reflect(sampleSphere[i],random);\nhemiRay=position+sign(dot(ray,normal))*ray;\nocclusionDepth=texture2D(textureSampler,clamp(hemiRay.xy,vec2(0.001,0.001),vec2(0.999,0.999))).r;\ndifference=depth-occlusionDepth;\nocclusion+=step(fallOff,difference)*(1.0-smoothstep(fallOff,area,difference));\n}\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor.r=result;\ngl_FragColor.g=result;\ngl_FragColor.b=result;\ngl_FragColor.a=1.0;\n}\n#endif\n","ssao2PixelShader":"\nprecision highp float;\nuniform sampler2D textureSampler;\nuniform float near;\nuniform float far;\nuniform float radius;\nvarying vec2 vUV;\nfloat perspectiveDepthToViewZ( const in float invClipZ,const in float near,const in float far ) {\nreturn ( near*far )/( ( far-near )*invClipZ-far );\n}\nfloat viewZToPerspectiveDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( near*far/viewZ+far)/( far-near );\n}\nfloat viewZToOrthographicDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( viewZ+near )/( near-far );\n}\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform sampler2D normalSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float base;\nuniform float xViewport;\nuniform float yViewport;\nuniform float maxZ;\nuniform float minZAspect;\nuniform vec2 texelSize;\nuniform mat4 projection;\nvoid main()\n{\nvec3 random=texture2D(randomSampler,vUV*randTextureTiles).rgb;\nfloat depth=texture2D(textureSampler,vUV).r;\nfloat depthSign=depth/abs(depth);\ndepth=depth*depthSign;\nvec3 normal=texture2D(normalSampler,vUV).rgb; \nfloat occlusion=0.0;\nfloat correctedRadius=min(radius,minZAspect*depth/near);\nvec3 vViewRay=vec3((vUV.x*2.0-1.0)*xViewport,(vUV.y*2.0-1.0)*yViewport,depthSign);\nvec3 origin=vViewRay*depth;\nvec3 rvec=random*2.0-1.0;\nrvec.z=0.0;\nvec3 tangent=normalize(rvec-normal*dot(rvec,normal));\nvec3 bitangent=cross(normal,tangent);\nmat3 tbn=mat3(tangent,bitangent,normal);\nfloat difference;\nif (depth>maxZ) {\ngl_FragColor=vec4(1.0,1.0,1.0,1.0);\nreturn;\n}\nfor (int i=0; i<SAMPLES; ++i) {\n\nvec3 samplePosition=tbn*sampleSphere[i];\nsamplePosition=samplePosition*correctedRadius+origin;\n\nvec4 offset=vec4(samplePosition,1.0);\noffset=projection*offset;\noffset.xyz/=offset.w;\noffset.xy=offset.xy*0.5+0.5;\nif (offset.x<0.0 || offset.y<0.0 || offset.x>1.0 || offset.y>1.0) {\ncontinue;\n}\n\nfloat sampleDepth=abs(texture2D(textureSampler,offset.xy).r);\n\nfloat rangeCheck=abs(depth-sampleDepth)<correctedRadius ? 1.0 : 0.0;\ndifference=depthSign*samplePosition.z-sampleDepth;\n\nocclusion+=(difference>=1e-5 ? 1.0 : 0.0)*rangeCheck;\n}\n\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor=vec4(vec3(result),1.0);\n}\n#endif\n#ifdef BILATERAL_BLUR\nuniform sampler2D depthSampler;\nuniform float outSize;\nuniform float samplerOffsets[SAMPLES];\nvec4 blur9(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.3846153846)*direction;\nvec2 off2=vec2(3.2307692308)*direction;\ncolor+=texture2D(image,uv)*0.2270270270;\ncolor+=texture2D(image,uv+(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv-(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv+(off2/resolution))*0.0702702703;\ncolor+=texture2D(image,uv-(off2/resolution))*0.0702702703;\nreturn color;\n}\nvec4 blur13(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\ncolor+=texture2D(image,uv)*0.1964825501511404;\ncolor+=texture2D(image,uv+(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv-(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv+(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv-(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv+(off3/resolution))*0.010381362401148057;\ncolor+=texture2D(image,uv-(off3/resolution))*0.010381362401148057;\nreturn color;\n}\nvec4 blur13Bilateral(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\nfloat compareDepth=abs(texture2D(depthSampler,uv).r);\nfloat sampleDepth;\nfloat weight;\nfloat weightSum=30.0;\ncolor+=texture2D(image,uv)*30.0;\nsampleDepth=abs(texture2D(depthSampler,uv+(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off3/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off3/resolution))*weight;\nreturn color/weightSum;\n}\nvoid main()\n{\n#if EXPENSIVE\nfloat compareDepth=abs(texture2D(depthSampler,vUV).r);\nfloat texelsize=1.0/outSize;\nfloat result=0.0;\nfloat weightSum=0.0;\nfor (int i=0; i<SAMPLES; ++i)\n{\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\nvec2 sampleOffset=vec2(texelsize*samplerOffsets[i],0.0);\n#else\nvec2 direction=vec2(0.0,1.0);\nvec2 sampleOffset=vec2(0.0,texelsize*samplerOffsets[i]);\n#endif\nvec2 samplePos=vUV+sampleOffset;\nfloat sampleDepth=abs(texture2D(depthSampler,samplePos).r);\nfloat weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30000.0);\nresult+=texture2D(textureSampler,samplePos).r*weight;\nweightSum+=weight;\n}\nresult/=weightSum;\ngl_FragColor.rgb=vec3(result);\ngl_FragColor.a=1.0;\n#else\nvec4 color;\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#else\nvec2 direction=vec2(0.0,1.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#endif\ngl_FragColor.rgb=vec3(color.r);\ngl_FragColor.a=1.0;\n#endif\n}\n#endif\n","ssaoCombinePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D originalColor;\nvarying vec2 vUV;\nvoid main(void) {\nvec4 ssaoColor=texture2D(textureSampler,vUV);\nvec4 sceneColor=texture2D(originalColor,vUV);\ngl_FragColor=sceneColor*ssaoColor;\n}\n","chromaticAberrationPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float chromatic_aberration;\nuniform float radialIntensity;\nuniform vec2 direction;\nuniform vec2 centerPosition;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\nvoid main(void)\n{\nvec2 centered_screen_pos=vec2(vUV.x-centerPosition.x,vUV.y-centerPosition.y);\nvec2 directionOfEffect=direction;\nif(directionOfEffect.x == 0. && directionOfEffect.y == 0.){\ndirectionOfEffect=normalize(centered_screen_pos);\n}\nfloat radius2=centered_screen_pos.x*centered_screen_pos.x\n+centered_screen_pos.y*centered_screen_pos.y;\nfloat radius=sqrt(radius2);\nvec4 original=texture2D(textureSampler,vUV);\n\nvec3 ref_indices=vec3(-0.3,0.0,0.3);\nfloat ref_shiftX=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.x/screen_width;\nfloat ref_shiftY=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.y/screen_height;\n\nvec2 ref_coords_r=vec2(vUV.x+ref_indices.r*ref_shiftX,vUV.y+ref_indices.r*ref_shiftY*0.5);\nvec2 ref_coords_g=vec2(vUV.x+ref_indices.g*ref_shiftX,vUV.y+ref_indices.g*ref_shiftY*0.5);\nvec2 ref_coords_b=vec2(vUV.x+ref_indices.b*ref_shiftX,vUV.y+ref_indices.b*ref_shiftY*0.5);\noriginal.r=texture2D(textureSampler,ref_coords_r).r;\noriginal.g=texture2D(textureSampler,ref_coords_g).g;\noriginal.b=texture2D(textureSampler,ref_coords_b).b;\ngl_FragColor=original;\n}","lensHighlightsPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float gain;\nuniform float threshold;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\n\nvec4 highlightColor(vec4 color) {\nvec4 highlight=color;\nfloat luminance=dot(highlight.rgb,vec3(0.2125,0.7154,0.0721));\nfloat lum_threshold;\nif (threshold>1.0) { lum_threshold=0.94+0.01*threshold; }\nelse { lum_threshold=0.5+0.44*threshold; }\nluminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);\nhighlight*=luminance*gain;\nhighlight.a=1.0;\nreturn highlight;\n}\nvoid main(void)\n{\nvec4 original=texture2D(textureSampler,vUV);\n\nif (gain == -1.0) {\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nreturn;\n}\nfloat w=2.0/screen_width;\nfloat h=2.0/screen_height;\nfloat weight=1.0;\n\nvec4 blurred=vec4(0.0,0.0,0.0,0.0);\n#ifdef PENTAGON\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.00*w,-1.19*h)));\n#else\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.85*w,0.36*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h)));\n#endif\nblurred/=39.0;\ngl_FragColor=blurred;\n\n}","depthOfFieldPixelShader":"\n\n\n\n\nuniform sampler2D textureSampler;\nuniform sampler2D highlightsSampler;\nuniform sampler2D depthSampler;\nuniform sampler2D grainSampler;\n\nuniform float grain_amount;\nuniform bool blur_noise;\nuniform float screen_width;\nuniform float screen_height;\nuniform float distortion;\nuniform bool dof_enabled;\n\nuniform float screen_distance; \nuniform float aperture;\nuniform float darken;\nuniform float edge_blur;\nuniform bool highlights;\n\nuniform float near;\nuniform float far;\n\nvarying vec2 vUV;\n\n#define PI 3.14159265\n#define TWOPI 6.28318530\n#define inverse_focal_length 0.1 \n\nvec2 centered_screen_pos;\nvec2 distorted_coords;\nfloat radius2;\nfloat radius;\n\nvec2 rand(vec2 co)\n{\nfloat noise1=(fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5453));\nfloat noise2=(fract(sin(dot(co,vec2(12.9898,78.233)*2.0))*43758.5453));\nreturn clamp(vec2(noise1,noise2),0.0,1.0);\n}\n\nvec2 getDistortedCoords(vec2 coords) {\nif (distortion == 0.0) { return coords; }\nvec2 direction=1.0*normalize(centered_screen_pos);\nvec2 dist_coords=vec2(0.5,0.5);\ndist_coords.x=0.5+direction.x*radius2*1.0;\ndist_coords.y=0.5+direction.y*radius2*1.0;\nfloat dist_amount=clamp(distortion*0.23,0.0,1.0);\ndist_coords=mix(coords,dist_coords,dist_amount);\nreturn dist_coords;\n}\n\nfloat sampleScreen(inout vec4 color,const in vec2 offset,const in float weight) {\n\nvec2 coords=distorted_coords;\nfloat angle=rand(coords*100.0).x*TWOPI;\ncoords+=vec2(offset.x*cos(angle)-offset.y*sin(angle),offset.x*sin(angle)+offset.y*cos(angle));\ncolor+=texture2D(textureSampler,coords)*weight;\nreturn weight;\n}\n\nfloat getBlurLevel(float size) {\nreturn min(3.0,ceil(size/1.0));\n}\n\nvec4 getBlurColor(float size) {\nvec4 col=texture2D(textureSampler,distorted_coords);\nif (size == 0.0) { return col; }\n\n\nfloat blur_level=getBlurLevel(size);\nfloat w=(size/screen_width);\nfloat h=(size/screen_height);\nfloat total_weight=1.0;\nvec2 sample_coords;\ntotal_weight+=sampleScreen(col,vec2(-0.50*w,0.24*h),0.93);\ntotal_weight+=sampleScreen(col,vec2(0.30*w,-0.75*h),0.90);\ntotal_weight+=sampleScreen(col,vec2(0.36*w,0.96*h),0.87);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,-0.55*h),0.85);\ntotal_weight+=sampleScreen(col,vec2(1.33*w,-0.37*h),0.83);\ntotal_weight+=sampleScreen(col,vec2(-0.82*w,1.31*h),0.80);\ntotal_weight+=sampleScreen(col,vec2(-0.31*w,-1.67*h),0.78);\ntotal_weight+=sampleScreen(col,vec2(1.47*w,1.11*h),0.76);\ntotal_weight+=sampleScreen(col,vec2(-1.97*w,0.19*h),0.74);\ntotal_weight+=sampleScreen(col,vec2(1.42*w,-1.57*h),0.72);\nif (blur_level>1.0) {\ntotal_weight+=sampleScreen(col,vec2(0.01*w,2.25*h),0.70);\ntotal_weight+=sampleScreen(col,vec2(-1.62*w,-1.74*h),0.67);\ntotal_weight+=sampleScreen(col,vec2(2.49*w,0.20*h),0.65);\ntotal_weight+=sampleScreen(col,vec2(-2.07*w,1.61*h),0.63);\ntotal_weight+=sampleScreen(col,vec2(0.46*w,-2.70*h),0.61);\ntotal_weight+=sampleScreen(col,vec2(1.55*w,2.40*h),0.59);\ntotal_weight+=sampleScreen(col,vec2(-2.88*w,-0.75*h),0.56);\ntotal_weight+=sampleScreen(col,vec2(2.73*w,-1.44*h),0.54);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,3.02*h),0.52);\ntotal_weight+=sampleScreen(col,vec2(-1.28*w,-3.05*h),0.49);\n}\nif (blur_level>2.0) {\ntotal_weight+=sampleScreen(col,vec2(3.11*w,1.43*h),0.46);\ntotal_weight+=sampleScreen(col,vec2(-3.36*w,1.08*h),0.44);\ntotal_weight+=sampleScreen(col,vec2(1.80*w,-3.16*h),0.41);\ntotal_weight+=sampleScreen(col,vec2(0.83*w,3.65*h),0.38);\ntotal_weight+=sampleScreen(col,vec2(-3.16*w,-2.19*h),0.34);\ntotal_weight+=sampleScreen(col,vec2(3.92*w,-0.53*h),0.31);\ntotal_weight+=sampleScreen(col,vec2(-2.59*w,3.12*h),0.26);\ntotal_weight+=sampleScreen(col,vec2(-0.20*w,-4.15*h),0.22);\ntotal_weight+=sampleScreen(col,vec2(3.02*w,3.00*h),0.15);\n}\ncol/=total_weight; \n\nif (darken>0.0) {\ncol.rgb*=clamp(0.3,1.0,1.05-size*0.5*darken);\n}\n\n\n\n\nreturn col;\n}\nvoid main(void)\n{\n\ncentered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nradius2=centered_screen_pos.x*centered_screen_pos.x+centered_screen_pos.y*centered_screen_pos.y;\nradius=sqrt(radius2);\ndistorted_coords=getDistortedCoords(vUV); \nvec2 texels_coords=vec2(vUV.x*screen_width,vUV.y*screen_height); \nfloat depth=texture2D(depthSampler,distorted_coords).r; \nfloat distance=near+(far-near)*depth; \nvec4 color=texture2D(textureSampler,vUV); \n\n\nfloat coc=abs(aperture*(screen_distance*(inverse_focal_length-1.0/distance)-1.0));\n\nif (dof_enabled == false || coc<0.07) { coc=0.0; }\n\nfloat edge_blur_amount=0.0;\nif (edge_blur>0.0) {\nedge_blur_amount=clamp((radius*2.0-1.0+0.15*edge_blur)*1.5,0.0,1.0)*1.3;\n}\n\nfloat blur_amount=max(edge_blur_amount,coc);\n\nif (blur_amount == 0.0) {\ngl_FragColor=texture2D(textureSampler,distorted_coords);\n}\nelse {\n\ngl_FragColor=getBlurColor(blur_amount*1.7);\n\nif (highlights) {\ngl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;\n}\nif (blur_noise) {\n\nvec2 noise=rand(distorted_coords)*0.01*blur_amount;\nvec2 blurred_coord=vec2(distorted_coords.x+noise.x,distorted_coords.y+noise.y);\ngl_FragColor=0.04*texture2D(textureSampler,blurred_coord)+0.96*gl_FragColor;\n}\n}\n\nif (grain_amount>0.0) {\nvec4 grain_color=texture2D(grainSampler,texels_coords*0.003);\ngl_FragColor.rgb+=(-0.5+grain_color.rgb)*0.30*grain_amount;\n}\n}\n","standardPixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(PASS_POST_PROCESS)\nvoid main(void)\n{\nvec4 color=texture2D(textureSampler,vUV);\ngl_FragColor=color;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\naverage/=16.0;\ngl_FragColor=average;\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\naverage*=0.25;\nfloat luminance=length(average.rgb);\nif (luminance<brightThreshold) {\naverage=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor=average;\n}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nuniform sampler2D lensSampler;\nuniform float exposure;\nvoid main(void)\n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\ncolour*=exposure;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\ncolour+=colour*texture2D(lensSampler,vUV).rgb;\nvec4 finalColor=vec4(colour.rgb,1.0)+texture2D(otherSampler,vUV);\ngl_FragColor=finalColor;\n}\n#endif\n#if defined(VLS)\n#define PI 3.1415926535897932384626433832795\nuniform mat4 shadowViewProjection;\nuniform mat4 lightWorld;\nuniform vec3 cameraPosition;\nuniform vec3 sunDirection;\nuniform vec3 sunColor;\nuniform vec2 depthValues;\nuniform float scatteringCoefficient;\nuniform float scatteringPower;\nuniform sampler2D shadowMapSampler;\nuniform sampler2D positionSampler;\nfloat computeScattering(float lightDotView)\n{\nfloat result=1.0-scatteringCoefficient*scatteringCoefficient;\nresult/=(4.0*PI*pow(1.0+scatteringCoefficient*scatteringCoefficient-(2.0*scatteringCoefficient)*lightDotView,1.5));\nreturn result;\n}\nvoid main(void)\n{\n\nvec3 worldPos=texture2D(positionSampler,vUV).rgb;\nvec3 startPosition=cameraPosition;\nvec3 rayVector=worldPos-startPosition;\nfloat rayLength=length(rayVector);\nvec3 rayDirection=rayVector/rayLength;\nfloat stepLength=rayLength/NB_STEPS;\nvec3 stepL=rayDirection*stepLength;\nvec3 currentPosition=startPosition;\nvec3 accumFog=vec3(0.0);\nfor (int i=0; i<int(NB_STEPS); i++)\n{\nvec4 worldInShadowCameraSpace=shadowViewProjection*vec4(currentPosition,1.0);\nfloat depthMetric=(worldInShadowCameraSpace.z+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depthMetric,0.0,1.0);\nworldInShadowCameraSpace.xyz/=worldInShadowCameraSpace.w;\nworldInShadowCameraSpace.xyz=0.5*worldInShadowCameraSpace.xyz+vec3(0.5);\nfloat shadowMapValue=texture2D(shadowMapSampler,worldInShadowCameraSpace.xy).r;\nif (shadowMapValue>shadowPixelDepth)\naccumFog+=sunColor*computeScattering(dot(rayDirection,sunDirection));\ncurrentPosition+=stepL;\n}\naccumFog/=NB_STEPS;\nvec3 color=accumFog*scatteringPower;\ngl_FragColor=vec4(color*exp(color) ,1.0);\n}\n#endif\n#if defined(VLSMERGE)\nuniform sampler2D originalSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(originalSampler,vUV)+texture2D(textureSampler,vUV);\n}\n#endif\n#if defined(LUMINANCE)\nuniform vec2 lumOffsets[4];\nvoid main()\n{\nfloat average=0.0;\nvec4 color=vec4(0.0);\nfloat maximum=-1e20;\nvec3 weight=vec3(0.299,0.587,0.114);\nfor (int i=0; i<4; i++)\n{\ncolor=texture2D(textureSampler,vUV+ lumOffsets[i]);\n\nfloat GreyValue=dot(color.rgb,vec3(0.33,0.33,0.33));\n\n#ifdef WEIGHTED_AVERAGE\nfloat GreyValue=dot(color.rgb,weight);\n#endif\n#ifdef BRIGHTNESS\nfloat GreyValue=max(color.r,max(color.g,color.b));\n#endif\n#ifdef HSL_COMPONENT\nfloat GreyValue=0.5*(max(color.r,max(color.g,color.b))+min(color.r,min(color.g,color.b)));\n#endif\n#ifdef MAGNITUDE\nfloat GreyValue=length(color.rgb);\n#endif\nmaximum=max(maximum,GreyValue);\naverage+=(0.25*log(1e-5+GreyValue));\n}\naverage=exp(average);\ngl_FragColor=vec4(average,maximum,0.0,1.0);\n}\n#endif\n#if defined(LUMINANCE_DOWN_SAMPLE)\nuniform vec2 dsOffsets[9];\nuniform float halfDestPixelSize;\n#ifdef FINAL_DOWN_SAMPLER\nvec4 pack(float value) {\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(value*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvoid main()\n{\nvec4 color=vec4(0.0);\nfloat average=0.0;\nfor (int i=0; i<9; i++)\n{\ncolor=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);\naverage+=color.r;\n}\naverage/=9.0;\n#ifdef FINAL_DOWN_SAMPLER\ngl_FragColor=pack(average);\n#else\ngl_FragColor=vec4(average,average,0.0,1.0);\n#endif\n}\n#endif\n#if defined(HDR)\nuniform sampler2D textureAdderSampler;\nuniform float averageLuminance;\nvoid main()\n{\nvec4 color=texture2D(textureAdderSampler,vUV);\nvec4 adjustedColor=color/averageLuminance;\ncolor=adjustedColor;\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(LENS_FLARE)\n#define GHOSTS 3\nuniform sampler2D lensColorSampler;\nuniform float strength;\nuniform float ghostDispersal;\nuniform float haloWidth;\nuniform vec2 resolution;\nuniform float distortionStrength;\nfloat hash(vec2 p)\n{\nfloat h=dot(p,vec2(127.1,311.7));\nreturn -1.0+2.0*fract(sin(h)*43758.5453123);\n}\nfloat noise(in vec2 p)\n{\nvec2 i=floor(p);\nvec2 f=fract(p);\nvec2 u=f*f*(3.0-2.0*f);\nreturn mix(mix(hash(i+vec2(0.0,0.0)),\nhash(i+vec2(1.0,0.0)),u.x),\nmix(hash(i+vec2(0.0,1.0)),\nhash(i+vec2(1.0,1.0)),u.x),u.y);\n}\nfloat fbm(vec2 p)\n{\nfloat f=0.0;\nf+=0.5000*noise(p); p*=2.02;\nf+=0.2500*noise(p); p*=2.03;\nf+=0.1250*noise(p); p*=2.01;\nf+=0.0625*noise(p); p*=2.04;\nf/=0.9375;\nreturn f;\n}\nvec3 pattern(vec2 uv)\n{\nvec2 p=-1.0+2.0*uv;\nfloat p2=dot(p,p);\nfloat f=fbm(vec2(15.0*p2))/2.0;\nfloat r=0.2+0.6*sin(12.5*length(uv-vec2(0.5)));\nfloat g=0.2+0.6*sin(20.5*length(uv-vec2(0.5)));\nfloat b=0.2+0.6*sin(17.2*length(uv-vec2(0.5)));\nreturn (1.0-f)*vec3(r,g,b);\n}\nfloat luminance(vec3 color)\n{\nreturn dot(color.rgb,vec3(0.2126,0.7152,0.0722));\n}\nvec4 textureDistorted(sampler2D tex,vec2 texcoord,vec2 direction,vec3 distortion)\n{\nreturn vec4(\ntexture2D(tex,texcoord+direction*distortion.r).r,\ntexture2D(tex,texcoord+direction*distortion.g).g,\ntexture2D(tex,texcoord+direction*distortion.b).b,\n1.0\n);\n}\nvoid main(void)\n{\nvec2 uv=-vUV+vec2(1.0);\nvec2 ghostDir=(vec2(0.5)-uv)*ghostDispersal;\nvec2 texelSize=1.0/resolution;\nvec3 distortion=vec3(-texelSize.x*distortionStrength,0.0,texelSize.x*distortionStrength);\nvec4 result=vec4(0.0);\nfloat ghostIndice=1.0;\nfor (int i=0; i<GHOSTS; ++i)\n{\nvec2 offset=fract(uv+ghostDir*ghostIndice);\nfloat weight=length(vec2(0.5)-offset)/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,offset,normalize(ghostDir),distortion)*weight*strength;\nghostIndice+=1.0;\n}\nvec2 haloVec=normalize(ghostDir)*haloWidth;\nfloat weight=length(vec2(0.5)-fract(uv+haloVec))/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,fract(uv+haloVec),normalize(ghostDir),distortion)*weight*strength;\nresult*=texture2D(lensColorSampler,vec2(length(vec2(0.5)-uv)/length(vec2(0.5))));\ngl_FragColor=result;\n}\n#endif\n#if defined(LENS_FLARE_COMPOSE)\nuniform sampler2D otherSampler;\nuniform sampler2D lensDirtSampler;\nuniform sampler2D lensStarSampler;\nuniform mat4 lensStarMatrix;\nvoid main(void)\n{\nvec2 lensFlareCoords=(lensStarMatrix*vec4(vUV,1.0,1.0)).xy;\nvec4 lensMod=texture2D(lensDirtSampler,vUV);\nlensMod+=texture2D(lensStarSampler,vUV);\nvec4 result=texture2D(textureSampler,vUV)*lensMod;\ngl_FragColor=texture2D(otherSampler,vUV)+result;\n}\n#endif\n#if defined(DEPTH_OF_FIELD)\nuniform sampler2D otherSampler;\nuniform sampler2D depthSampler;\nuniform float distance;\nvoid main(void)\n{\nvec4 sharp=texture2D(otherSampler,vUV);\nvec4 blur=texture2D(textureSampler,vUV);\nfloat dist=clamp(texture2D(depthSampler,vUV).r*distance,0.0,1.0);\nfloat factor=0.0;\nif (dist<0.05)\nfactor=1.0;\nelse if (dist<0.1)\nfactor=20.0*(0.1-dist);\nelse if (dist<0.5)\nfactor=0.0;\nelse\nfactor=2.0*(dist-0.5);\nfactor=clamp(factor,0.0,0.90);\ngl_FragColor=mix(sharp,blur,factor);\n}\n#endif\n#if defined(MOTION_BLUR)\nuniform mat4 inverseViewProjection;\nuniform mat4 prevViewProjection;\nuniform vec2 screenSize;\nuniform float motionScale;\nuniform float motionStrength;\nuniform sampler2D depthSampler;\nvoid main(void)\n{\nvec2 texelSize=1.0/screenSize;\nfloat depth=texture2D(depthSampler,vUV).r;\nvec4 cpos=vec4(vUV*2.0-1.0,depth,1.0);\ncpos=cpos*inverseViewProjection;\nvec4 ppos=cpos*prevViewProjection;\nppos.xyz/=ppos.w;\nppos.xy=ppos.xy*0.5+0.5;\nvec2 velocity=(ppos.xy-vUV)*motionScale*motionStrength;\nfloat speed=length(velocity/texelSize);\nint nSamples=int(clamp(speed,1.0,MAX_MOTION_SAMPLES));\nvec4 result=texture2D(textureSampler,vUV);\nfor (int i=1; i<int(MAX_MOTION_SAMPLES); ++i) {\nif (i>=nSamples)\nbreak;\nvec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5);\nresult+=texture2D(textureSampler,offset1);\n}\ngl_FragColor=result/float(nSamples);\n}\n#endif\n","fxaaVertexShader":"\nattribute vec2 position;\nuniform vec2 texelSize;\n\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd);\nsampleCoordS=vUV+vec2( 0.0,1.0)*texelSize;\nsampleCoordE=vUV+vec2( 1.0,0.0)*texelSize;\nsampleCoordN=vUV+vec2( 0.0,-1.0)*texelSize;\nsampleCoordW=vUV+vec2(-1.0,0.0)*texelSize;\nsampleCoordNW=vUV+vec2(-1.0,-1.0)*texelSize;\nsampleCoordSE=vUV+vec2( 1.0,1.0)*texelSize;\nsampleCoordNE=vUV+vec2( 1.0,-1.0)*texelSize;\nsampleCoordSW=vUV+vec2(-1.0,1.0)*texelSize;\ngl_Position=vec4(position,0.0,1.0);\n}","fxaaPixelShader":"uniform sampler2D textureSampler;\nuniform vec2 texelSize;\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst float fxaaQualitySubpix=1.0;\nconst float fxaaQualityEdgeThreshold=0.166;\nconst float fxaaQualityEdgeThresholdMin=0.0833;\nconst vec3 kLumaCoefficients=vec3(0.2126,0.7152,0.0722);\n#define FxaaLuma(rgba) dot(rgba.rgb,kLumaCoefficients)\nvoid main(){\nvec2 posM;\nposM.x=vUV.x;\nposM.y=vUV.y;\nvec4 rgbyM=texture2D(textureSampler,vUV,0.0);\nfloat lumaM=FxaaLuma(rgbyM);\nfloat lumaS=FxaaLuma(texture2D(textureSampler,sampleCoordS,0.0));\nfloat lumaE=FxaaLuma(texture2D(textureSampler,sampleCoordE,0.0));\nfloat lumaN=FxaaLuma(texture2D(textureSampler,sampleCoordN,0.0));\nfloat lumaW=FxaaLuma(texture2D(textureSampler,sampleCoordW,0.0));\nfloat maxSM=max(lumaS,lumaM);\nfloat minSM=min(lumaS,lumaM);\nfloat maxESM=max(lumaE,maxSM);\nfloat minESM=min(lumaE,minSM);\nfloat maxWN=max(lumaN,lumaW);\nfloat minWN=min(lumaN,lumaW);\nfloat rangeMax=max(maxWN,maxESM);\nfloat rangeMin=min(minWN,minESM);\nfloat rangeMaxScaled=rangeMax*fxaaQualityEdgeThreshold;\nfloat range=rangeMax-rangeMin;\nfloat rangeMaxClamped=max(fxaaQualityEdgeThresholdMin,rangeMaxScaled);\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\nreturn;\n}\nfloat lumaNW=FxaaLuma(texture2D(textureSampler,sampleCoordNW,0.0));\nfloat lumaSE=FxaaLuma(texture2D(textureSampler,sampleCoordSE,0.0));\nfloat lumaNE=FxaaLuma(texture2D(textureSampler,sampleCoordNE,0.0));\nfloat lumaSW=FxaaLuma(texture2D(textureSampler,sampleCoordSW,0.0));\nfloat lumaNS=lumaN+lumaS;\nfloat lumaWE=lumaW+lumaE;\nfloat subpixRcpRange=1.0/range;\nfloat subpixNSWE=lumaNS+lumaWE;\nfloat edgeHorz1=(-2.0*lumaM)+lumaNS;\nfloat edgeVert1=(-2.0*lumaM)+lumaWE;\nfloat lumaNESE=lumaNE+lumaSE;\nfloat lumaNWNE=lumaNW+lumaNE;\nfloat edgeHorz2=(-2.0*lumaE)+lumaNESE;\nfloat edgeVert2=(-2.0*lumaN)+lumaNWNE;\nfloat lumaNWSW=lumaNW+lumaSW;\nfloat lumaSWSE=lumaSW+lumaSE;\nfloat edgeHorz4=(abs(edgeHorz1)*2.0)+abs(edgeHorz2);\nfloat edgeVert4=(abs(edgeVert1)*2.0)+abs(edgeVert2);\nfloat edgeHorz3=(-2.0*lumaW)+lumaNWSW;\nfloat edgeVert3=(-2.0*lumaS)+lumaSWSE;\nfloat edgeHorz=abs(edgeHorz3)+edgeHorz4;\nfloat edgeVert=abs(edgeVert3)+edgeVert4;\nfloat subpixNWSWNESE=lumaNWSW+lumaNESE;\nfloat lengthSign=texelSize.x;\nbool horzSpan=edgeHorz>=edgeVert;\nfloat subpixA=subpixNSWE*2.0+subpixNWSWNESE;\nif (!horzSpan)\n{\nlumaN=lumaW;\n}\nif (!horzSpan) \n{\nlumaS=lumaE;\n}\nif (horzSpan) \n{\nlengthSign=texelSize.y;\n}\nfloat subpixB=(subpixA*(1.0/12.0))-lumaM;\nfloat gradientN=lumaN-lumaM;\nfloat gradientS=lumaS-lumaM;\nfloat lumaNN=lumaN+lumaM;\nfloat lumaSS=lumaS+lumaM;\nbool pairN=abs(gradientN)>=abs(gradientS);\nfloat gradient=max(abs(gradientN),abs(gradientS));\nif (pairN)\n{\nlengthSign=-lengthSign;\n}\nfloat subpixC=clamp(abs(subpixB)*subpixRcpRange,0.0,1.0);\nvec2 posB;\nposB.x=posM.x;\nposB.y=posM.y;\nvec2 offNP;\noffNP.x=(!horzSpan) ? 0.0 : texelSize.x;\noffNP.y=(horzSpan) ? 0.0 : texelSize.y;\nif (!horzSpan) \n{\nposB.x+=lengthSign*0.5;\n}\nif (horzSpan)\n{\nposB.y+=lengthSign*0.5;\n}\nvec2 posN;\nposN.x=posB.x-offNP.x*1.5;\nposN.y=posB.y-offNP.y*1.5;\nvec2 posP;\nposP.x=posB.x+offNP.x*1.5;\nposP.y=posB.y+offNP.y*1.5;\nfloat subpixD=((-2.0)*subpixC)+3.0;\nfloat lumaEndN=FxaaLuma(texture2D(textureSampler,posN,0.0));\nfloat subpixE=subpixC*subpixC;\nfloat lumaEndP=FxaaLuma(texture2D(textureSampler,posP,0.0));\nif (!pairN) \n{\nlumaNN=lumaSS;\n}\nfloat gradientScaled=gradient*1.0/4.0;\nfloat lumaMM=lumaM-lumaNN*0.5;\nfloat subpixF=subpixD*subpixE;\nbool lumaMLTZero=lumaMM<0.0;\nlumaEndN-=lumaNN*0.5;\nlumaEndP-=lumaNN*0.5;\nbool doneN=abs(lumaEndN)>=gradientScaled;\nbool doneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) \n{\nposN.x-=offNP.x*3.0;\n}\nif (!doneN) \n{\nposN.y-=offNP.y*3.0;\n}\nbool doneNP=(!doneN) || (!doneP);\nif (!doneP) \n{\nposP.x+=offNP.x*3.0;\n}\nif (!doneP)\n{\nposP.y+=offNP.y*3.0;\n}\nif (doneNP)\n{\nif (!doneN) lumaEndN=FxaaLuma(texture2D(textureSampler,posN.xy,0.0));\nif (!doneP) lumaEndP=FxaaLuma(texture2D(textureSampler,posP.xy,0.0));\nif (!doneN) lumaEndN=lumaEndN-lumaNN*0.5;\nif (!doneP) lumaEndP=lumaEndP-lumaNN*0.5;\ndoneN=abs(lumaEndN)>=gradientScaled;\ndoneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) posN.x-=offNP.x*12.0;\nif (!doneN) posN.y-=offNP.y*12.0;\ndoneNP=(!doneN) || (!doneP);\nif (!doneP) posP.x+=offNP.x*12.0;\nif (!doneP) posP.y+=offNP.y*12.0;\n}\nfloat dstN=posM.x-posN.x;\nfloat dstP=posP.x-posM.x;\nif (!horzSpan)\n{\ndstN=posM.y-posN.y;\n}\nif (!horzSpan) \n{\ndstP=posP.y-posM.y;\n}\nbool goodSpanN=(lumaEndN<0.0) != lumaMLTZero;\nfloat spanLength=(dstP+dstN);\nbool goodSpanP=(lumaEndP<0.0) != lumaMLTZero;\nfloat spanLengthRcp=1.0/spanLength;\nbool directionN=dstN<dstP;\nfloat dst=min(dstN,dstP);\nbool goodSpan=directionN ? goodSpanN : goodSpanP;\nfloat subpixG=subpixF*subpixF;\nfloat pixelOffset=(dst*(-spanLengthRcp))+0.5;\nfloat subpixH=subpixG*fxaaQualitySubpix;\nfloat pixelOffsetGood=goodSpan ? pixelOffset : 0.0;\nfloat pixelOffsetSubpix=max(pixelOffsetGood,subpixH);\nif (!horzSpan)\n{\nposM.x+=pixelOffsetSubpix*lengthSign;\n}\nif (horzSpan)\n{\nposM.y+=pixelOffsetSubpix*lengthSign;\n}\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n}","sharpenPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform vec2 sharpnessAmounts;\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 color=texture2D(textureSampler,vUV);\nvec4 edgeDetection=texture2D(textureSampler,vUV+onePixel*vec2(0,-1)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1)) -\ncolor*4.0;\ngl_FragColor=max(vec4(color.rgb*sharpnessAmounts.y,color.a)-(sharpnessAmounts.x*vec4(edgeDetection.rgb,0)),0.);\n}","kernelBlurVertexShader":"\nattribute vec2 position;\n\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nsampleCenter=(position*madd+madd);\n#include<kernelBlurVertex>[0..varyingCount]\ngl_Position=vec4(position,0.0,1.0);\n}","kernelBlurPixelShader":"\nuniform sampler2D textureSampler;\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#ifdef DOF\nuniform sampler2D circleOfConfusionSampler;\nuniform vec2 cameraMinMaxZ;\nfloat sampleDistance(const in vec2 offset) {\nfloat depth=texture2D(circleOfConfusionSampler,offset).g; \nreturn cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth; \n}\n#endif\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\n#ifdef PACKEDFLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nvoid main(void)\n{\n#ifdef DOF\nfloat sumOfWeights=0.0; \nfloat sampleDepth=0.0;\nfloat factor=0.0;\nfloat centerSampleDepth=sampleDistance(sampleCenter);\n#endif\nfloat computedWeight=0.0;\n#ifdef PACKEDFLOAT \nfloat blend=0.;\n#else\nvec4 blend=vec4(0.);\n#endif\n#include<kernelBlurFragment>[0..varyingCount]\n#include<kernelBlurFragment2>[0..depCount]\n#ifdef PACKEDFLOAT\ngl_FragColor=pack(blend);\n#else\ngl_FragColor=blend;\n#endif\n#ifdef DOF\n\nif(sumOfWeights == 0.0){\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor/=sumOfWeights;\n#endif\n}","depthOfFieldMergePixelShader":"\nuniform sampler2D textureSampler;\nuniform sampler2D originalSampler;\nuniform sampler2D circleOfConfusionSampler;\n#if BLUR_LEVEL>0\nuniform sampler2D blurStep1;\n#endif\n#if BLUR_LEVEL>1\nuniform sampler2D blurStep2;\n#endif\n\nvarying vec2 vUV;\nvoid main(void)\n{\nfloat coc=texture2D(circleOfConfusionSampler,vUV).r;\nvec4 original=texture2D(originalSampler,vUV);\n#if BLUR_LEVEL == 0\nvec4 blurred1=texture2D(textureSampler,vUV);\ngl_FragColor=mix(original,blurred1,coc);\n#endif\n#if BLUR_LEVEL == 1\nvec4 blurred1=texture2D(blurStep1,vUV);\nvec4 blurred2=texture2D(textureSampler,vUV); \nif(coc<0.5){\ngl_FragColor=mix(original,blurred1,coc/0.5);\n}else{\ngl_FragColor=mix(blurred1,blurred2,(coc-0.5)/0.5);\n}\n#endif\n#if BLUR_LEVEL == 2\nvec4 blurred1=texture2D(blurStep1,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\nvec4 blurred3=texture2D(textureSampler,vUV);\nif(coc<0.33){\ngl_FragColor=mix(original,blurred1,coc/0.33);\n}else if(coc<0.66){\ngl_FragColor=mix(blurred1,blurred2,(coc-0.33)/0.33);\n}else{\ngl_FragColor=mix(blurred2,blurred3,(coc-0.66)/0.34);\n}\n#endif\n}\n","circleOfConfusionPixelShader":"\nuniform sampler2D depthSampler;\n\nvarying vec2 vUV;\n\nuniform vec2 cameraMinMaxZ;\n\nuniform float focusDistance;\nuniform float cocPrecalculation;\nfloat sampleDistance(const in vec2 offset) {\nfloat depth=texture2D(depthSampler,offset).r; \nreturn (cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth)*1000.0; \n}\nvoid main(void)\n{\nfloat pixelDistance=sampleDistance(vUV);\nfloat coc=abs(cocPrecalculation* ((focusDistance-pixelDistance)/pixelDistance));\ncoc=clamp(coc,0.0,1.0);\ngl_FragColor=vec4(coc,texture2D(depthSampler,vUV).r,coc,1.0);\n}\n","geometryVertexShader":"precision highp float;\nprecision highp int;\n#include<bonesDeclaration>\n#include<instancesDeclaration>\nattribute vec3 position;\nattribute vec3 normal;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nvarying vec2 uv;\n#endif\n#ifdef UV2\nvarying vec2 uv2;\n#endif\n#endif\n\nuniform mat4 viewProjection;\nuniform mat4 view;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 pos=vec4(finalWorld*vec4(position,1.0));\nvNormalV=normalize(vec3((view*finalWorld)*vec4(normal,0.0)));\nvViewPos=view*pos;\n#ifdef POSITION\nvPosition=pos.xyz/pos.w;\n#endif\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","geometryPixelShader":"#extension GL_EXT_draw_buffers : require\nprecision highp float;\nprecision highp int;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef POSITION\n#include<mrtFragmentDeclaration>[3]\n#else\n#include<mrtFragmentDeclaration>[2]\n#endif\nvoid main() {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragData[0]=vec4(vViewPos.z/vViewPos.w,0.0,0.0,1.0);\n\ngl_FragData[1]=vec4(normalize(vNormalV),1.0);\n\n#ifdef POSITION\ngl_FragData[2]=vec4(vPosition,1.0);\n#endif\n}","refractionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D refractionSampler;\n\nuniform vec3 baseColor;\nuniform float depth;\nuniform float colorLevel;\nvoid main() {\nfloat ref=1.0-texture2D(refractionSampler,vUV).r;\nvec2 uv=vUV-vec2(0.5);\nvec2 offset=uv*depth*ref;\nvec3 sourceColor=texture2D(textureSampler,vUV-offset).rgb;\ngl_FragColor=vec4(sourceColor+sourceColor*ref*colorLevel,1.0);\n}","blackAndWhitePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float degree;\nvoid main(void) \n{\nvec3 color=texture2D(textureSampler,vUV).rgb;\nfloat luminance=dot(color,vec3(0.3,0.59,0.11)); \nvec3 blackAndWhite=vec3(luminance,luminance,luminance);\ngl_FragColor=vec4(color-((color-blackAndWhite)*degree),1.0);\n}","convolutionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform float kernel[9];\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 colorSum =\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,-1))*kernel[0] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,-1))*kernel[1] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,-1))*kernel[2] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0))*kernel[3] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,0))*kernel[4] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0))*kernel[5] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,1))*kernel[6] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1))*kernel[7] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,1))*kernel[8];\nfloat kernelWeight =\nkernel[0] +\nkernel[1] +\nkernel[2] +\nkernel[3] +\nkernel[4] +\nkernel[5] +\nkernel[6] +\nkernel[7] +\nkernel[8];\nif (kernelWeight<=0.0) {\nkernelWeight=1.0;\n}\ngl_FragColor=vec4((colorSum/kernelWeight).rgb,1);\n}","filterPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform mat4 kernelMatrix;\nvoid main(void)\n{\nvec3 baseColor=texture2D(textureSampler,vUV).rgb;\nvec3 updatedColor=(kernelMatrix*vec4(baseColor,1.0)).rgb;\ngl_FragColor=vec4(updatedColor,1.0);\n}","volumetricLightScatteringPixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D lightScatteringSampler;\nuniform float decay;\nuniform float exposure;\nuniform float weight;\nuniform float density;\nuniform vec2 meshPositionOnScreen;\nvarying vec2 vUV;\nvoid main(void) {\nvec2 tc=vUV;\nvec2 deltaTexCoord=(tc-meshPositionOnScreen.xy);\ndeltaTexCoord*=1.0/float(NUM_SAMPLES)*density;\nfloat illuminationDecay=1.0;\nvec4 color=texture2D(lightScatteringSampler,tc)*0.4;\nfor(int i=0; i<NUM_SAMPLES; i++) {\ntc-=deltaTexCoord;\nvec4 dataSample=texture2D(lightScatteringSampler,tc)*0.4;\ndataSample*=illuminationDecay*weight;\ncolor+=dataSample;\nilluminationDecay*=decay;\n}\nvec4 realColor=texture2D(textureSampler,vUV);\ngl_FragColor=((vec4((vec3(color.r,color.g,color.b)*exposure),1))+(realColor*(1.5-0.4)));\n}\n","volumetricLightScatteringPassPixelShader":"#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\n#endif\n#if defined(ALPHATEST)\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void)\n{\n#if defined(ALPHATEST)\nvec4 diffuseColor=texture2D(diffuseSampler,vUV);\nif (diffuseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\n","colorCorrectionPixelShader":"\nuniform sampler2D textureSampler; \nuniform sampler2D colorTable; \n\nvarying vec2 vUV;\n\nconst float SLICE_COUNT=16.0; \n\nvec4 sampleAs3DTexture(sampler2D textureSampler,vec3 uv,float width) {\nfloat sliceSize=1.0/width; \nfloat slicePixelSize=sliceSize/width; \nfloat sliceInnerSize=slicePixelSize*(width-1.0); \nfloat zSlice0=min(floor(uv.z*width),width-1.0);\nfloat zSlice1=min(zSlice0+1.0,width-1.0);\nfloat xOffset=slicePixelSize*0.5+uv.x*sliceInnerSize;\nfloat s0=xOffset+(zSlice0*sliceSize);\nfloat s1=xOffset+(zSlice1*sliceSize);\nvec4 slice0Color=texture2D(textureSampler,vec2(s0,uv.y));\nvec4 slice1Color=texture2D(textureSampler,vec2(s1,uv.y));\nfloat zOffset=mod(uv.z*width,1.0);\nvec4 result=mix(slice0Color,slice1Color,zOffset);\nreturn result;\n}\nvoid main(void)\n{\nvec4 screen_color=texture2D(textureSampler,vUV);\ngl_FragColor=sampleAs3DTexture(colorTable,screen_color.rgb,SLICE_COUNT);\n}","tonemapPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float _ExposureAdjustment;\n#if defined(HABLE_TONEMAPPING)\nconst float A=0.15;\nconst float B=0.50;\nconst float C=0.10;\nconst float D=0.20;\nconst float E=0.02;\nconst float F=0.30;\nconst float W=11.2;\n#endif\nfloat Luminance(vec3 c)\n{\nreturn dot(c,vec3(0.22,0.707,0.071));\n}\nvoid main(void) \n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\n#if defined(REINHARD_TONEMAPPING)\nfloat lum=Luminance(colour.rgb); \nfloat lumTm=lum*_ExposureAdjustment;\nfloat scale=lumTm/(1.0+lumTm); \ncolour*=scale/lum;\n#elif defined(HABLE_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nconst float ExposureBias=2.0;\nvec3 x=ExposureBias*colour;\nvec3 curr=((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;\nx=vec3(W,W,W);\nvec3 whiteScale=1.0/(((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F);\ncolour=curr*whiteScale;\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\ncolour=vec3(1.0,1.0,1.0)-exp2(-_ExposureAdjustment*colour);\n#endif\ngl_FragColor=vec4(colour.rgb,1.0);\n}","displayPassPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D passSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(passSampler,vUV);\n}","highlightsPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nconst vec3 RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722);\nvoid main(void) \n{\nvec4 tex=texture2D(textureSampler,vUV);\nvec3 c=tex.rgb;\nfloat luma=dot(c.rgb,RGBLuminanceCoefficients);\n\n\ngl_FragColor=vec4(pow(c,vec3(25.0-luma*15.0)),tex.a); \n}","imageProcessingPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\nvoid main(void)\n{\nvec4 result=texture2D(textureSampler,vUV);\n#ifdef IMAGEPROCESSING\n#ifndef FROMLINEARSPACE\n\nresult.rgb=toLinearSpace(result.rgb);\n#endif\n#ifdef GRAIN\nvec2 seed=vUV*(grainAnimatedSeed);\nfloat grain=dither(seed,grainVarianceAmount);\n\nfloat lum=getLuminance(result.rgb);\nfloat grainAmount=(cos(-PI+(lum*PI*2.))+1.)/2.;\nresult.rgb+=grain*grainAmount;\nresult.rgb=max(result.rgb,0.0);\n#endif\nresult=applyImageProcessing(result);\n#else\n\n#ifdef FROMLINEARSPACE\nresult=applyImageProcessing(result);\n#endif\n#endif\ngl_FragColor=result;\n}","lensFlareVertexShader":"\nattribute vec2 position;\n\nuniform mat4 viewportMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=position*madd+madd;\ngl_Position=viewportMatrix*vec4(position,0.0,1.0);\n}","lensFlarePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\ngl_FragColor=baseColor*color;\n}","anaglyphPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D leftSampler;\nvoid main(void)\n{\nvec4 leftFrag=texture2D(leftSampler,vUV);\nleftFrag=vec4(1.0,leftFrag.g,leftFrag.b,1.0);\nvec4 rightFrag=texture2D(textureSampler,vUV);\nrightFrag=vec4(rightFrag.r,1.0,1.0,1.0);\ngl_FragColor=vec4(rightFrag.rgb*leftFrag.rgb,1.0);\n}","stereoscopicInterlacePixelShader":"const vec3 TWO=vec3(2.0,2.0,2.0);\nvarying vec2 vUV;\nuniform sampler2D camASampler;\nuniform sampler2D textureSampler;\nuniform vec2 stepSize;\nvoid main(void)\n{\nbool useCamB;\nvec2 texCoord1;\nvec2 texCoord2;\nvec3 frag1;\nvec3 frag2;\n#ifdef IS_STEREOSCOPIC_HORIZ\nuseCamB=vUV.x>0.5;\ntexCoord1=vec2(useCamB ? (vUV.x-0.5)*2.0 : vUV.x*2.0,vUV.y);\ntexCoord2=vec2(texCoord1.x+stepSize.x,vUV.y);\n#else\nuseCamB=vUV.y>0.5;\ntexCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2.0 : vUV.y*2.0);\ntexCoord2=vec2(vUV.x,texCoord1.y+stepSize.y);\n#endif\n\nif (useCamB){\nfrag1=texture2D(textureSampler,texCoord1).rgb;\nfrag2=texture2D(textureSampler,texCoord2).rgb;\n}else{\nfrag1=texture2D(camASampler ,texCoord1).rgb;\nfrag2=texture2D(camASampler ,texCoord2).rgb;\n}\ngl_FragColor=vec4((frag1+frag2)/TWO,1.0);\n}","vrDistortionCorrectionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 LensCenter;\nuniform vec2 Scale;\nuniform vec2 ScaleIn;\nuniform vec4 HmdWarpParam;\nvec2 HmdWarp(vec2 in01) {\nvec2 theta=(in01-LensCenter)*ScaleIn; \nfloat rSq=theta.x*theta.x+theta.y*theta.y;\nvec2 rvector=theta*(HmdWarpParam.x+HmdWarpParam.y*rSq+HmdWarpParam.z*rSq*rSq+HmdWarpParam.w*rSq*rSq*rSq);\nreturn LensCenter+Scale*rvector;\n}\nvoid main(void)\n{\nvec2 tc=HmdWarp(vUV);\nif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\ngl_FragColor=vec4(0.0,0.0,0.0,0.0);\nelse{\ngl_FragColor=texture2D(textureSampler,tc);\n}\n}","glowBlurPostProcessPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\n\nfloat getLuminance(vec3 color)\n{\nreturn dot(color,vec3(0.2126,0.7152,0.0722));\n}\nvoid main(void)\n{\nfloat weights[7];\nweights[0]=0.05;\nweights[1]=0.1;\nweights[2]=0.2;\nweights[3]=0.3;\nweights[4]=0.2;\nweights[5]=0.1;\nweights[6]=0.05;\nvec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);\nvec2 texelStep=texelSize*direction*blurWidth;\nvec2 start=vUV-3.0*texelStep;\nvec4 baseColor=vec4(0.,0.,0.,0.);\nvec2 texelOffset=vec2(0.,0.);\nfor (int i=0; i<7; i++)\n{\n\nvec4 texel=texture2D(textureSampler,start+texelOffset);\nbaseColor.a+=texel.a*weights[i];\n\nfloat luminance=getLuminance(baseColor.rgb);\nfloat luminanceTexel=getLuminance(texel.rgb);\nfloat choice=step(luminanceTexel,luminance);\nbaseColor.rgb=choice*baseColor.rgb+(1.0-choice)*texel.rgb;\ntexelOffset+=texelStep;\n}\ngl_FragColor=baseColor;\n}","glowMapGenerationPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform sampler2D emissiveSampler;\n#endif\nuniform vec4 color;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUVDiffuse).a<0.4)\ndiscard;\n#endif\n#ifdef EMISSIVE\ngl_FragColor=texture2D(emissiveSampler,vUVEmissive)*color;\n#else\ngl_FragColor=color;\n#endif\n}","glowMapGenerationVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nvarying vec4 vPosition;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform mat4 diffuseMatrix;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform mat4 emissiveMatrix;\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\n#ifdef CUBEMAP\nvPosition=finalWorld*vec4(position,1.0);\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*finalWorld*vec4(position,1.0);\ngl_Position=vPosition;\n#endif\n#ifdef ALPHATEST\n#ifdef DIFFUSEUV1\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef DIFFUSEUV2\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#ifdef EMISSIVE\n#ifdef EMISSIVEUV1\nvUVEmissive=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef EMISSIVEUV2\nvUVEmissive=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","glowMapMergePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#ifdef EMISSIVE\nuniform sampler2D textureSampler2;\n#endif\n\nuniform float offset;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef EMISSIVE\nbaseColor+=texture2D(textureSampler2,vUV);\nbaseColor*=offset;\n#else\nbaseColor.a=abs(offset-baseColor.a);\n#ifdef STROKE\nfloat alpha=smoothstep(.0,.1,baseColor.a);\nbaseColor.a=alpha;\nbaseColor.rgb=baseColor.rgb*alpha;\n#endif\n#endif\ngl_FragColor=baseColor;\n}","glowMapMergeVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) {\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","lineVertexShader":"\nattribute vec3 position;\nattribute vec4 normal;\n\nuniform mat4 worldViewProjection;\nuniform float width;\nuniform float aspectRatio;\nvoid main(void) {\nvec4 viewPosition=worldViewProjection*vec4(position,1.0);\nvec4 viewPositionNext=worldViewProjection*vec4(normal.xyz,1.0);\nvec2 currentScreen=viewPosition.xy/viewPosition.w;\nvec2 nextScreen=viewPositionNext.xy/viewPositionNext.w;\ncurrentScreen.x*=aspectRatio;\nnextScreen.x*=aspectRatio;\nvec2 dir=normalize(nextScreen-currentScreen);\nvec2 normalDir=vec2(-dir.y,dir.x);\nnormalDir*=width/2.0;\nnormalDir.x/=aspectRatio;\nvec4 offset=vec4(normalDir*normal.w,0.0,0.0);\ngl_Position=viewPosition+offset;\n}","linePixelShader":"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}","outlineVertexShader":"\nattribute vec3 position;\nattribute vec3 normal;\n#include<bonesDeclaration>\n\nuniform float offset;\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n#include<logDepthDeclaration>\nvoid main(void)\n{\nvec3 offsetPosition=position+normal*offset;\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(offsetPosition,1.0);\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#include<logDepthVertex>\n}\n","outlinePixelShader":"#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nuniform vec4 color;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#include<logDepthFragment>\ngl_FragColor=color;\n}","layerVertexShader":"\nattribute vec2 position;\n\nuniform vec2 scale;\nuniform vec2 offset;\nuniform mat4 textureMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvec2 shiftedPosition=position*scale+offset;\nvUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));\ngl_Position=vec4(shiftedPosition,0.0,1.0);\n}","layerPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=baseColor*color;\n}","backgroundVertexShader":"precision highp float;\n#include<__decl__backgroundVertex>\n#include<helperFunctions>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\nvoid main(void) {\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=position;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normal);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\n#ifdef EQUIRECTANGULAR_RELFECTION_FOV\nmat3 screenToWorld=inverseMat3(mat3(finalWorld*viewProjection));\nvec3 segment=mix(vDirectionW,screenToWorld*vec3(0.0,0.0,1.0),abs(fFovMultiplier-1.0));\nif (fFovMultiplier<=1.0) {\nvDirectionW=normalize(segment);\n} else {\nvDirectionW=normalize(vDirectionW+(vDirectionW-segment));\n}\n#endif\n#endif\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0 \nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n}\n","backgroundPixelShader":"#ifdef TEXTURELODSUPPORT\n#extension GL_EXT_shader_texture_lod : enable\n#endif\nprecision highp float;\n#include<__decl__backgroundFragment>\n#define RECIPROCAL_PI2 0.15915494\n\nuniform vec3 vEyePosition;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2; \n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n\n#ifndef SHADOWONLY\n#define SHADOWONLY;\n#endif\n#include<imageProcessingDeclaration>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<helperFunctions>\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n#include<imageProcessingFunctions>\n#include<clipPlaneFragmentDeclaration>\n\n#include<fogFragmentDeclaration>\n#ifdef REFLECTIONFRESNEL\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n#endif\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(0.0,1.0,0.0);\n#endif\n\nfloat shadow=1.;\nfloat globalShadow=0.;\nfloat shadowLightCount=0.;\n#include<lightFragment>[0..maxSimultaneousLights]\n#ifdef SHADOWINUSE\nglobalShadow/=shadowLightCount;\n#else\nglobalShadow=1.0;\n#endif\n\nvec3 reflectionColor=vec3(1.,1.,1.);\n#ifdef REFLECTION\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#ifdef REFLECTIONBLUR\nfloat reflectionLOD=vReflectionInfos.y;\n#ifdef TEXTURELODSUPPORT\n\nreflectionLOD=reflectionLOD*log2(vReflectionMicrosurfaceInfos.x)*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\nreflectionColor=sampleReflectionLod(reflectionSampler,reflectionCoords,reflectionLOD).rgb;\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD,0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec3 reflectionSpecularMid=sampleReflection(reflectionSampler,reflectionCoords).rgb;\nif(lodReflectionNormalizedDoubled<1.0){\nreflectionColor=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords).rgb,\nreflectionSpecularMid,\nlodReflectionNormalizedDoubled\n);\n} else {\nreflectionColor=mix(\nreflectionSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords).rgb,\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#else\nvec4 reflectionSample=sampleReflection(reflectionSampler,reflectionCoords);\nreflectionColor=reflectionSample.rgb;\n#endif\n#ifdef GAMMAREFLECTION\nreflectionColor=toLinearSpace(reflectionColor.rgb);\n#endif\n#ifdef REFLECTIONBGR\nreflectionColor=reflectionColor.bgr;\n#endif\n\nreflectionColor*=vReflectionInfos.x;\n#endif\n\nvec3 diffuseColor=vec3(1.,1.,1.);\nfloat finalAlpha=alpha;\n#ifdef DIFFUSE\nvec4 diffuseMap=texture2D(diffuseSampler,vDiffuseUV);\n#ifdef GAMMADIFFUSE\ndiffuseMap.rgb=toLinearSpace(diffuseMap.rgb);\n#endif\n\ndiffuseMap.rgb*=vDiffuseInfos.y;\n#ifdef DIFFUSEHASALPHA\nfinalAlpha*=diffuseMap.a;\n#endif\ndiffuseColor=diffuseMap.rgb;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 colorBase=diffuseColor;\n#else\nvec3 colorBase=reflectionColor*diffuseColor;\n#endif\ncolorBase=max(colorBase,0.0);\n\n#ifdef USERGBCOLOR\nvec3 finalColor=colorBase;\n#else\nvec3 finalColor=colorBase.r*vPrimaryColor.rgb*vPrimaryColor.a;\nfinalColor+=colorBase.g*vSecondaryColor.rgb*vSecondaryColor.a;\nfinalColor+=colorBase.b*vTertiaryColor.rgb*vTertiaryColor.a;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 reflectionAmount=vReflectionControl.xxx;\nvec3 reflectionReflectance0=vReflectionControl.yyy;\nvec3 reflectionReflectance90=vReflectionControl.zzz;\nfloat VdotN=dot(normalize(vEyePosition),normalW);\nvec3 planarReflectionFresnel=fresnelSchlickEnvironmentGGX(clamp(VdotN,0.0,1.0),reflectionReflectance0,reflectionReflectance90,1.0);\nreflectionAmount*=planarReflectionFresnel;\n#ifdef REFLECTIONFALLOFF\nfloat reflectionDistanceFalloff=1.0-clamp(length(vPositionW.xyz-vBackgroundCenter)*vReflectionControl.w,0.0,1.0);\nreflectionDistanceFalloff*=reflectionDistanceFalloff;\nreflectionAmount*=reflectionDistanceFalloff;\n#endif\nfinalColor=mix(finalColor,reflectionColor,clamp(reflectionAmount,0.,1.));\n#endif\n#ifdef OPACITYFRESNEL\nfloat viewAngleToFloor=dot(normalW,normalize(vEyePosition-vBackgroundCenter));\n\nconst float startAngle=0.1;\nfloat fadeFactor=clamp(viewAngleToFloor/startAngle,0.0,1.0);\nfinalAlpha*=fadeFactor*fadeFactor;\n#endif\n\n#ifdef SHADOWINUSE\nfinalColor=mix(finalColor*shadowLevel,finalColor,globalShadow);\n#endif\n\nvec4 color=vec4(finalColor,finalAlpha);\n#include<fogFragment>\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\ncolor.rgb=clamp(color.rgb,0.,30.0);\n#else\n\ncolor=applyImageProcessing(color);\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#ifndef GRAIN \n#ifdef NOISE\ncolor.rgb+=dither(vPositionW.xy,0.5);\ncolor=max(color,0.0);\n#endif\n#endif\ngl_FragColor=color;\n}\n"};
  91345. 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};\nuniform sampler2D shadowSampler{X};\nuniform mat4 lightMatrix{X};\n#endif\nuniform vec4 shadowsInfo{X};\nuniform vec2 depthValues{X};\n#endif\n#ifdef SPOTLIGHT{X}\nuniform vec4 vLightDirection{X};\n#endif\n#ifdef HEMILIGHT{X}\nuniform vec3 vLightGround{X};\n#endif\n#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};\nuniform sampler2D shadowSampler{X};\nuniform mat4 lightMatrix{X};\n#endif\n#endif\n#endif","defaultVertexDeclaration":"\nuniform mat4 viewProjection;\nuniform mat4 view;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n","defaultFragmentDeclaration":"uniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;\n\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifndef REFRACTIONMAP_3D\nuniform mat4 refractionMatrix;\n#endif\n#ifdef REFRACTIONFRESNEL\nuniform vec4 refractionLeftColor;\nuniform vec4 refractionRightColor;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\n#endif\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REFLECTIONMAP_SKYBOX\n#else\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#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 computeShadowWithPCFCube(vec3 lightPosition,samplerCube shadowSampler,float mapSize,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\nfloat visibility=1.;\nvec3 poissonDisk[4];\npoissonDisk[0]=vec3(-1.0,1.0,-1.0);\npoissonDisk[1]=vec3(1.0,-1.0,-1.0);\npoissonDisk[2]=vec3(-1.0,-1.0,-1.0);\npoissonDisk[3]=vec3(1.0,-1.0,1.0);\n\n#ifndef SHADOWFLOAT\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize))<depth) visibility-=0.25;\n#else\nif (textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize).x<depth) visibility-=0.25;\n#endif\nreturn min(1.0,visibility+darkness);\n}\nfloat computeShadowWithESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness); \nreturn esm;\n}\nfloat computeShadowWithCloseESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn esm;\n}\nfloat computeShadow(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadow=texture2D(shadowSampler,uv).x;\n#endif\nif (shadowPixelDepth>shadow)\n{\nreturn computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff);\n}\nreturn 1.;\n}\nfloat computeShadowWithPCF(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float mapSize,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\nfloat visibility=1.;\nvec2 poissonDisk[4];\npoissonDisk[0]=vec2(-0.94201624,-0.39906216);\npoissonDisk[1]=vec2(0.94558609,-0.76890725);\npoissonDisk[2]=vec2(-0.094184101,-0.92938870);\npoissonDisk[3]=vec2(0.34495938,0.29387760);\n\n#ifndef SHADOWFLOAT\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[0]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[1]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[2]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[3]*mapSize))<shadowPixelDepth) visibility-=0.25;\n#else\nif (texture2D(shadowSampler,uv+poissonDisk[0]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[1]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[2]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[3]*mapSize).x<shadowPixelDepth) visibility-=0.25;\n#endif\nreturn computeFallOff(min(1.0,visibility+darkness),clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithCloseESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0); \n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\n#endif\n","fresnelFunction":"#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection,vec3 worldNormal,float bias,float power)\n{\nfloat fresnelTerm=pow(bias+abs(dot(viewDirection,worldNormal)),power);\nreturn clamp(fresnelTerm,0.,1.);\n}\n#endif","reflectionFunction":"#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#else\n#ifdef SHADOWESM{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#else \n#ifdef SHADOWPCF{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithPCFCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadowWithPCF(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#else\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadow(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#endif\n#endif\n#endif\n#ifdef SHADOWONLY\n#ifndef SHADOWINUSE\n#define SHADOWINUSE\n#endif\nglobalShadow+=shadow;\nshadowLightCount+=1.0;\n#endif\n#else\nshadow=1.;\n#endif\n#ifndef SHADOWONLY\n#ifdef CUSTOMUSERLIGHTING\ndiffuseBase+=computeCustomDiffuseLighting(info,diffuseBase,shadow);\n#ifdef SPECULARTERM\nspecularBase+=computeCustomSpecularLighting(info,specularBase,shadow);\n#endif\n#elif defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X})\ndiffuseBase+=lightmapColor*shadow;\n#ifdef SPECULARTERM\n#ifndef LIGHTMAPNOSPECULAR{X}\nspecularBase+=info.specular*shadow*lightmapColor;\n#endif\n#endif\n#else\ndiffuseBase+=info.diffuse*shadow;\n#ifdef SPECULARTERM\nspecularBase+=info.specular*shadow;\n#endif\n#endif\n#endif\n#endif","logDepthFragment":"#ifdef LOGARITHMICDEPTH\ngl_FragDepthEXT=log2(vFragmentDepth)*logarithmicDepthConstant*0.5;\n#endif","fogFragment":"#ifdef FOG\nfloat fog=CalcFogFactor();\ncolor.rgb=fog*color.rgb+(1.0-fog)*vFogColor;\n#endif","pbrVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef ALBEDO\nuniform mat4 albedoMatrix;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#ifdef REFLECTIVITY \nuniform vec3 vReflectivityInfos;\nuniform mat4 reflectivityMatrix;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform mat4 microSurfaceSamplerMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n","pbrFragmentDeclaration":"uniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\n\nuniform vec4 vLightingIntensity;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\n\n#ifdef ALBEDO\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef REFLECTIVITY\nuniform vec3 vReflectivityInfos;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\n#endif\n\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#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};"};
  91346. var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : this);
  91347. globalObject["BABYLON"] = BABYLON
  91348. return BABYLON;
  91349. });
  91350. /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(16)))
  91351. /***/ }),
  91352. /* 1 */
  91353. /***/ (function(module, exports, __webpack_require__) {
  91354. "use strict";
  91355. Object.defineProperty(exports, "__esModule", { value: true });
  91356. var babylonjs_1 = __webpack_require__(0);
  91357. var helper_1 = __webpack_require__(2);
  91358. var HTMLMapper = (function () {
  91359. function HTMLMapper() {
  91360. }
  91361. HTMLMapper.prototype.map = function (element) {
  91362. var config = {};
  91363. var _loop_1 = function (attrIdx) {
  91364. var attr = element.attributes.item(attrIdx);
  91365. var split = attr.nodeName.split('.');
  91366. split.reduce(function (currentConfig, key, idx) {
  91367. var camelKey = helper_1.kebabToCamel(key);
  91368. if (idx === split.length - 1) {
  91369. var val = attr.nodeValue;
  91370. if (val === "true") {
  91371. val = true;
  91372. }
  91373. else if (val === "false") {
  91374. val = false;
  91375. }
  91376. else {
  91377. var isnum = /^\d+$/.test(val);
  91378. if (isnum) {
  91379. var number = parseFloat(val);
  91380. if (!isNaN(number)) {
  91381. val = number;
  91382. }
  91383. }
  91384. }
  91385. currentConfig[camelKey] = val;
  91386. }
  91387. else {
  91388. currentConfig[camelKey] = currentConfig[camelKey] || {};
  91389. }
  91390. return currentConfig[camelKey];
  91391. }, config);
  91392. };
  91393. for (var attrIdx = 0; attrIdx < element.attributes.length; ++attrIdx) {
  91394. _loop_1(attrIdx);
  91395. }
  91396. return config;
  91397. };
  91398. return HTMLMapper;
  91399. }());
  91400. var JSONMapper = (function () {
  91401. function JSONMapper() {
  91402. }
  91403. JSONMapper.prototype.map = function (rawSource) {
  91404. return JSON.parse(rawSource);
  91405. };
  91406. return JSONMapper;
  91407. }());
  91408. var DOMMapper = (function () {
  91409. function DOMMapper() {
  91410. }
  91411. DOMMapper.prototype.map = function (baseElement) {
  91412. var htmlMapper = new HTMLMapper();
  91413. var config = htmlMapper.map(baseElement);
  91414. var traverseChildren = function (element, partConfig) {
  91415. var children = element.children;
  91416. if (children.length) {
  91417. for (var i = 0; i < children.length; ++i) {
  91418. var item = children.item(i);
  91419. var configMapped = htmlMapper.map(item);
  91420. var key = helper_1.kebabToCamel(item.nodeName.toLowerCase());
  91421. if (item.attributes.getNamedItem('array') && item.attributes.getNamedItem('array').nodeValue === 'true') {
  91422. partConfig[key] = [];
  91423. }
  91424. else {
  91425. if (element.attributes.getNamedItem('array') && element.attributes.getNamedItem('array').nodeValue === 'true') {
  91426. partConfig.push(configMapped);
  91427. }
  91428. else if (partConfig[key]) {
  91429. element.setAttribute('array', 'true');
  91430. var oldItem = partConfig[key];
  91431. partConfig = [oldItem, configMapped];
  91432. }
  91433. else {
  91434. partConfig[key] = configMapped;
  91435. }
  91436. }
  91437. traverseChildren(item, partConfig[key] || configMapped);
  91438. }
  91439. }
  91440. return partConfig;
  91441. };
  91442. traverseChildren(baseElement, config);
  91443. return config;
  91444. };
  91445. return DOMMapper;
  91446. }());
  91447. var MapperManager = (function () {
  91448. function MapperManager() {
  91449. this.mappers = {
  91450. "html": new HTMLMapper(),
  91451. "json": new JSONMapper(),
  91452. "dom": new DOMMapper()
  91453. };
  91454. }
  91455. MapperManager.prototype.getMapper = function (type) {
  91456. if (!this.mappers[type]) {
  91457. babylonjs_1.Tools.Error("No mapper defined for " + type);
  91458. }
  91459. return this.mappers[type] || this.mappers[MapperManager.DefaultMapper];
  91460. };
  91461. MapperManager.prototype.registerMapper = function (type, mapper) {
  91462. this.mappers[type] = mapper;
  91463. };
  91464. MapperManager.DefaultMapper = 'json';
  91465. return MapperManager;
  91466. }());
  91467. exports.MapperManager = MapperManager;
  91468. exports.mapperManager = new MapperManager();
  91469. /***/ }),
  91470. /* 2 */
  91471. /***/ (function(module, exports, __webpack_require__) {
  91472. "use strict";
  91473. Object.defineProperty(exports, "__esModule", { value: true });
  91474. function isUrl(urlToCheck) {
  91475. if (urlToCheck.indexOf('http') === 0 || urlToCheck.indexOf('/') === 0 || urlToCheck.indexOf('./') === 0 || urlToCheck.indexOf('../') === 0) {
  91476. return true;
  91477. }
  91478. return false;
  91479. }
  91480. exports.isUrl = isUrl;
  91481. function kebabToCamel(s) {
  91482. return s.replace(/(\-\w)/g, function (m) { return m[1].toUpperCase(); });
  91483. }
  91484. exports.kebabToCamel = kebabToCamel;
  91485. function camelToKebab(str) {
  91486. return !str ? null : str.replace(/([A-Z])/g, function (g) { return '-' + g[0].toLowerCase(); });
  91487. }
  91488. exports.camelToKebab = camelToKebab;
  91489. /***/ }),
  91490. /* 3 */
  91491. /***/ (function(module, exports, __webpack_require__) {
  91492. "use strict";
  91493. Object.defineProperty(exports, "__esModule", { value: true });
  91494. var babylonjs_1 = __webpack_require__(0);
  91495. var ViewerManager = (function () {
  91496. function ViewerManager() {
  91497. this.viewers = {};
  91498. this.onViewerAddedObservable = new babylonjs_1.Observable();
  91499. }
  91500. ViewerManager.prototype.addViewer = function (viewer) {
  91501. this.viewers[viewer.getBaseId()] = viewer;
  91502. this._onViewerAdded(viewer);
  91503. };
  91504. ViewerManager.prototype.getViewerById = function (id) {
  91505. return this.viewers[id];
  91506. };
  91507. ViewerManager.prototype.getViewerByHTMLElement = function (element) {
  91508. for (var id in this.viewers) {
  91509. if (this.viewers[id].containerElement === element) {
  91510. return this.getViewerById(id);
  91511. }
  91512. }
  91513. };
  91514. ViewerManager.prototype.getViewerPromiseById = function (id) {
  91515. var _this = this;
  91516. return new Promise(function (resolve, reject) {
  91517. var localViewer = _this.getViewerById(id);
  91518. if (localViewer) {
  91519. return resolve(localViewer);
  91520. }
  91521. var viewerFunction = function (viewer) {
  91522. if (viewer.getBaseId() === id) {
  91523. resolve(viewer);
  91524. _this.onViewerAddedObservable.removeCallback(viewerFunction);
  91525. }
  91526. };
  91527. _this.onViewerAddedObservable.add(viewerFunction);
  91528. });
  91529. };
  91530. ViewerManager.prototype._onViewerAdded = function (viewer) {
  91531. this.onViewerAdded && this.onViewerAdded(viewer);
  91532. this.onViewerAddedObservable.notifyObservers(viewer);
  91533. };
  91534. return ViewerManager;
  91535. }());
  91536. exports.ViewerManager = ViewerManager;
  91537. exports.viewerManager = new ViewerManager();
  91538. /***/ }),
  91539. /* 4 */
  91540. /***/ (function(module, exports, __webpack_require__) {
  91541. "use strict";
  91542. var __extends = (this && this.__extends) || (function () {
  91543. var extendStatics = Object.setPrototypeOf ||
  91544. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  91545. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  91546. return function (d, b) {
  91547. extendStatics(d, b);
  91548. function __() { this.constructor = d; }
  91549. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  91550. };
  91551. })();
  91552. Object.defineProperty(exports, "__esModule", { value: true });
  91553. var viewer_1 = __webpack_require__(5);
  91554. var babylonjs_1 = __webpack_require__(0);
  91555. var DefaultViewer = (function (_super) {
  91556. __extends(DefaultViewer, _super);
  91557. function DefaultViewer(containerElement, initialConfiguration) {
  91558. if (initialConfiguration === void 0) { initialConfiguration = { extends: 'default' }; }
  91559. var _this = _super.call(this, containerElement, initialConfiguration) || this;
  91560. _this.containerElement = containerElement;
  91561. _this.onModelLoaded = function (model) {
  91562. var hideLoadingDelay = 500;
  91563. if (_this.configuration.lab && _this.configuration.lab.hideLoadingDelay !== undefined) {
  91564. hideLoadingDelay = _this.configuration.lab.hideLoadingDelay;
  91565. }
  91566. setTimeout(function () {
  91567. _this.hideLoadingScreen();
  91568. }, hideLoadingDelay);
  91569. return;
  91570. };
  91571. _this.onModelLoadedObservable.add(_this.onModelLoaded);
  91572. return _this;
  91573. }
  91574. DefaultViewer.prototype.initScene = function () {
  91575. var _this = this;
  91576. return _super.prototype.initScene.call(this).then(function () {
  91577. _this.extendClassWithConfig(_this.scene, _this.configuration.scene);
  91578. return _this.scene;
  91579. });
  91580. };
  91581. DefaultViewer.prototype.onTemplatesLoaded = function () {
  91582. var _this = this;
  91583. this.showLoadingScreen();
  91584. this.initNavbar();
  91585. var closeButton = document.getElementById('close-button');
  91586. if (closeButton) {
  91587. closeButton.addEventListener('pointerdown', function () {
  91588. _this.hideOverlayScreen();
  91589. });
  91590. }
  91591. return _super.prototype.onTemplatesLoaded.call(this);
  91592. };
  91593. DefaultViewer.prototype.initNavbar = function () {
  91594. var navbar = this.templateManager.getTemplate('navBar');
  91595. if (navbar) {
  91596. var navbarHeight_1 = navbar.parent.clientHeight + 'px';
  91597. var navbarShown_1 = true;
  91598. var timeoutCancel_1;
  91599. var triggerNavbar = function (show, evt) {
  91600. if (show === void 0) { show = false; }
  91601. if (!navbar || evt.button > 0)
  91602. return;
  91603. timeoutCancel_1 && clearTimeout(timeoutCancel_1);
  91604. if (show === navbarShown_1)
  91605. return;
  91606. if (show) {
  91607. navbar.parent.style.bottom = show ? '0px' : '-' + navbarHeight_1;
  91608. navbarShown_1 = show;
  91609. }
  91610. else {
  91611. var visibilityTimeout = 2000;
  91612. if (navbar.configuration.params && navbar.configuration.params.visibilityTimeout !== undefined) {
  91613. visibilityTimeout = navbar.configuration.params.visibilityTimeout;
  91614. }
  91615. timeoutCancel_1 = setTimeout(function () {
  91616. if (navbar) {
  91617. navbar.parent.style.bottom = '-' + navbarHeight_1;
  91618. }
  91619. navbarShown_1 = show;
  91620. }, visibilityTimeout);
  91621. }
  91622. };
  91623. this.templateManager.eventManager.registerCallback('viewer', triggerNavbar.bind(this, false), 'pointerout');
  91624. this.templateManager.eventManager.registerCallback('viewer', triggerNavbar.bind(this, true), 'pointerdown');
  91625. this.templateManager.eventManager.registerCallback('viewer', triggerNavbar.bind(this, false), 'pointerup');
  91626. this.templateManager.eventManager.registerCallback('navBar', triggerNavbar.bind(this, true), 'pointerover');
  91627. var viewerTemplate = this.templateManager.getTemplate('viewer');
  91628. var viewerElement_1 = viewerTemplate && viewerTemplate.parent;
  91629. var triggerFullscren = function (eventData) {
  91630. if (viewerElement_1) {
  91631. var fullscreenElement = document.fullscreenElement || document.webkitFullscreenElement || document.mozFullScreenElement || document.msFullscreenElement;
  91632. if (!fullscreenElement) {
  91633. var requestFullScreen = viewerElement_1.requestFullscreen || viewerElement_1.webkitRequestFullscreen || viewerElement_1.msRequestFullscreen || viewerElement_1.mozRequestFullScreen;
  91634. requestFullScreen.call(viewerElement_1);
  91635. }
  91636. else {
  91637. var exitFullscreen = document.exitFullscreen || document.webkitExitFullscreen || document.msExitFullscreen || document.mozCancelFullScreen;
  91638. exitFullscreen.call(document);
  91639. }
  91640. }
  91641. };
  91642. this.templateManager.eventManager.registerCallback('navBar', triggerFullscren, 'pointerdown', '#fullscreen-button');
  91643. }
  91644. };
  91645. DefaultViewer.prototype.prepareContainerElement = function () {
  91646. this.containerElement.style.position = 'relative';
  91647. this.containerElement.style.display = 'flex';
  91648. };
  91649. DefaultViewer.prototype.configureModel = function (modelConfiguration, model) {
  91650. _super.prototype.configureModel.call(this, modelConfiguration, model);
  91651. var navbar = this.templateManager.getTemplate('navBar');
  91652. if (!navbar)
  91653. return;
  91654. var metadataContainer = navbar.parent.querySelector('#model-metadata');
  91655. if (metadataContainer) {
  91656. if (modelConfiguration.title !== undefined) {
  91657. var element = metadataContainer.querySelector('span.model-title');
  91658. if (element) {
  91659. element.innerHTML = modelConfiguration.title;
  91660. }
  91661. }
  91662. if (modelConfiguration.subtitle !== undefined) {
  91663. var element = metadataContainer.querySelector('span.model-subtitle');
  91664. if (element) {
  91665. element.innerHTML = modelConfiguration.subtitle;
  91666. }
  91667. }
  91668. if (modelConfiguration.thumbnail !== undefined) {
  91669. metadataContainer.querySelector('.thumbnail').style.backgroundImage = "url('" + modelConfiguration.thumbnail + "')";
  91670. }
  91671. }
  91672. };
  91673. DefaultViewer.prototype.loadModel = function (model) {
  91674. var _this = this;
  91675. if (model === void 0) { model = this.configuration.model; }
  91676. this.showLoadingScreen();
  91677. return _super.prototype.loadModel.call(this, model, true).catch(function (error) {
  91678. console.log(error);
  91679. _this.hideLoadingScreen();
  91680. _this.showOverlayScreen('error');
  91681. return Promise.reject(error);
  91682. });
  91683. };
  91684. DefaultViewer.prototype.showOverlayScreen = function (subScreen) {
  91685. var _this = this;
  91686. var template = this.templateManager.getTemplate('overlay');
  91687. if (!template)
  91688. return Promise.resolve('Overlay template not found');
  91689. return template.show((function (template) {
  91690. var canvasRect = _this.containerElement.getBoundingClientRect();
  91691. var canvasPositioning = window.getComputedStyle(_this.containerElement).position;
  91692. template.parent.style.display = 'flex';
  91693. template.parent.style.width = canvasRect.width + "px";
  91694. template.parent.style.height = canvasRect.height + "px";
  91695. template.parent.style.opacity = "1";
  91696. var subTemplate = _this.templateManager.getTemplate(subScreen);
  91697. if (!subTemplate) {
  91698. return Promise.reject(subScreen + ' template not found');
  91699. }
  91700. return subTemplate.show((function (template) {
  91701. template.parent.style.display = 'flex';
  91702. return Promise.resolve(template);
  91703. }));
  91704. }));
  91705. };
  91706. DefaultViewer.prototype.hideOverlayScreen = function () {
  91707. var template = this.templateManager.getTemplate('overlay');
  91708. if (!template)
  91709. return Promise.resolve('Overlay template not found');
  91710. return template.hide((function (template) {
  91711. template.parent.style.opacity = "0";
  91712. var onTransitionEnd = function () {
  91713. template.parent.removeEventListener("transitionend", onTransitionEnd);
  91714. template.parent.style.display = 'none';
  91715. };
  91716. template.parent.addEventListener("transitionend", onTransitionEnd);
  91717. var overlays = template.parent.querySelectorAll('.overlay');
  91718. if (overlays) {
  91719. for (var i = 0; i < overlays.length; ++i) {
  91720. var htmlElement = overlays.item(i);
  91721. htmlElement.style.display = 'none';
  91722. }
  91723. }
  91724. return Promise.resolve(template);
  91725. }));
  91726. };
  91727. DefaultViewer.prototype.showLoadingScreen = function () {
  91728. var _this = this;
  91729. var template = this.templateManager.getTemplate('loadingScreen');
  91730. if (!template)
  91731. return Promise.resolve('Loading Screen template not found');
  91732. return template.show((function (template) {
  91733. var canvasRect = _this.containerElement.getBoundingClientRect();
  91734. var canvasPositioning = window.getComputedStyle(_this.containerElement).position;
  91735. template.parent.style.display = 'flex';
  91736. template.parent.style.width = canvasRect.width + "px";
  91737. template.parent.style.height = canvasRect.height + "px";
  91738. template.parent.style.opacity = "1";
  91739. template.parent.style.backgroundColor = "black";
  91740. return Promise.resolve(template);
  91741. }));
  91742. };
  91743. DefaultViewer.prototype.hideLoadingScreen = function () {
  91744. var template = this.templateManager.getTemplate('loadingScreen');
  91745. if (!template)
  91746. return Promise.resolve('Loading Screen template not found');
  91747. return template.hide((function (template) {
  91748. template.parent.style.opacity = "0";
  91749. var onTransitionEnd = function () {
  91750. template.parent.removeEventListener("transitionend", onTransitionEnd);
  91751. template.parent.style.display = 'none';
  91752. };
  91753. template.parent.addEventListener("transitionend", onTransitionEnd);
  91754. return Promise.resolve(template);
  91755. }));
  91756. };
  91757. DefaultViewer.prototype.configureLights = function (lightsConfiguration, model) {
  91758. var _this = this;
  91759. if (lightsConfiguration === void 0) { lightsConfiguration = {}; }
  91760. _super.prototype.configureLights.call(this, lightsConfiguration, model);
  91761. if (this.configuration.lab && this.configuration.lab.flashlight) {
  91762. var pointerPosition = BABYLON.Vector3.Zero();
  91763. var lightTarget_1;
  91764. var angle = 0.5;
  91765. var exponent = Math.PI / 2;
  91766. if (typeof this.configuration.lab.flashlight === "object") {
  91767. exponent = this.configuration.lab.flashlight.exponent || exponent;
  91768. angle = this.configuration.lab.flashlight.angle || angle;
  91769. }
  91770. var flashlight = new babylonjs_1.SpotLight("flashlight", babylonjs_1.Vector3.Zero(), babylonjs_1.Vector3.Zero(), exponent, angle, this.scene);
  91771. if (typeof this.configuration.lab.flashlight === "object") {
  91772. flashlight.intensity = this.configuration.lab.flashlight.intensity || flashlight.intensity;
  91773. if (this.configuration.lab.flashlight.diffuse) {
  91774. flashlight.diffuse.r = this.configuration.lab.flashlight.diffuse.r;
  91775. flashlight.diffuse.g = this.configuration.lab.flashlight.diffuse.g;
  91776. flashlight.diffuse.b = this.configuration.lab.flashlight.diffuse.b;
  91777. }
  91778. if (this.configuration.lab.flashlight.specular) {
  91779. flashlight.specular.r = this.configuration.lab.flashlight.specular.r;
  91780. flashlight.specular.g = this.configuration.lab.flashlight.specular.g;
  91781. flashlight.specular.b = this.configuration.lab.flashlight.specular.b;
  91782. }
  91783. }
  91784. this.scene.constantlyUpdateMeshUnderPointer = true;
  91785. this.scene.onPointerObservable.add(function (eventData, eventState) {
  91786. if (eventData.type === 4 && eventData.pickInfo) {
  91787. lightTarget_1 = (eventData.pickInfo.pickedPoint);
  91788. }
  91789. else {
  91790. lightTarget_1 = undefined;
  91791. }
  91792. });
  91793. var updateFlashlightFunction = function () {
  91794. if (_this.camera && flashlight) {
  91795. flashlight.position.copyFrom(_this.camera.position);
  91796. if (lightTarget_1) {
  91797. lightTarget_1.subtractToRef(flashlight.position, flashlight.direction);
  91798. }
  91799. }
  91800. };
  91801. this.scene.registerBeforeRender(updateFlashlightFunction);
  91802. this.registeredOnBeforerenderFunctions.push(updateFlashlightFunction);
  91803. }
  91804. };
  91805. return DefaultViewer;
  91806. }(viewer_1.AbstractViewer));
  91807. exports.DefaultViewer = DefaultViewer;
  91808. /***/ }),
  91809. /* 5 */
  91810. /***/ (function(module, exports, __webpack_require__) {
  91811. "use strict";
  91812. Object.defineProperty(exports, "__esModule", { value: true });
  91813. var viewerManager_1 = __webpack_require__(3);
  91814. var templateManager_1 = __webpack_require__(19);
  91815. var loader_1 = __webpack_require__(22);
  91816. var babylonjs_1 = __webpack_require__(0);
  91817. var deepmerge = __webpack_require__(13);
  91818. var viewerModel_1 = __webpack_require__(30);
  91819. var AbstractViewer = (function () {
  91820. function AbstractViewer(containerElement, initialConfiguration) {
  91821. if (initialConfiguration === void 0) { initialConfiguration = {}; }
  91822. var _this = this;
  91823. this.containerElement = containerElement;
  91824. this.resize = function () {
  91825. if (!_this.isCanvasInDOM()) {
  91826. return;
  91827. }
  91828. if (_this.canvas.clientWidth <= 0 || _this.canvas.clientHeight <= 0) {
  91829. return;
  91830. }
  91831. _this.engine.resize();
  91832. };
  91833. this.render = function () {
  91834. _this.scene && _this.scene.activeCamera && _this.scene.render();
  91835. };
  91836. if (containerElement.id) {
  91837. this.baseId = containerElement.id;
  91838. }
  91839. else {
  91840. this.baseId = containerElement.id = 'bjs' + Math.random().toString(32).substr(2, 8);
  91841. }
  91842. this.onSceneInitObservable = new babylonjs_1.Observable();
  91843. this.onEngineInitObservable = new babylonjs_1.Observable();
  91844. this.onModelLoadedObservable = new babylonjs_1.Observable();
  91845. this.onModelLoadProgressObservable = new babylonjs_1.Observable();
  91846. this.onModelLoadErrorObservable = new babylonjs_1.Observable();
  91847. this.onInitDoneObservable = new babylonjs_1.Observable();
  91848. this.onLoaderInitObservable = new babylonjs_1.Observable();
  91849. this.registeredOnBeforerenderFunctions = [];
  91850. this.models = [];
  91851. viewerManager_1.viewerManager.addViewer(this);
  91852. this.templateManager = new templateManager_1.TemplateManager(containerElement);
  91853. this.prepareContainerElement();
  91854. loader_1.default.loadConfiguration(initialConfiguration, function (configuration) {
  91855. _this.configuration = deepmerge(_this.configuration || {}, configuration);
  91856. if (_this.configuration.observers) {
  91857. _this.configureObservers(_this.configuration.observers);
  91858. }
  91859. var templateConfiguration = _this.configuration.templates || {};
  91860. _this.templateManager.initTemplate(templateConfiguration);
  91861. _this.templateManager.onAllLoaded.add(function () {
  91862. var canvas = _this.templateManager.getCanvas();
  91863. if (canvas) {
  91864. _this.canvas = canvas;
  91865. }
  91866. _this._onTemplateLoaded();
  91867. });
  91868. });
  91869. }
  91870. Object.defineProperty(AbstractViewer.prototype, "isHdrSupported", {
  91871. get: function () {
  91872. return this._hdrSupport;
  91873. },
  91874. enumerable: true,
  91875. configurable: true
  91876. });
  91877. AbstractViewer.prototype.getBaseId = function () {
  91878. return this.baseId;
  91879. };
  91880. AbstractViewer.prototype.isCanvasInDOM = function () {
  91881. return !!this.canvas && !!this.canvas.parentElement;
  91882. };
  91883. AbstractViewer.prototype.updateConfiguration = function (newConfiguration) {
  91884. if (newConfiguration === void 0) { newConfiguration = this.configuration; }
  91885. this.configuration = deepmerge(this.configuration || {}, newConfiguration);
  91886. if (newConfiguration.scene) {
  91887. this.configureScene(newConfiguration.scene);
  91888. }
  91889. if (newConfiguration.optimizer) {
  91890. this.configureOptimizer(newConfiguration.optimizer);
  91891. }
  91892. if (newConfiguration.observers) {
  91893. this.configureObservers(newConfiguration.observers);
  91894. }
  91895. if (newConfiguration.model && typeof newConfiguration.model === 'object') {
  91896. this.configureModel(newConfiguration.model);
  91897. }
  91898. if (newConfiguration.lights) {
  91899. this.configureLights(newConfiguration.lights);
  91900. }
  91901. if (newConfiguration.skybox !== undefined || newConfiguration.ground !== undefined) {
  91902. this.configureEnvironment(newConfiguration.skybox, newConfiguration.ground);
  91903. }
  91904. if (newConfiguration.camera) {
  91905. this.configureCamera(newConfiguration.camera);
  91906. }
  91907. };
  91908. AbstractViewer.prototype.configureEnvironment = function (skyboxConifguration, groundConfiguration) {
  91909. if (!skyboxConifguration && !groundConfiguration) {
  91910. if (this.environmentHelper) {
  91911. this.environmentHelper.dispose();
  91912. delete this.environmentHelper;
  91913. }
  91914. ;
  91915. return Promise.resolve(this.scene);
  91916. }
  91917. var options = {
  91918. createGround: !!groundConfiguration,
  91919. createSkybox: !!skyboxConifguration,
  91920. setupImageProcessing: false
  91921. };
  91922. if (groundConfiguration) {
  91923. var groundConfig = (typeof groundConfiguration === 'boolean') ? {} : groundConfiguration;
  91924. var groundSize = groundConfig.size || (typeof skyboxConifguration === 'object' && skyboxConifguration.scale);
  91925. if (groundSize) {
  91926. options.groundSize = groundSize;
  91927. }
  91928. options.enableGroundShadow = groundConfig === true || groundConfig.receiveShadows;
  91929. if (groundConfig.shadowLevel !== undefined) {
  91930. options.groundShadowLevel = groundConfig.shadowLevel;
  91931. }
  91932. options.enableGroundMirror = !!groundConfig.mirror;
  91933. if (groundConfig.texture) {
  91934. options.groundTexture = groundConfig.texture;
  91935. }
  91936. if (groundConfig.color) {
  91937. options.groundColor = new babylonjs_1.Color3(groundConfig.color.r, groundConfig.color.g, groundConfig.color.b);
  91938. }
  91939. if (groundConfig.opacity !== undefined) {
  91940. options.groundOpacity = groundConfig.opacity;
  91941. }
  91942. if (groundConfig.mirror) {
  91943. options.enableGroundMirror = true;
  91944. if (typeof groundConfig.mirror === "object") {
  91945. if (groundConfig.mirror.amount !== undefined)
  91946. options.groundMirrorAmount = groundConfig.mirror.amount;
  91947. if (groundConfig.mirror.sizeRatio !== undefined)
  91948. options.groundMirrorSizeRatio = groundConfig.mirror.sizeRatio;
  91949. if (groundConfig.mirror.blurKernel !== undefined)
  91950. options.groundMirrorBlurKernel = groundConfig.mirror.blurKernel;
  91951. if (groundConfig.mirror.fresnelWeight !== undefined)
  91952. options.groundMirrorFresnelWeight = groundConfig.mirror.fresnelWeight;
  91953. if (groundConfig.mirror.fallOffDistance !== undefined)
  91954. options.groundMirrorFallOffDistance = groundConfig.mirror.fallOffDistance;
  91955. if (this.defaultPipelineTextureType !== undefined)
  91956. options.groundMirrorTextureType = this.defaultPipelineTextureType;
  91957. }
  91958. }
  91959. }
  91960. var postInitSkyboxMaterial = false;
  91961. if (skyboxConifguration) {
  91962. var conf = skyboxConifguration === true ? {} : skyboxConifguration;
  91963. if (conf.material && conf.material.imageProcessingConfiguration) {
  91964. options.setupImageProcessing = false;
  91965. }
  91966. var skyboxSize = conf.scale;
  91967. if (skyboxSize) {
  91968. options.skyboxSize = skyboxSize;
  91969. }
  91970. options.sizeAuto = !options.skyboxSize;
  91971. if (conf.color) {
  91972. options.skyboxColor = new babylonjs_1.Color3(conf.color.r, conf.color.g, conf.color.b);
  91973. }
  91974. if (conf.cubeTexture && conf.cubeTexture.url) {
  91975. if (typeof conf.cubeTexture.url === "string") {
  91976. options.skyboxTexture = conf.cubeTexture.url;
  91977. }
  91978. else {
  91979. postInitSkyboxMaterial = true;
  91980. }
  91981. }
  91982. if (conf.material && conf.material.imageProcessingConfiguration) {
  91983. postInitSkyboxMaterial = true;
  91984. }
  91985. }
  91986. options.setupImageProcessing = false;
  91987. if (!this.environmentHelper) {
  91988. this.environmentHelper = this.scene.createDefaultEnvironment(options);
  91989. }
  91990. else {
  91991. var scene = this.environmentHelper.rootMesh.getScene();
  91992. if (scene !== this.scene) {
  91993. this.environmentHelper.dispose();
  91994. this.environmentHelper = this.scene.createDefaultEnvironment(options);
  91995. }
  91996. else {
  91997. this.environmentHelper.updateOptions(options);
  91998. }
  91999. }
  92000. if (postInitSkyboxMaterial) {
  92001. var skyboxMaterial = this.environmentHelper.skyboxMaterial;
  92002. if (skyboxMaterial) {
  92003. if (typeof skyboxConifguration === 'object' && skyboxConifguration.material && skyboxConifguration.material.imageProcessingConfiguration) {
  92004. this.extendClassWithConfig(skyboxMaterial.imageProcessingConfiguration, skyboxConifguration.material.imageProcessingConfiguration);
  92005. }
  92006. }
  92007. }
  92008. };
  92009. AbstractViewer.prototype.configureScene = function (sceneConfig, optimizerConfig) {
  92010. if (!this.scene) {
  92011. return;
  92012. }
  92013. if (sceneConfig.debug) {
  92014. this.scene.debugLayer.show();
  92015. }
  92016. else {
  92017. if (this.scene.debugLayer.isVisible()) {
  92018. this.scene.debugLayer.hide();
  92019. }
  92020. }
  92021. if (sceneConfig.clearColor) {
  92022. var cc = sceneConfig.clearColor;
  92023. var oldcc = this.scene.clearColor;
  92024. if (cc.r !== undefined) {
  92025. oldcc.r = cc.r;
  92026. }
  92027. if (cc.g !== undefined) {
  92028. oldcc.g = cc.g;
  92029. }
  92030. if (cc.b !== undefined) {
  92031. oldcc.b = cc.b;
  92032. }
  92033. if (cc.a !== undefined) {
  92034. oldcc.a = cc.a;
  92035. }
  92036. }
  92037. if (sceneConfig.imageProcessingConfiguration) {
  92038. this.extendClassWithConfig(this.scene.imageProcessingConfiguration, sceneConfig.imageProcessingConfiguration);
  92039. }
  92040. if (sceneConfig.environmentTexture) {
  92041. if (this.scene.environmentTexture) {
  92042. this.scene.environmentTexture.dispose();
  92043. }
  92044. var environmentTexture = babylonjs_1.CubeTexture.CreateFromPrefilteredData(sceneConfig.environmentTexture, this.scene);
  92045. this.scene.environmentTexture = environmentTexture;
  92046. }
  92047. if (sceneConfig.autoRotate) {
  92048. this.camera.useAutoRotationBehavior = true;
  92049. }
  92050. };
  92051. AbstractViewer.prototype.configureOptimizer = function (optimizerConfig) {
  92052. if (typeof optimizerConfig === 'boolean') {
  92053. if (this.sceneOptimizer) {
  92054. this.sceneOptimizer.stop();
  92055. this.sceneOptimizer.dispose();
  92056. delete this.sceneOptimizer;
  92057. }
  92058. if (optimizerConfig) {
  92059. this.sceneOptimizer = new babylonjs_1.SceneOptimizer(this.scene);
  92060. this.sceneOptimizer.start();
  92061. }
  92062. }
  92063. else {
  92064. var optimizerOptions = new babylonjs_1.SceneOptimizerOptions(optimizerConfig.targetFrameRate, optimizerConfig.trackerDuration);
  92065. if (optimizerConfig.degradation) {
  92066. switch (optimizerConfig.degradation) {
  92067. case "low":
  92068. optimizerOptions = babylonjs_1.SceneOptimizerOptions.LowDegradationAllowed(optimizerConfig.targetFrameRate);
  92069. break;
  92070. case "moderate":
  92071. optimizerOptions = babylonjs_1.SceneOptimizerOptions.ModerateDegradationAllowed(optimizerConfig.targetFrameRate);
  92072. break;
  92073. case "hight":
  92074. optimizerOptions = babylonjs_1.SceneOptimizerOptions.HighDegradationAllowed(optimizerConfig.targetFrameRate);
  92075. break;
  92076. }
  92077. }
  92078. if (this.sceneOptimizer) {
  92079. this.sceneOptimizer.stop();
  92080. this.sceneOptimizer.dispose();
  92081. }
  92082. this.sceneOptimizer = new babylonjs_1.SceneOptimizer(this.scene, optimizerOptions, optimizerConfig.autoGeneratePriorities, optimizerConfig.improvementMode);
  92083. this.sceneOptimizer.start();
  92084. }
  92085. };
  92086. AbstractViewer.prototype.configureObservers = function (observersConfiguration) {
  92087. if (observersConfiguration.onEngineInit) {
  92088. this.onEngineInitObservable.add(window[observersConfiguration.onEngineInit]);
  92089. }
  92090. else {
  92091. if (observersConfiguration.onEngineInit === '' && this.configuration.observers && this.configuration.observers.onEngineInit) {
  92092. this.onEngineInitObservable.removeCallback(window[this.configuration.observers.onEngineInit]);
  92093. }
  92094. }
  92095. if (observersConfiguration.onSceneInit) {
  92096. this.onSceneInitObservable.add(window[observersConfiguration.onSceneInit]);
  92097. }
  92098. else {
  92099. if (observersConfiguration.onSceneInit === '' && this.configuration.observers && this.configuration.observers.onSceneInit) {
  92100. this.onSceneInitObservable.removeCallback(window[this.configuration.observers.onSceneInit]);
  92101. }
  92102. }
  92103. if (observersConfiguration.onModelLoaded) {
  92104. this.onModelLoadedObservable.add(window[observersConfiguration.onModelLoaded]);
  92105. }
  92106. else {
  92107. if (observersConfiguration.onModelLoaded === '' && this.configuration.observers && this.configuration.observers.onModelLoaded) {
  92108. this.onModelLoadedObservable.removeCallback(window[this.configuration.observers.onModelLoaded]);
  92109. }
  92110. }
  92111. };
  92112. AbstractViewer.prototype.configureCamera = function (cameraConfig, model) {
  92113. var _this = this;
  92114. var focusMeshes = model ? model.meshes : this.scene.meshes;
  92115. if (!this.scene.activeCamera) {
  92116. this.scene.createDefaultCamera(true, true, true);
  92117. this.camera = this.scene.activeCamera;
  92118. }
  92119. if (cameraConfig.position) {
  92120. this.camera.position.copyFromFloats(cameraConfig.position.x || 0, cameraConfig.position.y || 0, cameraConfig.position.z || 0);
  92121. }
  92122. if (cameraConfig.rotation) {
  92123. this.camera.rotationQuaternion = new babylonjs_1.Quaternion(cameraConfig.rotation.x || 0, cameraConfig.rotation.y || 0, cameraConfig.rotation.z || 0, cameraConfig.rotation.w || 0);
  92124. }
  92125. this.extendClassWithConfig(this.camera, cameraConfig);
  92126. this.camera.minZ = cameraConfig.minZ || this.camera.minZ;
  92127. this.camera.maxZ = cameraConfig.maxZ || this.camera.maxZ;
  92128. if (cameraConfig.behaviors) {
  92129. for (var name_1 in cameraConfig.behaviors) {
  92130. this.setCameraBehavior(cameraConfig.behaviors[name_1], focusMeshes);
  92131. }
  92132. }
  92133. ;
  92134. var sceneExtends = this.scene.getWorldExtends(function (mesh) {
  92135. return !_this.environmentHelper || (mesh !== _this.environmentHelper.ground && mesh !== _this.environmentHelper.rootMesh && mesh !== _this.environmentHelper.skybox);
  92136. });
  92137. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  92138. var sceneDiagonalLenght = sceneDiagonal.length();
  92139. if (isFinite(sceneDiagonalLenght))
  92140. this.camera.upperRadiusLimit = sceneDiagonalLenght * 3;
  92141. };
  92142. AbstractViewer.prototype.configureLights = function (lightsConfiguration, model) {
  92143. var _this = this;
  92144. if (lightsConfiguration === void 0) { lightsConfiguration = {}; }
  92145. var focusMeshes = model ? model.meshes : this.scene.meshes;
  92146. if (!Object.keys(lightsConfiguration).length)
  92147. return;
  92148. var lightsAvailable = this.scene.lights.map(function (light) { return light.name; });
  92149. var lightsToConfigure = Object.keys(this.configuration.lights || []);
  92150. if (Object.keys(lightsToConfigure).length !== lightsAvailable.length) {
  92151. lightsAvailable.forEach(function (lName) {
  92152. if (lightsToConfigure.indexOf(lName) === -1) {
  92153. _this.scene.getLightByName(lName).dispose();
  92154. }
  92155. });
  92156. }
  92157. Object.keys(lightsConfiguration).forEach(function (name, idx) {
  92158. var lightConfig = { type: 0 };
  92159. if (typeof lightsConfiguration[name] === 'object') {
  92160. lightConfig = lightsConfiguration[name];
  92161. }
  92162. lightConfig.name = name;
  92163. var light;
  92164. if (lightsAvailable.indexOf(name) === -1) {
  92165. var constructor = babylonjs_1.Light.GetConstructorFromName(lightConfig.type, lightConfig.name, _this.scene);
  92166. if (!constructor)
  92167. return;
  92168. light = constructor();
  92169. }
  92170. else {
  92171. light = _this.scene.getLightByName(name);
  92172. lightsAvailable = lightsAvailable.filter(function (ln) { return ln !== name; });
  92173. if (lightConfig.type !== undefined && light.getTypeID() !== lightConfig.type) {
  92174. light.dispose();
  92175. var constructor = babylonjs_1.Light.GetConstructorFromName(lightConfig.type, lightConfig.name, _this.scene);
  92176. if (!constructor)
  92177. return;
  92178. light = constructor();
  92179. }
  92180. }
  92181. if (lightsConfiguration[name] === false) {
  92182. light.dispose();
  92183. return;
  92184. }
  92185. var enabled = lightConfig.enabled !== undefined ? lightConfig.enabled : !lightConfig.disabled;
  92186. light.setEnabled(enabled);
  92187. _this.extendClassWithConfig(light, lightConfig);
  92188. if (light instanceof babylonjs_1.ShadowLight) {
  92189. if (lightConfig.target) {
  92190. if (light.setDirectionToTarget) {
  92191. var target = babylonjs_1.Vector3.Zero().copyFrom(lightConfig.target);
  92192. light.setDirectionToTarget(target);
  92193. }
  92194. }
  92195. else if (lightConfig.direction) {
  92196. var direction = babylonjs_1.Vector3.Zero().copyFrom(lightConfig.direction);
  92197. light.direction = direction;
  92198. }
  92199. var shadowGenerator = light.getShadowGenerator();
  92200. if (lightConfig.shadowEnabled && _this.maxShadows) {
  92201. if (!shadowGenerator) {
  92202. shadowGenerator = new babylonjs_1.ShadowGenerator(512, light);
  92203. }
  92204. _this.extendClassWithConfig(shadowGenerator, lightConfig.shadowConfig || {});
  92205. var shadownMap = shadowGenerator.getShadowMap();
  92206. if (!shadownMap)
  92207. return;
  92208. var renderList = shadownMap.renderList;
  92209. for (var index = 0; index < focusMeshes.length; index++) {
  92210. if (babylonjs_1.Tags.MatchesQuery(focusMeshes[index], 'castShadow')) {
  92211. renderList && renderList.push(focusMeshes[index]);
  92212. }
  92213. }
  92214. }
  92215. else if (shadowGenerator) {
  92216. shadowGenerator.dispose();
  92217. }
  92218. }
  92219. });
  92220. };
  92221. AbstractViewer.prototype.configureModel = function (modelConfiguration, model) {
  92222. var focusMeshes = model ? model.meshes : this.scene.meshes;
  92223. var meshesWithNoParent = focusMeshes.filter(function (m) { return !m.parent; });
  92224. var updateMeshesWithNoParent = function (variable, value, param) {
  92225. meshesWithNoParent.forEach(function (mesh) {
  92226. if (param) {
  92227. mesh[variable][param] = value;
  92228. }
  92229. else {
  92230. mesh[variable] = value;
  92231. }
  92232. });
  92233. };
  92234. var updateXYZ = function (variable, configValues) {
  92235. if (configValues.x !== undefined) {
  92236. updateMeshesWithNoParent(variable, configValues.x, 'x');
  92237. }
  92238. if (configValues.y !== undefined) {
  92239. updateMeshesWithNoParent(variable, configValues.y, 'y');
  92240. }
  92241. if (configValues.z !== undefined) {
  92242. updateMeshesWithNoParent(variable, configValues.z, 'z');
  92243. }
  92244. if (configValues.w !== undefined) {
  92245. updateMeshesWithNoParent(variable, configValues.w, 'w');
  92246. }
  92247. };
  92248. if (modelConfiguration.position) {
  92249. updateXYZ('position', modelConfiguration.position);
  92250. }
  92251. if (modelConfiguration.rotation) {
  92252. if (modelConfiguration.rotation.w) {
  92253. meshesWithNoParent.forEach(function (mesh) {
  92254. if (!mesh.rotationQuaternion) {
  92255. mesh.rotationQuaternion = new babylonjs_1.Quaternion();
  92256. }
  92257. });
  92258. updateXYZ('rotationQuaternion', modelConfiguration.rotation);
  92259. }
  92260. else {
  92261. updateXYZ('rotation', modelConfiguration.rotation);
  92262. }
  92263. }
  92264. if (modelConfiguration.scaling) {
  92265. updateXYZ('scaling', modelConfiguration.scaling);
  92266. }
  92267. if (modelConfiguration.castShadow) {
  92268. focusMeshes.forEach(function (mesh) {
  92269. babylonjs_1.Tags.AddTagsTo(mesh, 'castShadow');
  92270. });
  92271. }
  92272. if (modelConfiguration.normalize) {
  92273. var center = false;
  92274. var unitSize = false;
  92275. var parentIndex = void 0;
  92276. if (modelConfiguration.normalize === true) {
  92277. center = true;
  92278. unitSize = true;
  92279. parentIndex = 0;
  92280. }
  92281. else {
  92282. center = !!modelConfiguration.normalize.center;
  92283. unitSize = !!modelConfiguration.normalize.unitSize;
  92284. parentIndex = modelConfiguration.normalize.parentIndex;
  92285. }
  92286. var meshesToNormalize = [];
  92287. if (parentIndex !== undefined) {
  92288. meshesToNormalize.push(focusMeshes[parentIndex]);
  92289. }
  92290. else {
  92291. meshesToNormalize = meshesWithNoParent;
  92292. }
  92293. if (unitSize) {
  92294. meshesToNormalize.forEach(function (mesh) {
  92295. mesh.normalizeToUnitCube(true);
  92296. mesh.computeWorldMatrix(true);
  92297. });
  92298. }
  92299. if (center) {
  92300. meshesToNormalize.forEach(function (mesh) {
  92301. var boundingInfo = mesh.getHierarchyBoundingVectors(true);
  92302. var sizeVec = boundingInfo.max.subtract(boundingInfo.min);
  92303. var halfSizeVec = sizeVec.scale(0.5);
  92304. var center = boundingInfo.min.add(halfSizeVec);
  92305. mesh.position = center.scale(-1);
  92306. mesh.position.y += halfSizeVec.y;
  92307. mesh.computeWorldMatrix(true);
  92308. });
  92309. }
  92310. }
  92311. };
  92312. AbstractViewer.prototype.dispose = function () {
  92313. window.removeEventListener('resize', this.resize);
  92314. if (this.sceneOptimizer) {
  92315. this.sceneOptimizer.stop();
  92316. this.sceneOptimizer.dispose();
  92317. }
  92318. if (this.scene.activeCamera) {
  92319. this.scene.activeCamera.detachControl(this.canvas);
  92320. }
  92321. this.scene.dispose();
  92322. this.engine.dispose();
  92323. this.templateManager.dispose();
  92324. };
  92325. AbstractViewer.prototype.onTemplatesLoaded = function () {
  92326. return Promise.resolve(this);
  92327. };
  92328. AbstractViewer.prototype._onTemplateLoaded = function () {
  92329. var _this = this;
  92330. return this.onTemplatesLoaded().then(function () {
  92331. var autoLoadModel = !!_this.configuration.model;
  92332. return _this.initEngine().then(function (engine) {
  92333. return _this.onEngineInitObservable.notifyObserversWithPromise(engine);
  92334. }).then(function () {
  92335. if (autoLoadModel) {
  92336. return _this.loadModel().then(function () { return _this.scene; });
  92337. }
  92338. else {
  92339. return _this.scene || _this.initScene();
  92340. }
  92341. }).then(function (scene) {
  92342. return _this.onSceneInitObservable.notifyObserversWithPromise(scene);
  92343. }).then(function () {
  92344. return _this.onInitDoneObservable.notifyObserversWithPromise(_this);
  92345. });
  92346. });
  92347. };
  92348. AbstractViewer.prototype.initEngine = function () {
  92349. this.injectCustomShaders();
  92350. var canvasElement = this.templateManager.getCanvas();
  92351. if (!canvasElement) {
  92352. return Promise.reject('Canvas element not found!');
  92353. }
  92354. var config = this.configuration.engine || {};
  92355. this.engine = new babylonjs_1.Engine(canvasElement, !!config.antialiasing, config.engineOptions);
  92356. babylonjs_1.Database.IDBStorageEnabled = false;
  92357. if (!config.disableResize) {
  92358. window.addEventListener('resize', this.resize);
  92359. }
  92360. this.engine.runRenderLoop(this.render);
  92361. if (this.configuration.engine && this.configuration.engine.adaptiveQuality) {
  92362. var scale = Math.max(0.5, 1 / (window.devicePixelRatio || 2));
  92363. this.engine.setHardwareScalingLevel(scale);
  92364. }
  92365. this.handleHardwareLimitations();
  92366. return Promise.resolve(this.engine);
  92367. };
  92368. AbstractViewer.prototype.initScene = function () {
  92369. if (this.scene) {
  92370. this.scene.dispose();
  92371. }
  92372. this.scene = new babylonjs_1.Scene(this.engine);
  92373. this.scene.createDefaultLight(true);
  92374. if (this.configuration.scene) {
  92375. this.configureScene(this.configuration.scene);
  92376. if (this.configuration.optimizer) {
  92377. this.configureOptimizer(this.configuration.optimizer);
  92378. }
  92379. }
  92380. return Promise.resolve(this.scene);
  92381. };
  92382. AbstractViewer.prototype.loadModel = function (modelConfig, clearScene) {
  92383. var _this = this;
  92384. if (modelConfig === void 0) { modelConfig = this.configuration.model; }
  92385. if (clearScene === void 0) { clearScene = true; }
  92386. var modelUrl = (typeof modelConfig === 'string') ? modelConfig : modelConfig.url;
  92387. if (!modelUrl) {
  92388. return Promise.reject("no model configuration found");
  92389. }
  92390. if (this.isLoading) {
  92391. return Promise.reject("sanother model is curently being loaded.");
  92392. }
  92393. this.isLoading = true;
  92394. if ((typeof modelConfig === 'string')) {
  92395. if (this.configuration.model && typeof this.configuration.model === 'object') {
  92396. this.configuration.model.url = modelConfig;
  92397. }
  92398. }
  92399. else {
  92400. if (this.configuration.model) {
  92401. deepmerge(this.configuration.model, modelConfig);
  92402. }
  92403. else {
  92404. this.configuration.model = modelConfig;
  92405. }
  92406. }
  92407. return Promise.resolve(this.scene).then(function (scene) {
  92408. if (!scene)
  92409. return _this.initScene();
  92410. if (clearScene) {
  92411. _this.models.forEach(function (m) { return m.dispose(); });
  92412. _this.models.length = 0;
  92413. }
  92414. return scene;
  92415. }).then(function () {
  92416. return new Promise(function (resolve, reject) {
  92417. var model = new viewerModel_1.ViewerModel(_this.configuration.model, _this.scene);
  92418. _this.models.push(model);
  92419. _this.lastUsedLoader = model.loader;
  92420. model.onLoadedObservable.add(function (model) {
  92421. resolve(model);
  92422. });
  92423. model.onLoadErrorObservable.add(function (errorObject) {
  92424. _this.onModelLoadErrorObservable.notifyObserversWithPromise(errorObject).then(function () {
  92425. reject(errorObject.exception);
  92426. });
  92427. });
  92428. model.onLoadProgressObservable.add(function (progressEvent) {
  92429. return _this.onModelLoadProgressObservable.notifyObserversWithPromise(progressEvent);
  92430. });
  92431. _this.onLoaderInitObservable.notifyObserversWithPromise(_this.lastUsedLoader);
  92432. });
  92433. }).then(function (model) {
  92434. return _this.onModelLoadedObservable.notifyObserversWithPromise(model)
  92435. .then(function () {
  92436. _this.configureModel(_this.configuration.model || modelConfig, model);
  92437. _this.configureLights(_this.configuration.lights);
  92438. if (_this.configuration.camera) {
  92439. _this.configureCamera(_this.configuration.camera, model);
  92440. }
  92441. return _this.initEnvironment(model);
  92442. }).then(function () {
  92443. _this.isLoading = false;
  92444. return model;
  92445. });
  92446. });
  92447. };
  92448. AbstractViewer.prototype.initEnvironment = function (model) {
  92449. this.configureEnvironment(this.configuration.skybox, this.configuration.ground);
  92450. return Promise.resolve(this.scene);
  92451. };
  92452. AbstractViewer.prototype.handleHardwareLimitations = function () {
  92453. var maxVaryingRows = this.engine.getCaps().maxVaryingVectors;
  92454. var maxFragmentSamplers = this.engine.getCaps().maxTexturesImageUnits;
  92455. if ((maxVaryingRows < 8) || (maxFragmentSamplers < 8)) {
  92456. this.maxShadows = 0;
  92457. }
  92458. else {
  92459. this.maxShadows = 3;
  92460. }
  92461. var caps = this.engine.getCaps();
  92462. var linearHalfFloatTargets = caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering;
  92463. var linearFloatTargets = caps.textureFloatRender && caps.textureFloatLinearFiltering;
  92464. this._hdrSupport = !!(linearFloatTargets || linearHalfFloatTargets);
  92465. if (linearHalfFloatTargets) {
  92466. this.defaultHighpTextureType = babylonjs_1.Engine.TEXTURETYPE_HALF_FLOAT;
  92467. this.shadowGeneratorBias = 0.002;
  92468. }
  92469. else if (linearFloatTargets) {
  92470. this.defaultHighpTextureType = babylonjs_1.Engine.TEXTURETYPE_FLOAT;
  92471. this.shadowGeneratorBias = 0.001;
  92472. }
  92473. else {
  92474. this.defaultHighpTextureType = babylonjs_1.Engine.TEXTURETYPE_UNSIGNED_INT;
  92475. this.shadowGeneratorBias = 0.001;
  92476. }
  92477. this.defaultPipelineTextureType = this._hdrSupport ? this.defaultHighpTextureType : babylonjs_1.Engine.TEXTURETYPE_UNSIGNED_INT;
  92478. };
  92479. AbstractViewer.prototype.injectCustomShaders = function () {
  92480. var customShaders = this.configuration.customShaders;
  92481. if (!customShaders) {
  92482. return;
  92483. }
  92484. if (customShaders.shaders) {
  92485. Object.keys(customShaders.shaders).forEach(function (key) {
  92486. babylonjs_1.Effect.ShadersStore[key] = customShaders.shaders[key];
  92487. });
  92488. }
  92489. if (customShaders.includes) {
  92490. Object.keys(customShaders.includes).forEach(function (key) {
  92491. babylonjs_1.Effect.IncludesShadersStore[key] = customShaders.includes[key];
  92492. });
  92493. }
  92494. };
  92495. AbstractViewer.prototype.extendClassWithConfig = function (object, config) {
  92496. var _this = this;
  92497. if (!config)
  92498. return;
  92499. Object.keys(config).forEach(function (key) {
  92500. if (key in object && typeof object[key] !== 'function') {
  92501. if (typeof object[key] === 'object') {
  92502. _this.extendClassWithConfig(object[key], config[key]);
  92503. }
  92504. else {
  92505. if (config[key] !== undefined) {
  92506. object[key] = config[key];
  92507. }
  92508. }
  92509. }
  92510. });
  92511. };
  92512. AbstractViewer.prototype.setCameraBehavior = function (behaviorConfig, payload) {
  92513. var behavior;
  92514. var type = (typeof behaviorConfig !== "object") ? behaviorConfig : behaviorConfig.type;
  92515. var config = (typeof behaviorConfig === "object") ? behaviorConfig : {};
  92516. switch (type) {
  92517. case 0:
  92518. this.camera.useAutoRotationBehavior = true;
  92519. behavior = this.camera.autoRotationBehavior;
  92520. break;
  92521. case 1:
  92522. this.camera.useBouncingBehavior = true;
  92523. behavior = this.camera.bouncingBehavior;
  92524. break;
  92525. case 2:
  92526. this.camera.useFramingBehavior = true;
  92527. behavior = this.camera.framingBehavior;
  92528. break;
  92529. default:
  92530. behavior = null;
  92531. break;
  92532. }
  92533. if (behavior) {
  92534. if (typeof behaviorConfig === "object") {
  92535. this.extendClassWithConfig(behavior, behaviorConfig);
  92536. }
  92537. }
  92538. switch (type) {
  92539. case 0:
  92540. break;
  92541. case 1:
  92542. break;
  92543. case 2:
  92544. if (config.zoomOnBoundingInfo) {
  92545. var meshes = payload;
  92546. var bounding = meshes[0].getHierarchyBoundingVectors();
  92547. behavior.zoomOnBoundingInfo(bounding.min, bounding.max);
  92548. }
  92549. break;
  92550. }
  92551. };
  92552. return AbstractViewer;
  92553. }());
  92554. exports.AbstractViewer = AbstractViewer;
  92555. /***/ }),
  92556. /* 6 */
  92557. /***/ (function(module, exports) {
  92558. module.exports = "<viewer></viewer> <loading-screen></loading-screen> <overlay></overlay>";
  92559. /***/ }),
  92560. /* 7 */
  92561. /***/ (function(module, exports) {
  92562. 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}}>";
  92563. /***/ }),
  92564. /* 8 */
  92565. /***/ (function(module, exports) {
  92566. 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=="
  92567. /***/ }),
  92568. /* 9 */
  92569. /***/ (function(module, exports) {
  92570. 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>";
  92571. /***/ }),
  92572. /* 10 */
  92573. /***/ (function(module, exports) {
  92574. 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>";
  92575. /***/ }),
  92576. /* 11 */
  92577. /***/ (function(module, exports) {
  92578. module.exports = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAQAAAD9CzEMAAAAt0lEQVR42u2WAQbDQBBFQ9IbRtDcrrqK3LBbXrEH6OuHEPMBjPd2xHyZKtdNpcLMg11Pr7y4/YdvwIdd4jtw4BU0Rjrbz9mNzkjzgpU3wNhCvH5M3i1fKzzeK3K8V+R4r8jxTpHjlULhc0WOd8fU6e4I8y3y13tFjHel4GswwAvFSR/ZN6Zv2gjvmzbGhwqPzxUenys83is8Pld4vFac/9sy8/SVNrbgYJl8WGhsvkpoA1+pVK6ZLyLNXm2txsT5AAAAAElFTkSuQmCC"
  92579. /***/ }),
  92580. /* 12 */
  92581. /***/ (function(module, exports) {
  92582. module.exports = "Error loading the model";
  92583. /***/ }),
  92584. /* 13 */
  92585. /***/ (function(module, exports, __webpack_require__) {
  92586. (function (global, factory) {
  92587. true ? module.exports = factory() :
  92588. typeof define === 'function' && define.amd ? define(factory) :
  92589. (global.deepmerge = factory());
  92590. }(this, (function () { 'use strict';
  92591. var isMergeableObject = function isMergeableObject(value) {
  92592. return isNonNullObject(value)
  92593. && !isSpecial(value)
  92594. };
  92595. function isNonNullObject(value) {
  92596. return !!value && typeof value === 'object'
  92597. }
  92598. function isSpecial(value) {
  92599. var stringValue = Object.prototype.toString.call(value);
  92600. return stringValue === '[object RegExp]'
  92601. || stringValue === '[object Date]'
  92602. || isReactElement(value)
  92603. }
  92604. // see https://github.com/facebook/react/blob/b5ac963fb791d1298e7f396236383bc955f916c1/src/isomorphic/classic/element/ReactElement.js#L21-L25
  92605. var canUseSymbol = typeof Symbol === 'function' && Symbol.for;
  92606. var REACT_ELEMENT_TYPE = canUseSymbol ? Symbol.for('react.element') : 0xeac7;
  92607. function isReactElement(value) {
  92608. return value.$$typeof === REACT_ELEMENT_TYPE
  92609. }
  92610. function emptyTarget(val) {
  92611. return Array.isArray(val) ? [] : {}
  92612. }
  92613. function cloneUnlessOtherwiseSpecified(value, optionsArgument) {
  92614. var clone = !optionsArgument || optionsArgument.clone !== false;
  92615. return (clone && isMergeableObject(value))
  92616. ? deepmerge(emptyTarget(value), value, optionsArgument)
  92617. : value
  92618. }
  92619. function defaultArrayMerge(target, source, optionsArgument) {
  92620. return target.concat(source).map(function(element) {
  92621. return cloneUnlessOtherwiseSpecified(element, optionsArgument)
  92622. })
  92623. }
  92624. function mergeObject(target, source, optionsArgument) {
  92625. var destination = {};
  92626. if (isMergeableObject(target)) {
  92627. Object.keys(target).forEach(function(key) {
  92628. destination[key] = cloneUnlessOtherwiseSpecified(target[key], optionsArgument);
  92629. });
  92630. }
  92631. Object.keys(source).forEach(function(key) {
  92632. if (!isMergeableObject(source[key]) || !target[key]) {
  92633. destination[key] = cloneUnlessOtherwiseSpecified(source[key], optionsArgument);
  92634. } else {
  92635. destination[key] = deepmerge(target[key], source[key], optionsArgument);
  92636. }
  92637. });
  92638. return destination
  92639. }
  92640. function deepmerge(target, source, optionsArgument) {
  92641. var sourceIsArray = Array.isArray(source);
  92642. var targetIsArray = Array.isArray(target);
  92643. var options = optionsArgument || { arrayMerge: defaultArrayMerge };
  92644. var sourceAndTargetTypesMatch = sourceIsArray === targetIsArray;
  92645. if (!sourceAndTargetTypesMatch) {
  92646. return cloneUnlessOtherwiseSpecified(source, optionsArgument)
  92647. } else if (sourceIsArray) {
  92648. var arrayMerge = options.arrayMerge || defaultArrayMerge;
  92649. return arrayMerge(target, source, optionsArgument)
  92650. } else {
  92651. return mergeObject(target, source, optionsArgument)
  92652. }
  92653. }
  92654. deepmerge.all = function deepmergeAll(array, optionsArgument) {
  92655. if (!Array.isArray(array)) {
  92656. throw new Error('first argument should be an array')
  92657. }
  92658. return array.reduce(function(prev, next) {
  92659. return deepmerge(prev, next, optionsArgument)
  92660. }, {})
  92661. };
  92662. var deepmerge_1 = deepmerge;
  92663. return deepmerge_1;
  92664. })));
  92665. /***/ }),
  92666. /* 14 */
  92667. /***/ (function(module, exports, __webpack_require__) {
  92668. module.exports = __webpack_require__(15);
  92669. /***/ }),
  92670. /* 15 */
  92671. /***/ (function(module, exports, __webpack_require__) {
  92672. "use strict";
  92673. Object.defineProperty(exports, "__esModule", { value: true });
  92674. var mappers_1 = __webpack_require__(1);
  92675. exports.mapperManager = mappers_1.mapperManager;
  92676. var viewerManager_1 = __webpack_require__(3);
  92677. exports.viewerManager = viewerManager_1.viewerManager;
  92678. var defaultViewer_1 = __webpack_require__(4);
  92679. exports.DefaultViewer = defaultViewer_1.DefaultViewer;
  92680. var viewer_1 = __webpack_require__(5);
  92681. exports.AbstractViewer = viewer_1.AbstractViewer;
  92682. var babylonjs_1 = __webpack_require__(0);
  92683. __webpack_require__(32);
  92684. __webpack_require__(33);
  92685. var initializer_1 = __webpack_require__(34);
  92686. exports.InitTags = initializer_1.InitTags;
  92687. babylonjs_1.PromisePolyfill.Apply();
  92688. exports.disableInit = false;
  92689. document.addEventListener("DOMContentLoaded", function (event) {
  92690. if (exports.disableInit)
  92691. return;
  92692. initializer_1.InitTags();
  92693. });
  92694. /***/ }),
  92695. /* 16 */
  92696. /***/ (function(module, exports) {
  92697. var g;
  92698. // This works in non-strict mode
  92699. g = (function() {
  92700. return this;
  92701. })();
  92702. try {
  92703. // This works if eval is allowed (see CSP)
  92704. g = g || Function("return this")() || (1,eval)("this");
  92705. } catch(e) {
  92706. // This works if the window reference is available
  92707. if(typeof window === "object")
  92708. g = window;
  92709. }
  92710. // g can still be undefined, but nothing to do about it...
  92711. // We return undefined, instead of nothing here, so it's
  92712. // easier to handle this case. if(!global) { ...}
  92713. module.exports = g;
  92714. /***/ }),
  92715. /* 17 */
  92716. /***/ (function(module, exports) {
  92717. module.exports = cannon;
  92718. /***/ }),
  92719. /* 18 */
  92720. /***/ (function(module, exports, __webpack_require__) {
  92721. /**
  92722. * from OimoPhysics DEV 1.1.0a AS3
  92723. * @author Saharan / http://el-ement.com/
  92724. *
  92725. * to Oimo.js 2015 JAVASCRIPT
  92726. * @author LoTh / http://lo-th.github.io/labs/
  92727. */
  92728. var OIMO = {
  92729. REVISION: "1.2",
  92730. // Global identification of next shape.
  92731. // This will be incremented every time a shape is created.
  92732. nextID: 0,
  92733. proxyID: 0,
  92734. // BroadPhase
  92735. BR_NULL: 0,
  92736. BR_BRUTE_FORCE: 1,
  92737. BR_SWEEP_AND_PRUNE: 2,
  92738. BR_BOUNDING_VOLUME_TREE: 3,
  92739. // body type
  92740. BODY_NULL: 0,
  92741. BODY_DYNAMIC: 1,
  92742. BODY_STATIC: 2,
  92743. // shape type
  92744. SHAPE_NULL: 0,
  92745. SHAPE_SPHERE: 1,
  92746. SHAPE_BOX: 2,
  92747. SHAPE_CYLINDER: 3,
  92748. SHAPE_TETRA: 4,
  92749. // joint type
  92750. JOINT_NULL: 0,
  92751. JOINT_DISTANCE: 1,
  92752. JOINT_BALL_AND_SOCKET: 2,
  92753. JOINT_HINGE: 3,
  92754. JOINT_WHEEL: 4,
  92755. JOINT_SLIDER: 5,
  92756. JOINT_PRISMATIC: 6,
  92757. // this world scale defaut is 0.1 to 10 meters max for dynamique body
  92758. // scale all by 100 so object is between 10 to 10000 three unit.
  92759. WORLD_SCALE: 100,
  92760. INV_SCALE: 0.01,
  92761. // AABB aproximation
  92762. AABB_PROX: 0.005,
  92763. // Math function
  92764. sqrt: Math.sqrt,
  92765. abs: Math.abs,
  92766. floor: Math.floor,
  92767. cos: Math.cos,
  92768. sin: Math.sin,
  92769. acos: Math.acos,
  92770. asin: Math.asin,
  92771. atan2: Math.atan2,
  92772. round: Math.round,
  92773. pow: Math.pow,
  92774. max: Math.max,
  92775. min: Math.min,
  92776. random: Math.random,
  92777. lerp: function (a, b, percent) { return a + (b - a) * percent; },
  92778. rand: function (a, b) { return OIMO.lerp(a, b, OIMO.random()); },
  92779. randInt: function (a, b, n) { return OIMO.lerp(a, b, OIMO.random()).toFixed(n || 0) * 1; },
  92780. int: function (x) { return ~~x; },
  92781. fix: function (x, n) { return x.toFixed(n || 3, 10); },
  92782. clamp: function (value, min, max) { return OIMO.max(min, OIMO.min(max, value)); },
  92783. degtorad: 0.0174532925199432957,
  92784. radtodeg: 57.295779513082320876,
  92785. PI: 3.141592653589793,
  92786. TwoPI: 6.283185307179586,
  92787. PI90: 1.570796326794896,
  92788. PI270: 4.712388980384689,
  92789. CustomError: null,
  92790. Error: function (Class, Msg) {
  92791. if (OIMO.CustomError == null) console.error(Class, Msg);
  92792. else OIMO.CustomError.innerHTML += Class + " - " + Msg + '<br>';
  92793. }
  92794. };
  92795. var OIMO_ARRAY_TYPE;
  92796. if (!OIMO_ARRAY_TYPE) { OIMO_ARRAY_TYPE = typeof Float32Array !== 'undefined' ? Float32Array : Array; }
  92797. try {
  92798. (function (w) {
  92799. var perfNow;
  92800. var perfNowNames = ['now', 'webkitNow', 'msNow', 'mozNow'];
  92801. if (!!w['performance']) for (var i = 0; i < perfNowNames.length; ++i) {
  92802. var n = perfNowNames[i];
  92803. if (!!w['performance'][n]) {
  92804. perfNow = function () { return w['performance'][n]() };
  92805. break;
  92806. }
  92807. }
  92808. if (!perfNow) perfNow = Date.now;
  92809. //w.perfNow = perfNow;
  92810. OIMO.now = perfNow;
  92811. })(window);
  92812. } catch (e) { OIMO.now = function () { return 0; }; }
  92813. /**
  92814. * The class of physical computing world.
  92815. * You must be added to the world physical all computing objects
  92816. * @author saharan
  92817. * @author lo-th
  92818. */
  92819. OIMO.World = function (TimeStep, BroadPhaseType, Iterations, NoStat) {
  92820. // The time between each step
  92821. this.timeStep = TimeStep || 0.01666; // 1/60;
  92822. // The number of iterations for constraint solvers.
  92823. this.numIterations = Iterations || 8;
  92824. // It is a wide-area collision judgment that is used in order to reduce as much as possible a detailed collision judgment.
  92825. switch (BroadPhaseType || 2) {
  92826. case 1: this.broadPhase = new OIMO.BruteForceBroadPhase(); break;
  92827. case 2: default: this.broadPhase = new OIMO.SAPBroadPhase(); break;
  92828. case 3: this.broadPhase = new OIMO.DBVTBroadPhase(); break;
  92829. }
  92830. // This is the detailed information of the performance.
  92831. this.performance = null;
  92832. this.isNoStat = NoStat || false;
  92833. if (!this.isNoStat) this.performance = new OIMO.Performance(this);
  92834. // Whether the constraints randomizer is enabled or not.
  92835. this.enableRandomizer = true;
  92836. // The rigid body list
  92837. this.rigidBodies = null;
  92838. // number of rigid body
  92839. this.numRigidBodies = 0;
  92840. // The contact list
  92841. this.contacts = null;
  92842. this.unusedContacts = null;
  92843. // The number of contact
  92844. this.numContacts = 0;
  92845. // The number of contact points
  92846. this.numContactPoints = 0;
  92847. // The joint list
  92848. this.joints = null;
  92849. // The number of joints.
  92850. this.numJoints = 0;
  92851. // The number of simulation islands.
  92852. this.numIslands = 0;
  92853. // The gravity in the world.
  92854. this.gravity = new OIMO.Vec3(0, -9.80665, 0);
  92855. var numShapeTypes = 5;//4;//3;
  92856. this.detectors = [];
  92857. this.detectors.length = numShapeTypes;
  92858. var i = numShapeTypes;
  92859. while (i--) {
  92860. this.detectors[i] = [];
  92861. this.detectors[i].length = numShapeTypes;
  92862. }
  92863. this.detectors[OIMO.SHAPE_SPHERE][OIMO.SHAPE_SPHERE] = new OIMO.SphereSphereCollisionDetector();
  92864. this.detectors[OIMO.SHAPE_SPHERE][OIMO.SHAPE_BOX] = new OIMO.SphereBoxCollisionDetector(false);
  92865. this.detectors[OIMO.SHAPE_BOX][OIMO.SHAPE_SPHERE] = new OIMO.SphereBoxCollisionDetector(true);
  92866. this.detectors[OIMO.SHAPE_BOX][OIMO.SHAPE_BOX] = new OIMO.BoxBoxCollisionDetector();
  92867. // CYLINDER add
  92868. this.detectors[OIMO.SHAPE_CYLINDER][OIMO.SHAPE_CYLINDER] = new OIMO.CylinderCylinderCollisionDetector();
  92869. this.detectors[OIMO.SHAPE_CYLINDER][OIMO.SHAPE_BOX] = new OIMO.BoxCylinderCollisionDetector(true);
  92870. this.detectors[OIMO.SHAPE_BOX][OIMO.SHAPE_CYLINDER] = new OIMO.BoxCylinderCollisionDetector(false);
  92871. this.detectors[OIMO.SHAPE_CYLINDER][OIMO.SHAPE_SPHERE] = new OIMO.SphereCylinderCollisionDetector(true);
  92872. this.detectors[OIMO.SHAPE_SPHERE][OIMO.SHAPE_CYLINDER] = new OIMO.SphereCylinderCollisionDetector(false);
  92873. // TETRA add
  92874. this.detectors[OIMO.SHAPE_TETRA][OIMO.SHAPE_TETRA] = new OIMO.TetraTetraCollisionDetector();
  92875. this.randX = 65535;
  92876. this.randA = 98765;
  92877. this.randB = 123456789;
  92878. //this.maxIslandRigidBodies = 64;
  92879. this.islandRigidBodies = [];
  92880. //this.islandRigidBodies.length = this.maxIslandRigidBodies;
  92881. this.islandStack = [];
  92882. //this.islandStack.length = this.maxIslandRigidBodies;
  92883. //this.maxIslandConstraints = 128;
  92884. this.islandConstraints = [];
  92885. //this.islandConstraints.length = this.maxIslandConstraints;
  92886. };
  92887. OIMO.World.prototype = {
  92888. constructor: OIMO.World,
  92889. /**
  92890. * Reset the randomizer and remove all rigid bodies, shapes, joints and any object from the world.
  92891. */
  92892. clear: function () {
  92893. this.randX = 65535;
  92894. while (this.joints !== null) {
  92895. this.removeJoint(this.joints);
  92896. }
  92897. while (this.contacts !== null) {
  92898. this.removeContact(this.contacts);
  92899. }
  92900. while (this.rigidBodies !== null) {
  92901. this.removeRigidBody(this.rigidBodies);
  92902. }
  92903. OIMO.nextID = 0;
  92904. OIMO.proxyID = 0;
  92905. },
  92906. /**
  92907. * I'll add a rigid body to the world.
  92908. * Rigid body that has been added will be the operands of each step.
  92909. * @param rigidBody Rigid body that you want to add
  92910. */
  92911. addRigidBody: function (rigidBody) {
  92912. if (rigidBody.parent) {
  92913. OIMO.Error("World", "It is not possible to be added to more than one world one of the rigid body");
  92914. }
  92915. rigidBody.parent = this;
  92916. rigidBody.awake();
  92917. for (var shape = rigidBody.shapes; shape !== null; shape = shape.next) {
  92918. this.addShape(shape);
  92919. }
  92920. if (this.rigidBodies !== null) (this.rigidBodies.prev = rigidBody).next = this.rigidBodies;
  92921. this.rigidBodies = rigidBody;
  92922. this.numRigidBodies++;
  92923. },
  92924. /**
  92925. * I will remove the rigid body from the world.
  92926. * Rigid body that has been deleted is excluded from the calculation on a step-by-step basis.
  92927. * @param rigidBody Rigid body to be removed
  92928. */
  92929. removeRigidBody: function (rigidBody) {
  92930. var remove = rigidBody;
  92931. if (remove.parent !== this) return;
  92932. remove.awake();
  92933. var js = remove.jointLink;
  92934. while (js != null) {
  92935. var joint = js.joint;
  92936. js = js.next;
  92937. this.removeJoint(joint);
  92938. }
  92939. for (var shape = rigidBody.shapes; shape !== null; shape = shape.next) {
  92940. this.removeShape(shape);
  92941. }
  92942. var prev = remove.prev;
  92943. var next = remove.next;
  92944. if (prev !== null) prev.next = next;
  92945. if (next !== null) next.prev = prev;
  92946. if (this.rigidBodies == remove) this.rigidBodies = next;
  92947. remove.prev = null;
  92948. remove.next = null;
  92949. remove.parent = null;
  92950. this.numRigidBodies--;
  92951. },
  92952. getByName: function (name) {
  92953. var result = null;
  92954. var body = this.rigidBodies;
  92955. while (body !== null) {
  92956. if (body.name !== " " && body.name === name) result = body;
  92957. body = body.next;
  92958. }
  92959. var joint = this.joints;
  92960. while (joint !== null) {
  92961. if (joint.name !== "" && joint.name === name) result = joint;
  92962. joint = joint.next;
  92963. }
  92964. return result;
  92965. },
  92966. /**
  92967. * I'll add a shape to the world..
  92968. * Add to the rigid world, and if you add a shape to a rigid body that has been added to the world,
  92969. * Shape will be added to the world automatically, please do not call from outside this method.
  92970. * @param shape Shape you want to add
  92971. */
  92972. addShape: function (shape) {
  92973. if (!shape.parent || !shape.parent.parent) {
  92974. OIMO.Error("World", "It is not possible to be added alone to shape world");
  92975. }
  92976. shape.proxy = this.broadPhase.createProxy(shape);
  92977. shape.updateProxy();
  92978. this.broadPhase.addProxy(shape.proxy);
  92979. },
  92980. /**
  92981. * I will remove the shape from the world.
  92982. * Add to the rigid world, and if you add a shape to a rigid body that has been added to the world,
  92983. * Shape will be added to the world automatically, please do not call from outside this method.
  92984. * @param shape Shape you want to delete
  92985. */
  92986. removeShape: function (shape) {
  92987. this.broadPhase.removeProxy(shape.proxy);
  92988. shape.proxy = null;
  92989. },
  92990. /**
  92991. * I'll add a joint to the world.
  92992. * Joint that has been added will be the operands of each step.
  92993. * @param shape Joint to be added
  92994. */
  92995. addJoint: function (joint) {
  92996. if (joint.parent) {
  92997. OIMO.Error("World", "It is not possible to be added to more than one world one of the joint");
  92998. }
  92999. if (this.joints != null) (this.joints.prev = joint).next = this.joints;
  93000. this.joints = joint;
  93001. joint.parent = this;
  93002. this.numJoints++;
  93003. joint.awake();
  93004. joint.attach();
  93005. },
  93006. /**
  93007. * I will remove the joint from the world.
  93008. * Joint that has been added will be the operands of each step.
  93009. * @param shape Joint to be deleted
  93010. */
  93011. removeJoint: function (joint) {
  93012. var remove = joint;
  93013. var prev = remove.prev;
  93014. var next = remove.next;
  93015. if (prev !== null) prev.next = next;
  93016. if (next !== null) next.prev = prev;
  93017. if (this.joints == remove) this.joints = next;
  93018. remove.prev = null;
  93019. remove.next = null;
  93020. this.numJoints--;
  93021. remove.awake();
  93022. remove.detach();
  93023. remove.parent = null;
  93024. },
  93025. worldscale: function (scale) {
  93026. OIMO.WORLD_SCALE = scale || 100;
  93027. OIMO.INV_SCALE = 1 / OIMO.WORLD_SCALE;
  93028. },
  93029. addContact: function (s1, s2) {
  93030. var newContact;
  93031. if (this.unusedContacts !== null) {
  93032. newContact = this.unusedContacts;
  93033. this.unusedContacts = this.unusedContacts.next;
  93034. } else {
  93035. newContact = new OIMO.Contact();
  93036. }
  93037. newContact.attach(s1, s2);
  93038. newContact.detector = this.detectors[s1.type][s2.type];
  93039. if (this.contacts) (this.contacts.prev = newContact).next = this.contacts;
  93040. this.contacts = newContact;
  93041. this.numContacts++;
  93042. },
  93043. removeContact: function (contact) {
  93044. var prev = contact.prev;
  93045. var next = contact.next;
  93046. if (next) next.prev = prev;
  93047. if (prev) prev.next = next;
  93048. if (this.contacts == contact) this.contacts = next;
  93049. contact.prev = null;
  93050. contact.next = null;
  93051. contact.detach();
  93052. contact.next = this.unusedContacts;
  93053. this.unusedContacts = contact;
  93054. this.numContacts--;
  93055. },
  93056. checkContact: function (name1, name2) {
  93057. var n1, n2;
  93058. var contact = this.contacts;
  93059. while (contact !== null) {
  93060. n1 = contact.body1.name || ' ';
  93061. n2 = contact.body2.name || ' ';
  93062. if ((n1 == name1 && n2 == name2) || (n2 == name1 && n1 == name2)) { if (contact.touching) return true; else return false; }
  93063. else contact = contact.next;
  93064. }
  93065. return false;
  93066. },
  93067. callSleep: function (body) {
  93068. if (!body.allowSleep) return false;
  93069. if (body.linearVelocity.lengthSq() > 0.04) return false;
  93070. if (body.angularVelocity.lengthSq() > 0.25) return false;
  93071. return true;
  93072. },
  93073. /**
  93074. * I will proceed only time step seconds time of World.
  93075. */
  93076. step: function () {
  93077. var time0, time1, time2, time3;
  93078. var stat = !this.isNoStat ? true : false;
  93079. if (stat) time0 = OIMO.now();
  93080. var body = this.rigidBodies;
  93081. while (body !== null) {
  93082. body.addedToIsland = false;
  93083. if (body.sleeping) {
  93084. if (
  93085. body.linearVelocity.testZero() ||
  93086. body.angularVelocity.testZero() ||
  93087. body.position.testDiff(body.sleepPosition) ||
  93088. body.orientation.testDiff(body.sleepOrientation)
  93089. ) body.awake(); // awake the body
  93090. }
  93091. body = body.next;
  93092. }
  93093. //------------------------------------------------------
  93094. // UPDATE CONTACT
  93095. //------------------------------------------------------
  93096. // broad phase
  93097. if (stat) time1 = OIMO.now();
  93098. this.broadPhase.detectPairs();
  93099. var pairs = this.broadPhase.pairs;
  93100. var i = this.broadPhase.numPairs;
  93101. //do{
  93102. while (i--) {
  93103. //for(var i=0, l=numPairs; i<l; i++){
  93104. var pair = pairs[i];
  93105. var s1;
  93106. var s2;
  93107. if (pair.shape1.id < pair.shape2.id) {
  93108. s1 = pair.shape1;
  93109. s2 = pair.shape2;
  93110. } else {
  93111. s1 = pair.shape2;
  93112. s2 = pair.shape1;
  93113. }
  93114. var link;
  93115. if (s1.numContacts < s2.numContacts) link = s1.contactLink;
  93116. else link = s2.contactLink;
  93117. var exists = false;
  93118. while (link) {
  93119. var contact = link.contact;
  93120. if (contact.shape1 == s1 && contact.shape2 == s2) {
  93121. contact.persisting = true;
  93122. exists = true;// contact already exists
  93123. break;
  93124. }
  93125. link = link.next;
  93126. }
  93127. if (!exists) {
  93128. this.addContact(s1, s2);
  93129. }
  93130. }// while(i-- >0);
  93131. if (stat) {
  93132. time2 = OIMO.now();
  93133. this.performance.broadPhaseTime = time2 - time1;
  93134. }
  93135. // update & narrow phase
  93136. this.numContactPoints = 0;
  93137. contact = this.contacts;
  93138. while (contact !== null) {
  93139. if (!contact.persisting) {
  93140. if (contact.shape1.aabb.intersectTest(contact.shape2.aabb)) {
  93141. /*var aabb1=contact.shape1.aabb;
  93142. var aabb2=contact.shape2.aabb;
  93143. if(
  93144. aabb1.minX>aabb2.maxX || aabb1.maxX<aabb2.minX ||
  93145. aabb1.minY>aabb2.maxY || aabb1.maxY<aabb2.minY ||
  93146. aabb1.minZ>aabb2.maxZ || aabb1.maxZ<aabb2.minZ
  93147. ){*/
  93148. var next = contact.next;
  93149. this.removeContact(contact);
  93150. contact = next;
  93151. continue;
  93152. }
  93153. }
  93154. var b1 = contact.body1;
  93155. var b2 = contact.body2;
  93156. if (b1.isDynamic && !b1.sleeping || b2.isDynamic && !b2.sleeping) {
  93157. contact.updateManifold();
  93158. }
  93159. this.numContactPoints += contact.manifold.numPoints;
  93160. contact.persisting = false;
  93161. contact.constraint.addedToIsland = false;
  93162. contact = contact.next;
  93163. }
  93164. if (stat) {
  93165. time3 = OIMO.now();
  93166. this.performance.narrowPhaseTime = time3 - time2;
  93167. }
  93168. //------------------------------------------------------
  93169. // SOLVE ISLANDS
  93170. //------------------------------------------------------
  93171. var invTimeStep = 1 / this.timeStep;
  93172. //var body;
  93173. var joint;
  93174. var constraint;
  93175. //var num;
  93176. for (joint = this.joints; joint !== null; joint = joint.next) {
  93177. joint.addedToIsland = false;
  93178. }
  93179. // clear old island array
  93180. this.islandRigidBodies = [];
  93181. this.islandConstraints = [];
  93182. this.islandStack = [];
  93183. // expand island buffers
  93184. /*if(this.maxIslandRigidBodies<this.numRigidBodies){
  93185. this.maxIslandRigidBodies=this.numRigidBodies<<1;
  93186. //this.maxIslandRigidBodies=this.numRigidBodies*2;
  93187. this.islandRigidBodies=[];
  93188. this.islandStack=[];
  93189. this.islandRigidBodies.length = this.maxIslandRigidBodies;
  93190. this.islandStack.length = this.maxIslandRigidBodies;
  93191. }
  93192. var numConstraints=this.numJoints+this.numContacts;
  93193. if(this.maxIslandConstraints<numConstraints){
  93194. this.maxIslandConstraints=numConstraints<<1;
  93195. //this.maxIslandConstraints=numConstraints*2;
  93196. this.islandConstraints=[];
  93197. this.islandConstraints.length = this.maxIslandConstraints;
  93198. }*/
  93199. time1 = OIMO.now();
  93200. this.numIslands = 0;
  93201. // build and solve simulation islands
  93202. for (var base = this.rigidBodies; base !== null; base = base.next) {
  93203. if (base.addedToIsland || base.isStatic || base.sleeping) continue;// ignore
  93204. if (base.isLonely()) {// update single body
  93205. if (base.isDynamic) {
  93206. base.linearVelocity.addTime(this.gravity, this.timeStep);
  93207. /*base.linearVelocity.x+=this.gravity.x*this.timeStep;
  93208. base.linearVelocity.y+=this.gravity.y*this.timeStep;
  93209. base.linearVelocity.z+=this.gravity.z*this.timeStep;*/
  93210. }
  93211. if (this.callSleep(base)) {
  93212. base.sleepTime += this.timeStep;
  93213. if (base.sleepTime > 0.5) base.sleep();
  93214. else base.updatePosition(this.timeStep);
  93215. } else {
  93216. base.sleepTime = 0;
  93217. base.updatePosition(this.timeStep);
  93218. }
  93219. this.numIslands++;
  93220. continue;
  93221. }
  93222. var islandNumRigidBodies = 0;
  93223. var islandNumConstraints = 0;
  93224. var stackCount = 1;
  93225. // add rigid body to stack
  93226. this.islandStack[0] = base;
  93227. base.addedToIsland = true;
  93228. // build an island
  93229. do {
  93230. // get rigid body from stack
  93231. body = this.islandStack[--stackCount];
  93232. this.islandStack[stackCount] = null;
  93233. body.sleeping = false;
  93234. // add rigid body to the island
  93235. this.islandRigidBodies[islandNumRigidBodies++] = body;
  93236. if (body.isStatic) continue;
  93237. // search connections
  93238. for (var cs = body.contactLink; cs !== null; cs = cs.next) {
  93239. var contact = cs.contact;
  93240. constraint = contact.constraint;
  93241. if (constraint.addedToIsland || !contact.touching) continue;// ignore
  93242. // add constraint to the island
  93243. this.islandConstraints[islandNumConstraints++] = constraint;
  93244. constraint.addedToIsland = true;
  93245. var next = cs.body;
  93246. if (next.addedToIsland) continue;
  93247. // add rigid body to stack
  93248. this.islandStack[stackCount++] = next;
  93249. next.addedToIsland = true;
  93250. }
  93251. for (var js = body.jointLink; js !== null; js = js.next) {
  93252. constraint = js.joint;
  93253. if (constraint.addedToIsland) continue;// ignore
  93254. // add constraint to the island
  93255. this.islandConstraints[islandNumConstraints++] = constraint;
  93256. constraint.addedToIsland = true;
  93257. next = js.body;
  93258. if (next.addedToIsland || !next.isDynamic) continue;
  93259. // add rigid body to stack
  93260. this.islandStack[stackCount++] = next;
  93261. next.addedToIsland = true;
  93262. }
  93263. } while (stackCount != 0);
  93264. // update velocities
  93265. var gVel = new OIMO.Vec3().addTime(this.gravity, this.timeStep);
  93266. /*var gx=this.gravity.x*this.timeStep;
  93267. var gy=this.gravity.y*this.timeStep;
  93268. var gz=this.gravity.z*this.timeStep;*/
  93269. var j = islandNumRigidBodies;
  93270. while (j--) {
  93271. //or(var j=0, l=islandNumRigidBodies; j<l; j++){
  93272. body = this.islandRigidBodies[j];
  93273. if (body.isDynamic) {
  93274. body.linearVelocity.addEqual(gVel);
  93275. /*body.linearVelocity.x+=gx;
  93276. body.linearVelocity.y+=gy;
  93277. body.linearVelocity.z+=gz;*/
  93278. }
  93279. }
  93280. // randomizing order
  93281. if (this.enableRandomizer) {
  93282. //for(var j=1, l=islandNumConstraints; j<l; j++){
  93283. j = islandNumConstraints;
  93284. while (j--) {
  93285. if (j !== 0) {
  93286. var swap = (this.randX = (this.randX * this.randA + this.randB & 0x7fffffff)) / 2147483648.0 * j | 0;
  93287. constraint = this.islandConstraints[j];
  93288. this.islandConstraints[j] = this.islandConstraints[swap];
  93289. this.islandConstraints[swap] = constraint;
  93290. }
  93291. }
  93292. }
  93293. // solve contraints
  93294. j = islandNumConstraints;
  93295. while (j--) {
  93296. //for(j=0, l=islandNumConstraints; j<l; j++){
  93297. this.islandConstraints[j].preSolve(this.timeStep, invTimeStep);// pre-solve
  93298. }
  93299. var k = this.numIterations;
  93300. while (k--) {
  93301. //for(var k=0, l=this.numIterations; k<l; k++){
  93302. j = islandNumConstraints;
  93303. while (j--) {
  93304. //for(j=0, m=islandNumConstraints; j<m; j++){
  93305. this.islandConstraints[j].solve();// main-solve
  93306. }
  93307. }
  93308. j = islandNumConstraints;
  93309. while (j--) {
  93310. //for(j=0, l=islandNumConstraints; j<l; j++){
  93311. this.islandConstraints[j].postSolve();// post-solve
  93312. this.islandConstraints[j] = null;// gc
  93313. }
  93314. // sleeping check
  93315. var sleepTime = 10;
  93316. j = islandNumRigidBodies;
  93317. while (j--) {
  93318. //for(j=0, l=islandNumRigidBodies;j<l;j++){
  93319. body = this.islandRigidBodies[j];
  93320. if (this.callSleep(body)) {
  93321. body.sleepTime += this.timeStep;
  93322. if (body.sleepTime < sleepTime) sleepTime = body.sleepTime;
  93323. } else {
  93324. body.sleepTime = 0;
  93325. sleepTime = 0;
  93326. continue;
  93327. }
  93328. }
  93329. if (sleepTime > 0.5) {
  93330. // sleep the island
  93331. j = islandNumRigidBodies;
  93332. while (j--) {
  93333. //for(j=0, l=islandNumRigidBodies;j<l;j++){
  93334. this.islandRigidBodies[j].sleep();
  93335. this.islandRigidBodies[j] = null;// gc
  93336. }
  93337. } else {
  93338. // update positions
  93339. j = islandNumRigidBodies;
  93340. while (j--) {
  93341. //for(j=0, l=islandNumRigidBodies;j<l;j++){
  93342. this.islandRigidBodies[j].updatePosition(this.timeStep);
  93343. this.islandRigidBodies[j] = null;// gc
  93344. }
  93345. }
  93346. this.numIslands++;
  93347. }
  93348. if (stat) {
  93349. time2 = OIMO.now();
  93350. this.performance.solvingTime = time2 - time1;
  93351. //------------------------------------------------------
  93352. // END SIMULATION
  93353. //------------------------------------------------------
  93354. time2 = OIMO.now();
  93355. // fps update
  93356. this.performance.upfps();
  93357. this.performance.totalTime = time2 - time0;
  93358. }
  93359. }
  93360. }
  93361. /**
  93362. * The class of rigid body.
  93363. * Rigid body has the shape of a single or multiple collision processing,
  93364. * I can set the parameters individually.
  93365. * @author saharan
  93366. */
  93367. OIMO.RigidBody = function (x, y, z, rad, ax, ay, az) {
  93368. this.name = " ";
  93369. // The maximum number of shapes that can be added to a one rigid.
  93370. this.MAX_SHAPES = 64;//64;
  93371. this.prev = null;
  93372. this.next = null;
  93373. // I represent the kind of rigid body.
  93374. // Please do not change from the outside this variable.
  93375. // If you want to change the type of rigid body, always
  93376. // Please specify the type you want to set the arguments of setupMass method.
  93377. this.type = OIMO.BODY_NULL;
  93378. this.massInfo = new OIMO.MassInfo();
  93379. // It is the world coordinate of the center of gravity.
  93380. this.position = new OIMO.Vec3(x, y, z);
  93381. this.orientation = this.rotationAxisToQuad(rad || 0, ax || 0, ay || 0, az || 0);
  93382. this.newPosition = new OIMO.Vec3();
  93383. this.controlPos = false;
  93384. this.newOrientation = new OIMO.Quat();
  93385. this.newRotation = new OIMO.Vec3();
  93386. this.currentRotation = new OIMO.Vec3();
  93387. this.controlRot = false;
  93388. this.controlRotInTime = false;
  93389. // Is the translational velocity.
  93390. this.linearVelocity = new OIMO.Vec3();
  93391. // Is the angular velocity.
  93392. this.angularVelocity = new OIMO.Vec3();
  93393. // return matrix for three.js
  93394. this.matrix = new OIMO.Mat44();
  93395. //--------------------------------------------
  93396. // Please do not change from the outside this variables.
  93397. //--------------------------------------------
  93398. // It is a world that rigid body has been added.
  93399. this.parent = null;
  93400. this.contactLink = null;
  93401. this.numContacts = 0;
  93402. // An array of shapes that are included in the rigid body.
  93403. this.shapes = null;
  93404. // The number of shapes that are included in the rigid body.
  93405. this.numShapes = 0;
  93406. // It is the link array of joint that is connected to the rigid body.
  93407. this.jointLink = null;
  93408. // The number of joints that are connected to the rigid body.
  93409. this.numJoints = 0;
  93410. // It is the world coordinate of the center of gravity in the sleep just before.
  93411. this.sleepPosition = new OIMO.Vec3();
  93412. // It is a quaternion that represents the attitude of sleep just before.
  93413. this.sleepOrientation = new OIMO.Quat();
  93414. // I will show this rigid body to determine whether it is a rigid body static.
  93415. this.isStatic = false;
  93416. // I indicates that this rigid body to determine whether it is a rigid body dynamic.
  93417. this.isDynamic = false;
  93418. // It is a rotation matrix representing the orientation.
  93419. this.rotation = new OIMO.Mat33();
  93420. //--------------------------------------------
  93421. // It will be recalculated automatically from the shape, which is included.
  93422. //--------------------------------------------
  93423. // This is the weight.
  93424. this.mass = NaN;
  93425. // It is the reciprocal of the mass.
  93426. this.inverseMass = NaN;
  93427. // It is the inverse of the inertia tensor in the world system.
  93428. this.inverseInertia = new OIMO.Mat33();
  93429. // It is the inertia tensor in the initial state.
  93430. this.localInertia = new OIMO.Mat33();
  93431. // It is the inverse of the inertia tensor in the initial state.
  93432. this.inverseLocalInertia = new OIMO.Mat33();
  93433. // I indicates rigid body whether it has been added to the simulation Island.
  93434. this.addedToIsland = false;
  93435. // It shows how to sleep rigid body.
  93436. this.allowSleep = true;
  93437. // This is the time from when the rigid body at rest.
  93438. this.sleepTime = 0;
  93439. // I shows rigid body to determine whether it is a sleep state.
  93440. this.sleeping = false;
  93441. };
  93442. OIMO.RigidBody.prototype = {
  93443. constructor: OIMO.RigidBody,
  93444. /**
  93445. * I'll add a shape to rigid body.
  93446. * If you add a shape, please call the setupMass method to step up to the start of the next.
  93447. * @param shape shape to Add
  93448. */
  93449. addShape: function (shape) {
  93450. if (shape.parent) OIMO.Error("RigidBody", "It is not possible that you add to the multi-rigid body the shape of one");
  93451. if (this.shapes != null) (this.shapes.prev = shape).next = this.shapes;
  93452. this.shapes = shape;
  93453. shape.parent = this;
  93454. if (this.parent) this.parent.addShape(shape);
  93455. this.numShapes++;
  93456. },
  93457. /**
  93458. * I will delete the shape from the rigid body.
  93459. * If you delete a shape, please call the setupMass method to step up to the start of the next.
  93460. * @param shape shape to Delete
  93461. */
  93462. removeShape: function (shape) {
  93463. var remove = shape;
  93464. if (remove.parent != this) return;
  93465. var prev = remove.prev;
  93466. var next = remove.next;
  93467. if (prev != null) prev.next = next;
  93468. if (next != null) next.prev = prev;
  93469. if (this.shapes == remove) this.shapes = next;
  93470. remove.prev = null;
  93471. remove.next = null;
  93472. remove.parent = null;
  93473. if (this.parent) this.parent.removeShape(remove);
  93474. this.numShapes--;
  93475. },
  93476. remove: function () {
  93477. this.dispose();
  93478. },
  93479. dispose: function () {
  93480. this.parent.removeRigidBody(this);
  93481. },
  93482. checkContact: function (name) {
  93483. this.parent.checkContact(this.name, name);
  93484. },
  93485. /**
  93486. * Calulates mass datas(center of gravity, mass, moment inertia, etc...).
  93487. * If the parameter type is set to BODY_STATIC, the rigid body will be fixed to the space.
  93488. * If the parameter adjustPosition is set to true, the shapes' relative positions and
  93489. * the rigid body's position will be adjusted to the center of gravity.
  93490. * @param type
  93491. * @param adjustPosition
  93492. */
  93493. setupMass: function (type, AdjustPosition) {
  93494. var adjustPosition = (AdjustPosition !== undefined) ? AdjustPosition : true;
  93495. this.type = type || OIMO.BODY_DYNAMIC;
  93496. this.isDynamic = this.type == OIMO.BODY_DYNAMIC;
  93497. this.isStatic = this.type == OIMO.BODY_STATIC;
  93498. this.mass = 0;
  93499. this.localInertia.set(0, 0, 0, 0, 0, 0, 0, 0, 0);
  93500. var te = this.localInertia.elements;
  93501. //
  93502. var tmpM = new OIMO.Mat33();
  93503. var tmpV = new OIMO.Vec3();
  93504. for (var shape = this.shapes; shape != null; shape = shape.next) {
  93505. shape.calculateMassInfo(this.massInfo);
  93506. var shapeMass = this.massInfo.mass;
  93507. var relX = shape.relativePosition.x;
  93508. var relY = shape.relativePosition.y;
  93509. var relZ = shape.relativePosition.z;
  93510. /*tmpV.x+=relX*shapeMass;
  93511. tmpV.y+=relY*shapeMass;
  93512. tmpV.z+=relZ*shapeMass;*/
  93513. tmpV.addScale(shape.relativePosition, shapeMass);
  93514. this.mass += shapeMass;
  93515. this.rotateInertia(shape.relativeRotation, this.massInfo.inertia, tmpM);
  93516. this.localInertia.addEqual(tmpM);
  93517. // add offset inertia
  93518. te[0] += shapeMass * (relY * relY + relZ * relZ);
  93519. te[4] += shapeMass * (relX * relX + relZ * relZ);
  93520. te[8] += shapeMass * (relX * relX + relY * relY);
  93521. var xy = shapeMass * relX * relY;
  93522. var yz = shapeMass * relY * relZ;
  93523. var zx = shapeMass * relZ * relX;
  93524. te[1] -= xy;
  93525. te[3] -= xy;
  93526. te[2] -= yz;
  93527. te[6] -= yz;
  93528. te[5] -= zx;
  93529. te[7] -= zx;
  93530. }
  93531. this.inverseMass = 1 / this.mass;
  93532. tmpV.scaleEqual(this.inverseMass);
  93533. if (adjustPosition) {
  93534. this.position.addEqual(tmpV);
  93535. for (shape = this.shapes; shape != null; shape = shape.next) {
  93536. shape.relativePosition.subEqual(tmpV);
  93537. }
  93538. // subtract offset inertia
  93539. relX = tmpV.x;
  93540. relY = tmpV.y;
  93541. relZ = tmpV.z;
  93542. //var te = this.localInertia.elements;
  93543. te[0] -= this.mass * (relY * relY + relZ * relZ);
  93544. te[4] -= this.mass * (relX * relX + relZ * relZ);
  93545. te[8] -= this.mass * (relX * relX + relY * relY);
  93546. xy = this.mass * relX * relY;
  93547. yz = this.mass * relY * relZ;
  93548. zx = this.mass * relZ * relX;
  93549. te[1] += xy;
  93550. te[3] += xy;
  93551. te[2] += yz;
  93552. te[6] += yz;
  93553. te[5] += zx;
  93554. te[7] += zx;
  93555. }
  93556. this.inverseLocalInertia.invert(this.localInertia);
  93557. if (this.type == OIMO.BODY_STATIC) {
  93558. this.inverseMass = 0;
  93559. this.inverseLocalInertia.set(0, 0, 0, 0, 0, 0, 0, 0, 0);
  93560. }
  93561. this.syncShapes();
  93562. this.awake();
  93563. },
  93564. /**
  93565. * Awake the rigid body.
  93566. */
  93567. awake: function () {
  93568. if (!this.allowSleep || !this.sleeping) return;
  93569. this.sleeping = false;
  93570. this.sleepTime = 0;
  93571. // awake connected constraints
  93572. var cs = this.contactLink;
  93573. while (cs != null) {
  93574. cs.body.sleepTime = 0;
  93575. cs.body.sleeping = false;
  93576. cs = cs.next;
  93577. }
  93578. var js = this.jointLink;
  93579. while (js != null) {
  93580. js.body.sleepTime = 0;
  93581. js.body.sleeping = false;
  93582. js = js.next;
  93583. }
  93584. for (var shape = this.shapes; shape != null; shape = shape.next) {
  93585. shape.updateProxy();
  93586. }
  93587. },
  93588. /**
  93589. * Sleep the rigid body.
  93590. */
  93591. sleep: function () {
  93592. if (!this.allowSleep || this.sleeping) return;
  93593. this.linearVelocity.set(0, 0, 0);
  93594. this.angularVelocity.set(0, 0, 0);
  93595. this.sleepPosition.copy(this.position);
  93596. this.sleepOrientation.copy(this.orientation);
  93597. /*this.linearVelocity.x=0;
  93598. this.linearVelocity.y=0;
  93599. this.linearVelocity.z=0;
  93600. this.angularVelocity.x=0;
  93601. this.angularVelocity.y=0;
  93602. this.angularVelocity.z=0;
  93603. this.sleepPosition.x=this.position.x;
  93604. this.sleepPosition.y=this.position.y;
  93605. this.sleepPosition.z=this.position.z;*/
  93606. /*this.sleepOrientation.s=this.orientation.s;
  93607. this.sleepOrientation.x=this.orientation.x;
  93608. this.sleepOrientation.y=this.orientation.y;
  93609. this.sleepOrientation.z=this.orientation.z;*/
  93610. this.sleepTime = 0;
  93611. this.sleeping = true;
  93612. for (var shape = this.shapes; shape != null; shape = shape.next) {
  93613. shape.updateProxy();
  93614. }
  93615. },
  93616. /**
  93617. * Get whether the rigid body has not any connection with others.
  93618. * @return
  93619. */
  93620. isLonely: function () {
  93621. return this.numJoints == 0 && this.numContacts == 0;
  93622. },
  93623. /**
  93624. * The time integration of the motion of a rigid body, you can update the information such as the shape.
  93625. * This method is invoked automatically when calling the step of the World,
  93626. * There is no need to call from outside usually.
  93627. * @param timeStep time
  93628. */
  93629. updatePosition: function (timeStep) {
  93630. switch (this.type) {
  93631. case OIMO.BODY_STATIC:
  93632. this.linearVelocity.set(0, 0, 0);
  93633. this.angularVelocity.set(0, 0, 0);
  93634. // ONLY FOR TEST
  93635. if (this.controlPos) {
  93636. this.position.copy(this.newPosition);
  93637. this.controlPos = false;
  93638. }
  93639. if (this.controlRot) {
  93640. this.orientation.copy(this.newOrientation);
  93641. this.controlRot = false;
  93642. }
  93643. /*this.linearVelocity.x=0;
  93644. this.linearVelocity.y=0;
  93645. this.linearVelocity.z=0;
  93646. this.angularVelocity.x=0;
  93647. this.angularVelocity.y=0;
  93648. this.angularVelocity.z=0;*/
  93649. break;
  93650. case OIMO.BODY_DYNAMIC:
  93651. if (this.controlPos) {
  93652. this.angularVelocity.set(0, 0, 0);
  93653. this.linearVelocity.set(0, 0, 0);
  93654. this.linearVelocity.x = (this.newPosition.x - this.position.x) / timeStep;
  93655. this.linearVelocity.y = (this.newPosition.y - this.position.y) / timeStep;
  93656. this.linearVelocity.z = (this.newPosition.z - this.position.z) / timeStep;
  93657. this.controlPos = false;
  93658. }
  93659. if (this.controlRot) {
  93660. this.angularVelocity.set(0, 0, 0);
  93661. this.orientation.copy(this.newOrientation);
  93662. //var t=timeStep//*0.5;
  93663. //var q = new OIMO.Quat();
  93664. //q.sub(this.newOrientation, this.orientation);
  93665. //q.normalize(q);
  93666. /*q.s = (this.newOrientation.s - this.orientation.s)/t;
  93667. q.x = (this.newOrientation.x - this.orientation.x)/t;
  93668. q.y = (this.newOrientation.y - this.orientation.y)/t;
  93669. q.z = (this.newOrientation.z - this.orientation.z)/t;*/
  93670. //this.angularVelocity.applyQuaternion(q);
  93671. //this.angularVelocity.x = this.angularVelocity.x/t;
  93672. //this.angularVelocity.y = this.angularVelocity.y/t;
  93673. //this.angularVelocity.z = this.angularVelocity.z/t;
  93674. this.controlRot = false;
  93675. }
  93676. this.position.addTime(this.linearVelocity, timeStep);
  93677. this.orientation.addTime(this.angularVelocity, timeStep);
  93678. break;
  93679. default: OIMO.Error("RigidBody", "Invalid type.");
  93680. }
  93681. this.syncShapes();
  93682. },
  93683. rotateInertia: function (rot, inertia, out) {
  93684. var tm1 = rot.elements;
  93685. var tm2 = inertia.elements;
  93686. var a0 = tm1[0], a3 = tm1[3], a6 = tm1[6];
  93687. var a1 = tm1[1], a4 = tm1[4], a7 = tm1[7];
  93688. var a2 = tm1[2], a5 = tm1[5], a8 = tm1[8];
  93689. var b0 = tm2[0], b3 = tm2[3], b6 = tm2[6];
  93690. var b1 = tm2[1], b4 = tm2[4], b7 = tm2[7];
  93691. var b2 = tm2[2], b5 = tm2[5], b8 = tm2[8];
  93692. var e00 = a0 * b0 + a1 * b3 + a2 * b6;
  93693. var e01 = a0 * b1 + a1 * b4 + a2 * b7;
  93694. var e02 = a0 * b2 + a1 * b5 + a2 * b8;
  93695. var e10 = a3 * b0 + a4 * b3 + a5 * b6;
  93696. var e11 = a3 * b1 + a4 * b4 + a5 * b7;
  93697. var e12 = a3 * b2 + a4 * b5 + a5 * b8;
  93698. var e20 = a6 * b0 + a7 * b3 + a8 * b6;
  93699. var e21 = a6 * b1 + a7 * b4 + a8 * b7;
  93700. var e22 = a6 * b2 + a7 * b5 + a8 * b8;
  93701. var oe = out.elements;
  93702. oe[0] = e00 * a0 + e01 * a1 + e02 * a2;
  93703. oe[1] = e00 * a3 + e01 * a4 + e02 * a5;
  93704. oe[2] = e00 * a6 + e01 * a7 + e02 * a8;
  93705. oe[3] = e10 * a0 + e11 * a1 + e12 * a2;
  93706. oe[4] = e10 * a3 + e11 * a4 + e12 * a5;
  93707. oe[5] = e10 * a6 + e11 * a7 + e12 * a8;
  93708. oe[6] = e20 * a0 + e21 * a1 + e22 * a2;
  93709. oe[7] = e20 * a3 + e21 * a4 + e22 * a5;
  93710. oe[8] = e20 * a6 + e21 * a7 + e22 * a8;
  93711. },
  93712. syncShapes: function () {
  93713. var s = this.orientation.s;
  93714. var x = this.orientation.x;
  93715. var y = this.orientation.y;
  93716. var z = this.orientation.z;
  93717. var x2 = 2 * x;
  93718. var y2 = 2 * y;
  93719. var z2 = 2 * z;
  93720. var xx = x * x2;
  93721. var yy = y * y2;
  93722. var zz = z * z2;
  93723. var xy = x * y2;
  93724. var yz = y * z2;
  93725. var xz = x * z2;
  93726. var sx = s * x2;
  93727. var sy = s * y2;
  93728. var sz = s * z2;
  93729. var tr = this.rotation.elements;
  93730. tr[0] = 1 - yy - zz;
  93731. tr[1] = xy - sz;
  93732. tr[2] = xz + sy;
  93733. tr[3] = xy + sz;
  93734. tr[4] = 1 - xx - zz;
  93735. tr[5] = yz - sx;
  93736. tr[6] = xz - sy;
  93737. tr[7] = yz + sx;
  93738. tr[8] = 1 - xx - yy;
  93739. this.rotateInertia(this.rotation, this.inverseLocalInertia, this.inverseInertia);
  93740. for (var shape = this.shapes; shape != null; shape = shape.next) {
  93741. //var relPos=shape.relativePosition;
  93742. //var relRot=shape.relativeRotation;
  93743. //var rot=shape.rotation;
  93744. /*var lx=relPos.x;
  93745. var ly=relPos.y;
  93746. var lz=relPos.z;
  93747. shape.position.x=this.position.x+lx*tr[0]+ly*tr[1]+lz*tr[2];
  93748. shape.position.y=this.position.y+lx*tr[3]+ly*tr[4]+lz*tr[5];
  93749. shape.position.z=this.position.z+lx*tr[6]+ly*tr[7]+lz*tr[8];*/
  93750. shape.position.mul(this.position, shape.relativePosition, this.rotation);
  93751. //shape.rotation.mul(shape.relativeRotation,this.rotation);
  93752. // add by QuaziKb
  93753. shape.rotation.mul(this.rotation, shape.relativeRotation);
  93754. shape.updateProxy();
  93755. }
  93756. },
  93757. applyImpulse: function (position, force) {
  93758. this.linearVelocity.addScale(force, this.inverseMass);
  93759. /*this.linearVelocity.x+=force.x*this.inverseMass;
  93760. this.linearVelocity.y+=force.y*this.inverseMass;
  93761. this.linearVelocity.z+=force.z*this.inverseMass;*/
  93762. var rel = new OIMO.Vec3();
  93763. rel.sub(position, this.position).cross(rel, force).mulMat(this.inverseInertia, rel);
  93764. this.angularVelocity.addEqual(rel);
  93765. /*this.angularVelocity.x+=rel.x;
  93766. this.angularVelocity.y+=rel.y;
  93767. this.angularVelocity.z+=rel.z;*/
  93768. },
  93769. //---------------------------------------------
  93770. //
  93771. // FOR THREE JS
  93772. //
  93773. //---------------------------------------------
  93774. rotationVectToQuad: function (rot) {
  93775. var r = OIMO.EulerToAxis(rot.x * OIMO.degtorad, rot.y * OIMO.degtorad, rot.z * OIMO.degtorad);
  93776. return this.rotationAxisToQuad(r[0], r[1], r[2], r[3]);
  93777. },
  93778. rotationAxisToQuad: function (rad, ax, ay, az) { // in radian
  93779. var len = ax * ax + ay * ay + az * az;
  93780. if (len > 0) {
  93781. len = 1 / OIMO.sqrt(len);
  93782. ax *= len;
  93783. ay *= len;
  93784. az *= len;
  93785. }
  93786. var sin = OIMO.sin(rad * 0.5);
  93787. var cos = OIMO.cos(rad * 0.5);
  93788. return new OIMO.Quat(cos, sin * ax, sin * ay, sin * az);
  93789. },
  93790. //---------------------------------------------
  93791. // SET DYNAMIQUE POSITION AND ROTATION
  93792. //---------------------------------------------
  93793. setPosition: function (pos) {
  93794. this.newPosition.copy(pos).multiplyScalar(OIMO.INV_SCALE);
  93795. //this.newPosition.set(pos.x*OIMO.INV_SCALE,pos.y*OIMO.INV_SCALE,pos.z*OIMO.INV_SCALE);
  93796. this.controlPos = true;
  93797. },
  93798. setQuaternion: function (q) {
  93799. //if(this.type == this.BODY_STATIC)this.orientation.init(q.w,q.x,q.y,q.z);
  93800. this.newOrientation.set(q.x, q.y, q.z, q.w);
  93801. this.controlRot = true;
  93802. },
  93803. setRotation: function (rot) {
  93804. this.newOrientation = this.rotationVectToQuad(rot);
  93805. this.controlRot = true;
  93806. },
  93807. //---------------------------------------------
  93808. // RESET DYNAMIQUE POSITION AND ROTATION
  93809. //---------------------------------------------
  93810. resetPosition: function (x, y, z) {
  93811. this.linearVelocity.set(0, 0, 0);
  93812. this.angularVelocity.set(0, 0, 0);
  93813. this.position.set(x, y, z).multiplyScalar(OIMO.INV_SCALE);
  93814. //this.position.set( x*OIMO.INV_SCALE, y*OIMO.INV_SCALE, z*OIMO.INV_SCALE );
  93815. this.awake();
  93816. },
  93817. resetQuaternion: function (q) {
  93818. this.angularVelocity.set(0, 0, 0);
  93819. this.orientation = new OIMO.Quat(q.w, q.x, q.y, q.z);
  93820. this.awake();
  93821. },
  93822. resetRotation: function (x, y, z) {
  93823. this.angularVelocity.set(0, 0, 0);
  93824. this.orientation = this.rotationVectToQuad(new OIMO.Vec3(x, y, z));
  93825. this.awake();
  93826. },
  93827. //---------------------------------------------
  93828. // GET POSITION AND ROTATION
  93829. //---------------------------------------------
  93830. getPosition: function () {
  93831. return new OIMO.Vec3().scale(this.position, OIMO.WORLD_SCALE);
  93832. },
  93833. getRotation: function () {
  93834. return new OIMO.Euler().setFromRotationMatrix(this.rotation);
  93835. },
  93836. getQuaternion: function () {
  93837. return new OIMO.Quaternion().setFromRotationMatrix(this.rotation);
  93838. },
  93839. getMatrix: function () {
  93840. var m = this.matrix.elements;
  93841. var r, p;
  93842. if (!this.sleeping) {
  93843. // rotation matrix
  93844. r = this.rotation.elements;
  93845. m[0] = r[0]; m[1] = r[3]; m[2] = r[6]; m[3] = 0;
  93846. m[4] = r[1]; m[5] = r[4]; m[6] = r[7]; m[7] = 0;
  93847. m[8] = r[2]; m[9] = r[5]; m[10] = r[8]; m[11] = 0;
  93848. // position matrix
  93849. p = this.position;
  93850. m[12] = p.x * OIMO.WORLD_SCALE;
  93851. m[13] = p.y * OIMO.WORLD_SCALE;
  93852. m[14] = p.z * OIMO.WORLD_SCALE;
  93853. // sleep or not ?
  93854. m[15] = 0;
  93855. } else {
  93856. m[15] = 1;
  93857. }
  93858. return m;
  93859. }
  93860. };
  93861. /**
  93862. * The main class of body.
  93863. * is for simplify creation process and data access of rigidRody
  93864. * Rigid body has the shape of a single or multiple collision processing,
  93865. * all setting in object
  93866. *
  93867. * @author loth
  93868. */
  93869. OIMO.Body = function (Obj) {
  93870. var obj = Obj || {};
  93871. if (!obj.world) return;
  93872. if (obj.type === undefined) obj.type = "box";
  93873. this.name = obj.name || '';
  93874. // obsolete use world.add(obj)
  93875. this.body = obj.world.add(obj);
  93876. /*
  93877. // the world where i am
  93878. this.parent = obj.world;
  93879. // Yep my name
  93880. this.name = obj.name || '';
  93881. // I'm dynamique or not
  93882. var move = obj.move || false;
  93883. // I can sleep or not
  93884. var noSleep = obj.noSleep || false;
  93885. // My start position
  93886. var p = obj.pos || [0,0,0];
  93887. p = p.map(function(x) { return x * OIMO.INV_SCALE; });
  93888. // My size
  93889. var s = obj.size || [1,1,1];
  93890. s = s.map(function(x) { return x * OIMO.INV_SCALE; });
  93891. // My rotation in degre
  93892. var rot = obj.rot || [0,0,0];
  93893. rot = rot.map(function(x) { return x * OIMO.TO_RAD; });
  93894. var r = [];
  93895. for (var i=0; i<rot.length/3; i++){
  93896. var tmp = OIMO.EulerToAxis(rot[i+0], rot[i+1], rot[i+2]);
  93897. r.push(tmp[0]); r.push(tmp[1]); r.push(tmp[2]); r.push(tmp[3]);
  93898. }
  93899. // My physics setting
  93900. var sc = obj.sc || new OIMO.ShapeConfig();
  93901. if(obj.config){
  93902. // The density of the shape.
  93903. sc.density = obj.config[0] || 1;
  93904. // The coefficient of friction of the shape.
  93905. sc.friction = obj.config[1] || 0.4;
  93906. // The coefficient of restitution of the shape.
  93907. sc.restitution = obj.config[2] || 0.2;
  93908. // The bits of the collision groups to which the shape belongs.
  93909. sc.belongsTo = obj.config[3] || 1;
  93910. // The bits of the collision groups with which the shape collides.
  93911. sc.collidesWith = obj.config[4] || 0xffffffff;
  93912. }
  93913. if(obj.massPos){
  93914. obj.massPos = obj.massPos.map(function(x) { return x * OIMO.INV_SCALE; });
  93915. sc.relativePosition.init(obj.massPos[0], obj.massPos[1], obj.massPos[2]);
  93916. }
  93917. if(obj.massRot){
  93918. obj.massRot = obj.massRot.map(function(x) { return x * OIMO.TO_RAD; });
  93919. sc.relativeRotation = OIMO.EulerToMatrix(obj.massRot[0], obj.massRot[1], obj.massRot[2]);
  93920. }
  93921. // My rigidbody
  93922. this.body = new OIMO.RigidBody(p[0], p[1], p[2], r[0], r[1], r[2], r[3]);
  93923. // My shapes
  93924. var shapes = [];
  93925. var type = obj.type || "box";
  93926. if( typeof type === 'string' ) type = [type];// single shape
  93927. var n, n2;
  93928. for(var i=0; i<type.length; i++){
  93929. n = i*3;
  93930. n2 = i*4;
  93931. switch(type[i]){
  93932. case "sphere": shapes[i] = new OIMO.SphereShape(sc, s[n+0]); break;
  93933. case "cylinder": shapes[i] = new OIMO.BoxShape(sc, s[n+0], s[n+1], s[n+2]); break; // fake cylinder
  93934. case "box": shapes[i] = new OIMO.BoxShape(sc, s[n+0], s[n+1], s[n+2]); break;
  93935. }
  93936. this.body.addShape(shapes[i]);
  93937. if(i>0){
  93938. //shapes[i].position.init(p[0]+p[n+0], p[1]+p[n+1], p[2]+p[n+2] );
  93939. shapes[i].relativePosition = new OIMO.Vec3( p[n+0], p[n+1], p[n+2] );
  93940. if(r[n2+0]) shapes[i].relativeRotation = [ r[n2+0], r[n2+1], r[n2+2], r[n2+3] ];
  93941. }
  93942. }
  93943. // I'm static or i move
  93944. if(move){
  93945. if(obj.massPos || obj.massRot)this.body.setupMass(0x1, false);
  93946. else this.body.setupMass(0x1, true);
  93947. if(noSleep) this.body.allowSleep = false;
  93948. else this.body.allowSleep = true;
  93949. } else {
  93950. this.body.setupMass(0x2);
  93951. }
  93952. this.body.name = this.name;
  93953. this.sleeping = this.body.sleeping;
  93954. // finaly add to physics world
  93955. this.parent.addRigidBody(this.body);*/
  93956. }
  93957. OIMO.Body.prototype = {
  93958. constructor: OIMO.Body,
  93959. // SET
  93960. setPosition: function (pos) {
  93961. this.body.setPosition(pos);
  93962. },
  93963. setQuaternion: function (q) {
  93964. this.body.setQuaternion(q);
  93965. },
  93966. setRotation: function (rot) {
  93967. this.body.setRotation(rot);
  93968. },
  93969. // GET
  93970. getPosition: function () {
  93971. return this.body.getPosition();
  93972. },
  93973. getRotation: function () {
  93974. return this.body.getRotation();
  93975. },
  93976. getQuaternion: function () {
  93977. return this.body.getQuaternion();
  93978. },
  93979. getMatrix: function () {
  93980. return this.body.getMatrix();
  93981. },
  93982. getSleep: function () {
  93983. return this.body.sleeping;
  93984. },
  93985. // RESET
  93986. resetPosition: function (x, y, z) {
  93987. this.body.resetPosition(x, y, z);
  93988. },
  93989. resetRotation: function (x, y, z) {
  93990. this.body.resetRotation(x, y, z);
  93991. },
  93992. // force wakeup
  93993. awake: function () {
  93994. this.body.awake();
  93995. },
  93996. // remove rigidbody
  93997. remove: function () {
  93998. this.body.dispose();
  93999. //this.parent.removeRigidBody(this.body);
  94000. },
  94001. // test if this object hit another
  94002. checkContact: function (name) {
  94003. this.body.checkContact(name);
  94004. //this.parent.checkContact(this.name, name);
  94005. }
  94006. }
  94007. /**
  94008. * The main class of link.
  94009. * is for simplify creation process and data access of Joint
  94010. * all setting in object
  94011. *
  94012. * @author loth
  94013. */
  94014. OIMO.Link = function (Obj) {
  94015. var obj = Obj || {};
  94016. if (!obj.world) return;
  94017. if (obj.type === undefined) obj.type = "jointHinge";
  94018. this.name = obj.name || '';
  94019. // obsolete use world.add(obj)
  94020. this.joint = obj.world.add(obj);
  94021. // the world where i am
  94022. /*this.parent = obj.world;
  94023. this.name = obj.name || '';
  94024. var type = obj.type || "jointHinge";
  94025. var axe1 = obj.axe1 || [1,0,0];
  94026. var axe2 = obj.axe2 || [1,0,0];
  94027. var pos1 = obj.pos1 || [0,0,0];
  94028. var pos2 = obj.pos2 || [0,0,0];
  94029. pos1 = pos1.map(function(x){ return x * OIMO.INV_SCALE; });
  94030. pos2 = pos2.map(function(x){ return x * OIMO.INV_SCALE; });
  94031. var min, max;
  94032. if(type==="jointDistance"){
  94033. min = obj.min || 0;
  94034. max = obj.max || 10;
  94035. min = min*OIMO.INV_SCALE;
  94036. max = max*OIMO.INV_SCALE;
  94037. }else{
  94038. min = obj.min || 57.29578;
  94039. max = obj.max || 0;
  94040. min = min*OIMO.TO_RAD;
  94041. max = max*OIMO.TO_RAD;
  94042. }
  94043. var limit = obj.limit || null;
  94044. var spring = obj.spring || null;
  94045. var motor = obj.motor || null;
  94046. // joint setting
  94047. var jc = new OIMO.JointConfig();
  94048. jc.allowCollision = obj.collision || false;;
  94049. jc.localAxis1.init(axe1[0], axe1[1], axe1[2]);
  94050. jc.localAxis2.init(axe2[0], axe2[1], axe2[2]);
  94051. jc.localAnchorPoint1.init(pos1[0], pos1[1], pos1[2]);
  94052. jc.localAnchorPoint2.init(pos2[0], pos2[1], pos2[2]);
  94053. if (typeof obj.body1 == 'string' || obj.body1 instanceof String) obj.body1 = obj.world.getByName(obj.body1);
  94054. if (typeof obj.body2 == 'string' || obj.body2 instanceof String) obj.body2 = obj.world.getByName(obj.body2);
  94055. jc.body1 = obj.body1;
  94056. jc.body2 = obj.body2;
  94057. switch(type){
  94058. case "jointDistance": this.joint = new OIMO.DistanceJoint(jc, min, max);
  94059. if(spring !== null) this.joint.limitMotor.setSpring(spring[0], spring[1]);
  94060. if(motor !== null) this.joint.limitMotor.setSpring(motor[0], motor[1]);
  94061. break;
  94062. case "jointHinge": this.joint = new OIMO.HingeJoint(jc, min, max);
  94063. if(spring !== null) this.joint.limitMotor.setSpring(spring[0], spring[1]);// soften the joint ex: 100, 0.2
  94064. if(motor !== null) this.joint.limitMotor.setSpring(motor[0], motor[1]);
  94065. break;
  94066. case "jointPrisme": this.joint = new OIMO.PrismaticJoint(jc, min, max); break;
  94067. case "jointSlide": this.joint = new OIMO.SliderJoint(jc, min, max); break;
  94068. case "jointBall": this.joint = new OIMO.BallAndSocketJoint(jc); break;
  94069. case "jointWheel": this.joint = new OIMO.WheelJoint(jc);
  94070. if(limit !== null) this.joint.rotationalLimitMotor1.setLimit(limit[0], limit[1]);
  94071. if(spring !== null) this.joint.rotationalLimitMotor1.setSpring(spring[0], spring[1]);
  94072. if(motor !== null) this.joint.rotationalLimitMotor1.setSpring(motor[0], motor[1]);
  94073. break;
  94074. }
  94075. this.joint.name = this.name;
  94076. // finaly add to physics world
  94077. this.parent.addJoint(this.joint);*/
  94078. }
  94079. OIMO.Link.prototype = {
  94080. constructor: OIMO.Link,
  94081. getPosition: function () {
  94082. // array of two vect3 [point1, point2]
  94083. return this.joint.getPosition();
  94084. },
  94085. getMatrix: function () {
  94086. return this.joint.getMatrix();
  94087. },
  94088. // remove joint
  94089. remove: function () {
  94090. this.joint.dispose();
  94091. //this.parent.removeJoint(this.joint);
  94092. },
  94093. // force wakeup linked body
  94094. awake: function () {
  94095. this.joint.awake();
  94096. }
  94097. }
  94098. /**
  94099. * The Dictionary class for testing
  94100. * @author lo-th
  94101. */
  94102. OIMO.Dictionary = function () {
  94103. this.data = {};
  94104. this.keys = [];
  94105. };
  94106. OIMO.Dictionary.prototype = {
  94107. constructor: OIMO.Dictionary,
  94108. set: function (value) {
  94109. var key = value.id;
  94110. if (!this.get[key]) this.keys.push(key);
  94111. this.data[key] = value;
  94112. },
  94113. get: function (id) {
  94114. return this.data[id];
  94115. },
  94116. del: function (value) {
  94117. var k = this.keys;
  94118. var n = k.indexOf(value.id);
  94119. if (n > -1) {
  94120. delete this.data[k[n]];
  94121. k.splice(n, 1);
  94122. }
  94123. },
  94124. reset: function () {
  94125. var data = this.data, keys = this.keys, key;
  94126. while (keys.length > 0) {
  94127. key = keys.pop();
  94128. delete data[key];
  94129. }
  94130. }
  94131. };
  94132. OIMO.Performance = function (world) {
  94133. this.parent = world;
  94134. this.infos = new OIMO_ARRAY_TYPE(13);
  94135. this.f = [0, 0, 0];
  94136. this.types = ['None', 'BruteForce', 'Sweep & Prune', 'Bounding Volume Tree'];
  94137. this.broadPhase = this.types[this.parent.broadPhase.types];
  94138. this.version = OIMO.REVISION;
  94139. this.fps = 0;
  94140. this.broadPhaseTime = 0;
  94141. this.narrowPhaseTime = 0;
  94142. this.solvingTime = 0;
  94143. //this.updatingTime = 0;
  94144. this.totalTime = 0;
  94145. };
  94146. OIMO.Performance.prototype = {
  94147. upfps: function () {
  94148. this.f[1] = Date.now();
  94149. 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]++;
  94150. },
  94151. updatingTime: function () {
  94152. return OIMO.fix(this.totalTime - (this.broadPhaseTime + this.narrowPhaseTime + this.solvingTime));
  94153. },
  94154. show: function () {
  94155. var info = [
  94156. "Oimo.js " + this.version + "<br>",
  94157. this.broadPhase + "<br><br>",
  94158. "FPS: " + this.fps + " fps<br><br>",
  94159. "rigidbody " + this.parent.numRigidBodies + "<br>",
  94160. "contact &nbsp;&nbsp;" + this.parent.numContacts + "<br>",
  94161. "ct-point &nbsp;" + this.parent.numContactPoints + "<br>",
  94162. "paircheck " + this.parent.broadPhase.numPairChecks + "<br>",
  94163. "island &nbsp;&nbsp;&nbsp;" + this.parent.numIslands + "<br><br>",
  94164. "Time in milliseconde<br><br>",
  94165. "broad-phase &nbsp;" + OIMO.fix(this.broadPhaseTime) + "<br>",
  94166. "narrow-phase " + OIMO.fix(this.narrowPhaseTime) + "<br>",
  94167. "solving &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" + OIMO.fix(this.solvingTime) + "<br>",
  94168. "total &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" + OIMO.fix(this.totalTime) + "<br>",
  94169. "updating &nbsp;&nbsp;&nbsp;&nbsp;" + this.updatingTime() + "<br>"
  94170. ].join("\n");
  94171. return info;
  94172. },
  94173. toArray: function () {
  94174. this.infos[0] = this.parent.broadPhase.types;
  94175. this.infos[1] = this.parent.numRigidBodies;
  94176. this.infos[2] = this.parent.numContacts;
  94177. this.infos[3] = this.parent.broadPhase.numPairChecks;
  94178. this.infos[4] = this.parent.numContactPoints;
  94179. this.infos[5] = this.parent.numIslands;
  94180. this.infos[6] = this.broadPhaseTime;
  94181. this.infos[7] = this.narrowPhaseTime;
  94182. this.infos[8] = this.solvingTime;
  94183. this.infos[9] = this.updatingTime();
  94184. this.infos[10] = this.totalTime;
  94185. this.infos[11] = this.fps;
  94186. return this.infos;
  94187. }
  94188. };
  94189. OIMO.Mat44 = function (n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44) {
  94190. this.elements = new OIMO_ARRAY_TYPE(16);
  94191. var te = this.elements;
  94192. te[0] = (n11 !== undefined) ? n11 : 1; te[4] = n12 || 0; te[8] = n13 || 0; te[12] = n14 || 0;
  94193. te[1] = n21 || 0; te[5] = (n22 !== undefined) ? n22 : 1; te[9] = n23 || 0; te[13] = n24 || 0;
  94194. te[2] = n31 || 0; te[6] = n32 || 0; te[10] = (n33 !== undefined) ? n33 : 1; te[14] = n34 || 0;
  94195. te[3] = n41 || 0; te[7] = n42 || 0; te[11] = n43 || 0; te[15] = (n44 !== undefined) ? n44 : 1;
  94196. };
  94197. OIMO.Mat44.prototype = {
  94198. constructor: OIMO.Mat44,
  94199. set: function (n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44) {
  94200. var te = this.elements;
  94201. te[0] = n11; te[4] = n12; te[8] = n13; te[12] = n14;
  94202. te[1] = n21; te[5] = n22; te[9] = n23; te[13] = n24;
  94203. te[2] = n31; te[6] = n32; te[10] = n33; te[14] = n34;
  94204. te[3] = n41; te[7] = n42; te[11] = n43; te[15] = n44;
  94205. return this;
  94206. }/*,
  94207. extractRotation: function () {
  94208. var v1 = new THREE.Vector3();
  94209. return function ( m ) {
  94210. var te = this.elements;
  94211. var me = m.elements;
  94212. var scaleX = 1 / v1.set( me[ 0 ], me[ 1 ], me[ 2 ] ).length();
  94213. var scaleY = 1 / v1.set( me[ 4 ], me[ 5 ], me[ 6 ] ).length();
  94214. var scaleZ = 1 / v1.set( me[ 8 ], me[ 9 ], me[ 10 ] ).length();
  94215. te[ 0 ] = me[ 0 ] * scaleX;
  94216. te[ 1 ] = me[ 1 ] * scaleX;
  94217. te[ 2 ] = me[ 2 ] * scaleX;
  94218. te[ 4 ] = me[ 4 ] * scaleY;
  94219. te[ 5 ] = me[ 5 ] * scaleY;
  94220. te[ 6 ] = me[ 6 ] * scaleY;
  94221. te[ 8 ] = me[ 8 ] * scaleZ;
  94222. te[ 9 ] = me[ 9 ] * scaleZ;
  94223. te[ 10 ] = me[ 10 ] * scaleZ;
  94224. return this;
  94225. };
  94226. }() */
  94227. }
  94228. OIMO.Mat33 = function (e00, e01, e02, e10, e11, e12, e20, e21, e22) {
  94229. this.elements = new OIMO_ARRAY_TYPE(9);
  94230. var te = this.elements;
  94231. this.init(
  94232. (e00 !== undefined) ? e00 : 1, e01 || 0, e02 || 0,
  94233. e10 || 0, (e11 !== undefined) ? e11 : 1, e12 || 0,
  94234. e20 || 0, e21 || 0, (e22 !== undefined) ? e22 : 1
  94235. );
  94236. };
  94237. OIMO.Mat33.prototype = {
  94238. constructor: OIMO.Mat33,
  94239. set: function (e00, e01, e02, e10, e11, e12, e20, e21, e22) {
  94240. var te = this.elements;
  94241. te[0] = e00; te[1] = e01; te[2] = e02;
  94242. te[3] = e10; te[4] = e11; te[5] = e12;
  94243. te[6] = e20; te[7] = e21; te[8] = e22;
  94244. return this;
  94245. },
  94246. init: function (e00, e01, e02, e10, e11, e12, e20, e21, e22) {
  94247. var te = this.elements;
  94248. te[0] = e00; te[1] = e01; te[2] = e02;
  94249. te[3] = e10; te[4] = e11; te[5] = e12;
  94250. te[6] = e20; te[7] = e21; te[8] = e22;
  94251. return this;
  94252. },
  94253. multiply: function (s) {
  94254. var te = this.elements;
  94255. te[0] *= s; te[1] *= s; te[2] *= s;
  94256. te[3] *= s; te[4] *= s; te[5] *= s;
  94257. te[6] *= s; te[7] *= s; te[8] *= s;
  94258. return this;
  94259. },
  94260. add: function (m1, m2) {
  94261. var te = this.elements, tem1 = m1.elements, tem2 = m2.elements;
  94262. te[0] = tem1[0] + tem2[0]; te[1] = tem1[1] + tem2[1]; te[2] = tem1[2] + tem2[2];
  94263. te[3] = tem1[3] + tem2[3]; te[4] = tem1[4] + tem2[4]; te[5] = tem1[5] + tem2[5];
  94264. te[6] = tem1[6] + tem2[6]; te[7] = tem1[7] + tem2[7]; te[8] = tem1[8] + tem2[8];
  94265. return this;
  94266. },
  94267. addEqual: function (m) {
  94268. var te = this.elements, tem = m.elements;
  94269. te[0] += tem[0]; te[1] += tem[1]; te[2] += tem[2];
  94270. te[3] += tem[3]; te[4] += tem[4]; te[5] += tem[5];
  94271. te[6] += tem[6]; te[7] += tem[7]; te[8] += tem[8];
  94272. return this;
  94273. },
  94274. sub: function (m1, m2) {
  94275. var te = this.elements, tem1 = m1.elements, tem2 = m2.elements;
  94276. te[0] = tem1[0] - tem2[0]; te[1] = tem1[1] - tem2[1]; te[2] = tem1[2] - tem2[2];
  94277. te[3] = tem1[3] - tem2[3]; te[4] = tem1[4] - tem2[4]; te[5] = tem1[5] - tem2[5];
  94278. te[6] = tem1[6] - tem2[6]; te[7] = tem1[7] - tem2[7]; te[8] = tem1[8] - tem2[8];
  94279. return this;
  94280. },
  94281. subEqual: function (m) {
  94282. var te = this.elements, tem = m.elements;
  94283. te[0] -= tem[0]; te[1] -= tem[1]; te[2] -= tem[2];
  94284. te[3] -= tem[3]; te[4] -= tem[4]; te[5] -= tem[5];
  94285. te[6] -= tem[6]; te[7] -= tem[7]; te[8] -= tem[8];
  94286. return this;
  94287. },
  94288. scale: function (m, s) {
  94289. var te = this.elements, tm = m.elements;
  94290. te[0] = tm[0] * s; te[1] = tm[1] * s; te[2] = tm[2] * s;
  94291. te[3] = tm[3] * s; te[4] = tm[4] * s; te[5] = tm[5] * s;
  94292. te[6] = tm[6] * s; te[7] = tm[7] * s; te[8] = tm[8] * s;
  94293. return this;
  94294. },
  94295. scaleEqual: function (s) {
  94296. var te = this.elements;
  94297. te[0] *= s; te[1] *= s; te[2] *= s;
  94298. te[3] *= s; te[4] *= s; te[5] *= s;
  94299. te[6] *= s; te[7] *= s; te[8] *= s;
  94300. return this;
  94301. },
  94302. mul: function (m1, m2) {
  94303. var te = this.elements, tm1 = m1.elements, tm2 = m2.elements,
  94304. a0 = tm1[0], a3 = tm1[3], a6 = tm1[6],
  94305. a1 = tm1[1], a4 = tm1[4], a7 = tm1[7],
  94306. a2 = tm1[2], a5 = tm1[5], a8 = tm1[8],
  94307. b0 = tm2[0], b3 = tm2[3], b6 = tm2[6],
  94308. b1 = tm2[1], b4 = tm2[4], b7 = tm2[7],
  94309. b2 = tm2[2], b5 = tm2[5], b8 = tm2[8];
  94310. te[0] = a0 * b0 + a1 * b3 + a2 * b6;
  94311. te[1] = a0 * b1 + a1 * b4 + a2 * b7;
  94312. te[2] = a0 * b2 + a1 * b5 + a2 * b8;
  94313. te[3] = a3 * b0 + a4 * b3 + a5 * b6;
  94314. te[4] = a3 * b1 + a4 * b4 + a5 * b7;
  94315. te[5] = a3 * b2 + a4 * b5 + a5 * b8;
  94316. te[6] = a6 * b0 + a7 * b3 + a8 * b6;
  94317. te[7] = a6 * b1 + a7 * b4 + a8 * b7;
  94318. te[8] = a6 * b2 + a7 * b5 + a8 * b8;
  94319. return this;
  94320. },
  94321. mulScale: function (m, sx, sy, sz, Prepend) {
  94322. var prepend = Prepend || false;
  94323. var te = this.elements, tm = m.elements;
  94324. if (prepend) {
  94325. te[0] = sx * tm[0]; te[1] = sx * tm[1]; te[2] = sx * tm[2];
  94326. te[3] = sy * tm[3]; te[4] = sy * tm[4]; te[5] = sy * tm[5];
  94327. te[6] = sz * tm[6]; te[7] = sz * tm[7]; te[8] = sz * tm[8];
  94328. } else {
  94329. te[0] = tm[0] * sx; te[1] = tm[1] * sy; te[2] = tm[2] * sz;
  94330. te[3] = tm[3] * sx; te[4] = tm[4] * sy; te[5] = tm[5] * sz;
  94331. te[6] = tm[6] * sx; te[7] = tm[7] * sy; te[8] = tm[8] * sz;
  94332. }
  94333. return this;
  94334. },
  94335. mulRotate: function (m, rad, ax, ay, az, Prepend) {
  94336. var prepend = Prepend || false;
  94337. var s = OIMO.sin(rad);
  94338. var c = OIMO.cos(rad);
  94339. var c1 = 1 - c;
  94340. var r00 = ax * ax * c1 + c;
  94341. var r01 = ax * ay * c1 - az * s;
  94342. var r02 = ax * az * c1 + ay * s;
  94343. var r10 = ay * ax * c1 + az * s;
  94344. var r11 = ay * ay * c1 + c;
  94345. var r12 = ay * az * c1 - ax * s;
  94346. var r20 = az * ax * c1 - ay * s;
  94347. var r21 = az * ay * c1 + ax * s;
  94348. var r22 = az * az * c1 + c;
  94349. var tm = m.elements;
  94350. var a0 = tm[0], a3 = tm[3], a6 = tm[6];
  94351. var a1 = tm[1], a4 = tm[4], a7 = tm[7];
  94352. var a2 = tm[2], a5 = tm[5], a8 = tm[8];
  94353. var te = this.elements;
  94354. if (prepend) {
  94355. te[0] = r00 * a0 + r01 * a3 + r02 * a6;
  94356. te[1] = r00 * a1 + r01 * a4 + r02 * a7;
  94357. te[2] = r00 * a2 + r01 * a5 + r02 * a8;
  94358. te[3] = r10 * a0 + r11 * a3 + r12 * a6;
  94359. te[4] = r10 * a1 + r11 * a4 + r12 * a7;
  94360. te[5] = r10 * a2 + r11 * a5 + r12 * a8;
  94361. te[6] = r20 * a0 + r21 * a3 + r22 * a6;
  94362. te[7] = r20 * a1 + r21 * a4 + r22 * a7;
  94363. te[8] = r20 * a2 + r21 * a5 + r22 * a8;
  94364. } else {
  94365. te[0] = a0 * r00 + a1 * r10 + a2 * r20;
  94366. te[1] = a0 * r01 + a1 * r11 + a2 * r21;
  94367. te[2] = a0 * r02 + a1 * r12 + a2 * r22;
  94368. te[3] = a3 * r00 + a4 * r10 + a5 * r20;
  94369. te[4] = a3 * r01 + a4 * r11 + a5 * r21;
  94370. te[5] = a3 * r02 + a4 * r12 + a5 * r22;
  94371. te[6] = a6 * r00 + a7 * r10 + a8 * r20;
  94372. te[7] = a6 * r01 + a7 * r11 + a8 * r21;
  94373. te[8] = a6 * r02 + a7 * r12 + a8 * r22;
  94374. }
  94375. return this;
  94376. },
  94377. transpose: function (m) {
  94378. var te = this.elements, tm = m.elements;
  94379. te[0] = tm[0]; te[1] = tm[3]; te[2] = tm[6];
  94380. te[3] = tm[1]; te[4] = tm[4]; te[5] = tm[7];
  94381. te[6] = tm[2]; te[7] = tm[5]; te[8] = tm[8];
  94382. return this;
  94383. },
  94384. setQuat: function (q) {
  94385. var te = this.elements,
  94386. x2 = 2 * q.x, y2 = 2 * q.y, z2 = 2 * q.z,
  94387. xx = q.x * x2, yy = q.y * y2, zz = q.z * z2,
  94388. xy = q.x * y2, yz = q.y * z2, xz = q.x * z2,
  94389. sx = q.s * x2, sy = q.s * y2, sz = q.s * z2;
  94390. te[0] = 1 - yy - zz;
  94391. te[1] = xy - sz;
  94392. te[2] = xz + sy;
  94393. te[3] = xy + sz;
  94394. te[4] = 1 - xx - zz;
  94395. te[5] = yz - sx;
  94396. te[6] = xz - sy;
  94397. te[7] = yz + sx;
  94398. te[8] = 1 - xx - yy;
  94399. return this;
  94400. },
  94401. invert: function (m) {
  94402. var te = this.elements, tm = m.elements,
  94403. a0 = tm[0], a3 = tm[3], a6 = tm[6],
  94404. a1 = tm[1], a4 = tm[4], a7 = tm[7],
  94405. a2 = tm[2], a5 = tm[5], a8 = tm[8],
  94406. b01 = a4 * a8 - a7 * a5,
  94407. b11 = a7 * a2 - a1 * a8,
  94408. b21 = a1 * a5 - a4 * a2,
  94409. dt = a0 * (b01) + a3 * (b11) + a6 * (b21);
  94410. if (dt != 0) { dt = 1.0 / dt; }
  94411. te[0] = dt * b01;//(a4*a8 - a5*a7);
  94412. te[1] = dt * b11;//(a2*a7 - a1*a8);
  94413. te[2] = dt * b21;//(a1*a5 - a2*a4);
  94414. te[3] = dt * (a5 * a6 - a3 * a8);
  94415. te[4] = dt * (a0 * a8 - a2 * a6);
  94416. te[5] = dt * (a2 * a3 - a0 * a5);
  94417. te[6] = dt * (a3 * a7 - a4 * a6);
  94418. te[7] = dt * (a1 * a6 - a0 * a7);
  94419. te[8] = dt * (a0 * a4 - a1 * a3);
  94420. return this;
  94421. },
  94422. /*copy: function(m){
  94423. var te = this.elements, tem = m.elements;
  94424. te[0] = tem[0]; te[1] = tem[1]; te[2] = tem[2];
  94425. te[3] = tem[3]; te[4] = tem[4]; te[5] = tem[5];
  94426. te[6] = tem[6]; te[7] = tem[7]; te[8] = tem[8];
  94427. return this;
  94428. },*/
  94429. toEuler: function () { // not work !!
  94430. function clamp(x) {
  94431. return OIMO.min(OIMO.max(x, -1), 1);
  94432. }
  94433. var te = this.elements;
  94434. var m11 = te[0], m12 = te[3], m13 = te[6];
  94435. var m21 = te[1], m22 = te[4], m23 = te[7];
  94436. var m31 = te[2], m32 = te[5], m33 = te[8];
  94437. var p = new OIMO.Vec3();
  94438. var d = new OIMO.Quat();
  94439. var s;
  94440. p.y = OIMO.asin(clamp(m13));
  94441. if (OIMO.abs(m13) < 0.99999) {
  94442. p.x = OIMO.atan2(-m23, m33);
  94443. p.z = OIMO.atan2(-m12, m11);
  94444. } else {
  94445. p.x = OIMO.atan2(m32, m22);
  94446. p.z = 0;
  94447. }
  94448. return p;
  94449. },
  94450. /*clone: function(){
  94451. var te = this.elements;
  94452. return new OIMO.Mat33(
  94453. te[0], te[1], te[2],
  94454. te[3], te[4], te[5],
  94455. te[6], te[7], te[8]
  94456. );
  94457. },*/
  94458. toString: function () {
  94459. var te = this.elements;
  94460. var text =
  94461. "Mat33|" + te[0].toFixed(4) + ", " + te[1].toFixed(4) + ", " + te[2].toFixed(4) + "|\n" +
  94462. " |" + te[3].toFixed(4) + ", " + te[4].toFixed(4) + ", " + te[5].toFixed(4) + "|\n" +
  94463. " |" + te[6].toFixed(4) + ", " + te[7].toFixed(4) + ", " + te[8].toFixed(4) + "|";
  94464. return text;
  94465. },
  94466. // OK
  94467. multiplyScalar: function (s) {
  94468. var te = this.elements;
  94469. te[0] *= s; te[3] *= s; te[6] *= s;
  94470. te[1] *= s; te[4] *= s; te[7] *= s;
  94471. te[2] *= s; te[5] *= s; te[8] *= s;
  94472. return this;
  94473. },
  94474. identity: function () {
  94475. this.set(1, 0, 0, 0, 1, 0, 0, 0, 1);
  94476. return this;
  94477. },
  94478. clone: function () {
  94479. return new this.constructor().fromArray(this.elements);
  94480. },
  94481. copy: function (m) {
  94482. var me = m.elements;
  94483. this.set(
  94484. me[0], me[3], me[6],
  94485. me[1], me[4], me[7],
  94486. me[2], me[5], me[8]
  94487. );
  94488. return this;
  94489. },
  94490. fromArray: function (array) {
  94491. this.elements.set(array);
  94492. return this;
  94493. },
  94494. toArray: function () {
  94495. var te = this.elements;
  94496. return [
  94497. te[0], te[1], te[2],
  94498. te[3], te[4], te[5],
  94499. te[6], te[7], te[8]
  94500. ];
  94501. }
  94502. };
  94503. OIMO.Quat = function (s, x, y, z) {
  94504. this.s = (s !== undefined) ? s : 1;
  94505. this.x = x || 0;
  94506. this.y = y || 0;
  94507. this.z = z || 0;
  94508. };
  94509. OIMO.Quat.prototype = {
  94510. constructor: OIMO.Quat,
  94511. set: function (x, y, z, w) {
  94512. this.x = x;
  94513. this.y = y;
  94514. this.z = z;
  94515. this.s = w;
  94516. return this;
  94517. },
  94518. init: function (s, x, y, z) {
  94519. this.s = (s !== undefined) ? s : 1;
  94520. this.x = x || 0;
  94521. this.y = y || 0;
  94522. this.z = z || 0;
  94523. return this;
  94524. },
  94525. add: function (q1, q2) {
  94526. this.s = q1.s + q2.s;
  94527. this.x = q1.x + q2.x;
  94528. this.y = q1.y + q2.y;
  94529. this.z = q1.z + q2.z;
  94530. return this;
  94531. },
  94532. addTime: function (v, t) {
  94533. var x = v.x;
  94534. var y = v.y;
  94535. var z = v.z;
  94536. var qs = this.s;
  94537. var qx = this.x;
  94538. var qy = this.y;
  94539. var qz = this.z;
  94540. t *= 0.5;
  94541. var ns = (-x * qx - y * qy - z * qz) * t;
  94542. var nx = (x * qs + y * qz - z * qy) * t;
  94543. var ny = (-x * qz + y * qs + z * qx) * t;
  94544. var nz = (x * qy - y * qx + z * qs) * t;
  94545. qs += ns;
  94546. qx += nx;
  94547. qy += ny;
  94548. qz += nz;
  94549. var s = 1 / OIMO.sqrt(qs * qs + qx * qx + qy * qy + qz * qz);
  94550. this.s = qs * s;
  94551. this.x = qx * s;
  94552. this.y = qy * s;
  94553. this.z = qz * s;
  94554. return this;
  94555. },
  94556. sub: function (q1, q2) {
  94557. this.s = q1.s - q2.s;
  94558. this.x = q1.x - q2.x;
  94559. this.y = q1.y - q2.y;
  94560. this.z = q1.z - q2.z;
  94561. return this;
  94562. },
  94563. scale: function (q, s) {
  94564. this.s = q.s * s;
  94565. this.x = q.x * s;
  94566. this.y = q.y * s;
  94567. this.z = q.z * s;
  94568. return this;
  94569. },
  94570. mul: function (q1, q2) {
  94571. var ax = q1.x, ay = q1.y, az = q1.z, as = q1.s,
  94572. bx = q2.x, by = q2.y, bz = q2.z, bs = q2.s;
  94573. this.x = ax * bs + as * bx + ay * bz - az * by;
  94574. this.y = ay * bs + as * by + az * bx - ax * bz;
  94575. this.z = az * bs + as * bz + ax * by - ay * bx;
  94576. this.s = as * bs - ax * bx - ay * by - az * bz;
  94577. return this;
  94578. },
  94579. arc: function (v1, v2) {
  94580. var x1 = v1.x;
  94581. var y1 = v1.y;
  94582. var z1 = v1.z;
  94583. var x2 = v2.x;
  94584. var y2 = v2.y;
  94585. var z2 = v2.z;
  94586. var d = x1 * x2 + y1 * y2 + z1 * z2;
  94587. if (d == -1) {
  94588. x2 = y1 * x1 - z1 * z1;
  94589. y2 = -z1 * y1 - x1 * x1;
  94590. z2 = x1 * z1 + y1 * y1;
  94591. d = 1 / OIMO.sqrt(x2 * x2 + y2 * y2 + z2 * z2);
  94592. this.s = 0;
  94593. this.x = x2 * d;
  94594. this.y = y2 * d;
  94595. this.z = z2 * d;
  94596. return this;
  94597. }
  94598. var cx = y1 * z2 - z1 * y2;
  94599. var cy = z1 * x2 - x1 * z2;
  94600. var cz = x1 * y2 - y1 * x2;
  94601. this.s = OIMO.sqrt((1 + d) * 0.5);
  94602. d = 0.5 / this.s;
  94603. this.x = cx * d;
  94604. this.y = cy * d;
  94605. this.z = cz * d;
  94606. return this;
  94607. },
  94608. normalize: function (q) {
  94609. var len = OIMO.sqrt(q.s * q.s + q.x * q.x + q.y * q.y + q.z * q.z);
  94610. if (len > 0) { len = 1 / len; }
  94611. this.s = q.s * len;
  94612. this.x = q.x * len;
  94613. this.y = q.y * len;
  94614. this.z = q.z * len;
  94615. return this;
  94616. },
  94617. invert: function (q) {
  94618. this.s = q.s;
  94619. this.x = -q.x;
  94620. this.y = -q.y;
  94621. this.z = -q.z;
  94622. return this;
  94623. },
  94624. length: function () {
  94625. return OIMO.sqrt(this.s * this.s + this.x * this.x + this.y * this.y + this.z * this.z);
  94626. },
  94627. copy: function (q) {
  94628. this.s = q.s;
  94629. this.x = q.x;
  94630. this.y = q.y;
  94631. this.z = q.z;
  94632. return this;
  94633. },
  94634. testDiff: function (q) {
  94635. if (this.s !== q.s || this.x !== q.x || this.y !== q.y || this.z !== q.z) return true;
  94636. else return false;
  94637. },
  94638. clone: function (q) {
  94639. return new OIMO.Quat(this.s, this.x, this.y, this.z);
  94640. },
  94641. toString: function () {
  94642. return "Quat[" + this.s.toFixed(4) + ", (" + this.x.toFixed(4) + ", " + this.y.toFixed(4) + ", " + this.z.toFixed(4) + ")]";
  94643. }
  94644. }
  94645. // for three easy export
  94646. OIMO.Quaternion = function (x, y, z, w) {
  94647. this.x = x || 0;
  94648. this.y = y || 0;
  94649. this.z = z || 0;
  94650. this.w = (w !== undefined) ? w : 1;
  94651. };
  94652. OIMO.Quaternion.prototype = {
  94653. constructor: OIMO.Quaternion,
  94654. setFromRotationMatrix: function (m) {
  94655. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  94656. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  94657. var te = m.elements,
  94658. m11 = te[0], m12 = te[1], m13 = te[2],
  94659. m21 = te[3], m22 = te[4], m23 = te[5],
  94660. m31 = te[6], m32 = te[7], m33 = te[8],
  94661. trace = m11 + m22 + m33,
  94662. s;
  94663. if (trace > 0) {
  94664. s = 0.5 / OIMO.sqrt(trace + 1.0);
  94665. this.w = 0.25 / s;
  94666. this.x = (m32 - m23) * s;
  94667. this.y = (m13 - m31) * s;
  94668. this.z = (m21 - m12) * s;
  94669. } else if (m11 > m22 && m11 > m33) {
  94670. s = 2.0 * OIMO.sqrt(1.0 + m11 - m22 - m33);
  94671. this.w = (m32 - m23) / s;
  94672. this.x = 0.25 * s;
  94673. this.y = (m12 + m21) / s;
  94674. this.z = (m13 + m31) / s;
  94675. } else if (m22 > m33) {
  94676. s = 2.0 * OIMO.sqrt(1.0 + m22 - m11 - m33);
  94677. this.w = (m13 - m31) / s;
  94678. this.x = (m12 + m21) / s;
  94679. this.y = 0.25 * s;
  94680. this.z = (m23 + m32) / s;
  94681. } else {
  94682. s = 2.0 * OIMO.sqrt(1.0 + m33 - m11 - m22);
  94683. this.w = (m21 - m12) / s;
  94684. this.x = (m13 + m31) / s;
  94685. this.y = (m23 + m32) / s;
  94686. this.z = 0.25 * s;
  94687. }
  94688. //this.onChangeCallback();
  94689. return this;
  94690. }
  94691. }
  94692. OIMO.Vec3 = function (x, y, z) {
  94693. this.x = x || 0;
  94694. this.y = y || 0;
  94695. this.z = z || 0;
  94696. };
  94697. OIMO.Vec3.prototype = {
  94698. constructor: OIMO.Vec3,
  94699. init: function (x, y, z) {
  94700. this.x = x || 0;
  94701. this.y = y || 0;
  94702. this.z = z || 0;
  94703. return this;
  94704. },
  94705. set: function (x, y, z) {
  94706. this.x = x;
  94707. this.y = y;
  94708. this.z = z;
  94709. return this;
  94710. },
  94711. add: function (v1, v2) {
  94712. this.x = v1.x + v2.x;
  94713. this.y = v1.y + v2.y;
  94714. this.z = v1.z + v2.z;
  94715. return this;
  94716. },
  94717. addEqual: function (v) {
  94718. this.x += v.x;
  94719. this.y += v.y;
  94720. this.z += v.z;
  94721. return this;
  94722. },
  94723. addTime: function (v, t) {
  94724. this.x += v.x * t;
  94725. this.y += v.y * t;
  94726. this.z += v.z * t;
  94727. return this;
  94728. },
  94729. sub: function (v1, v2) {
  94730. this.x = v1.x - v2.x;
  94731. this.y = v1.y - v2.y;
  94732. this.z = v1.z - v2.z;
  94733. return this;
  94734. },
  94735. subEqual: function (v) {
  94736. this.x -= v.x;
  94737. this.y -= v.y;
  94738. this.z -= v.z;
  94739. return this;
  94740. },
  94741. addScale: function (v, s) {
  94742. this.x += v.x * s;
  94743. this.y += v.y * s;
  94744. this.z += v.z * s;
  94745. return this;
  94746. },
  94747. scale: function (v, s) {
  94748. this.x = v.x * s;
  94749. this.y = v.y * s;
  94750. this.z = v.z * s;
  94751. return this;
  94752. },
  94753. scaleEqual: function (s) {
  94754. this.x *= s;
  94755. this.y *= s;
  94756. this.z *= s;
  94757. return this;
  94758. },
  94759. /*dot: function(v){
  94760. return this.x*v.x+this.y*v.y+this.z*v.z;
  94761. },*/
  94762. cross: function (v1, v2) {
  94763. var ax = v1.x, ay = v1.y, az = v1.z,
  94764. bx = v2.x, by = v2.y, bz = v2.z;
  94765. this.x = ay * bz - az * by;
  94766. this.y = az * bx - ax * bz;
  94767. this.z = ax * by - ay * bx;
  94768. return this;
  94769. },
  94770. mul: function (o, v, m) {
  94771. var te = m.elements;
  94772. this.x = o.x + v.x * te[0] + v.y * te[1] + v.z * te[2];
  94773. this.y = o.y + v.x * te[3] + v.y * te[4] + v.z * te[5];
  94774. this.z = o.z + v.x * te[6] + v.y * te[7] + v.z * te[8];
  94775. return this;
  94776. },
  94777. mulMat: function (m, v) {
  94778. var te = m.elements;
  94779. this.x = te[0] * v.x + te[1] * v.y + te[2] * v.z;
  94780. this.y = te[3] * v.x + te[4] * v.y + te[5] * v.z;
  94781. this.z = te[6] * v.x + te[7] * v.y + te[8] * v.z;
  94782. return this;
  94783. },
  94784. normalize: function (v) {
  94785. var x = v.x, y = v.y, z = v.z;
  94786. var l = x * x + y * y + z * z;
  94787. if (l > 0) {
  94788. l = 1 / OIMO.sqrt(l);
  94789. this.x = x * l;
  94790. this.y = y * l;
  94791. this.z = z * l;
  94792. }
  94793. return this;
  94794. },
  94795. /*norm: function(){
  94796. var x = this.x, y = this.y, z = this.z;
  94797. var l = x*x + y*y + z*z;
  94798. if (l > 0) {
  94799. l = 1 / OIMO.sqrt(l);
  94800. this.x = x*l;
  94801. this.y = y*l;
  94802. this.z = z*l;
  94803. }
  94804. return this;
  94805. },*/
  94806. invert: function (v) {
  94807. this.x = -v.x;
  94808. this.y = -v.y;
  94809. this.z = -v.z;
  94810. return this;
  94811. },
  94812. /*length: function(){
  94813. var x = this.x, y = this.y, z = this.z;
  94814. return OIMO.sqrt(x*x + y*y + z*z);
  94815. },*/
  94816. negate: function () {
  94817. this.x = -this.x;
  94818. this.y = -this.y;
  94819. this.z = -this.z;
  94820. return this;
  94821. },
  94822. dot: function (v) {
  94823. return this.x * v.x + this.y * v.y + this.z * v.z;
  94824. },
  94825. lengthSq: function () {
  94826. return this.x * this.x + this.y * this.y + this.z * this.z;
  94827. },
  94828. length: function () {
  94829. return OIMO.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  94830. },
  94831. /*len: function(){
  94832. var x = this.x, y = this.y, z = this.z;
  94833. return x*x + y*y + z*z;
  94834. },*/
  94835. copy: function (v) {
  94836. this.x = v.x;
  94837. this.y = v.y;
  94838. this.z = v.z;
  94839. return this;
  94840. },
  94841. applyQuaternion: function (q) {
  94842. var x = this.x;
  94843. var y = this.y;
  94844. var z = this.z;
  94845. var qx = q.x;
  94846. var qy = q.y;
  94847. var qz = q.z;
  94848. var qs = q.s;
  94849. // calculate quat * vector
  94850. var ix = qs * x + qy * z - qz * y;
  94851. var iy = qs * y + qz * x - qx * z;
  94852. var iz = qs * z + qx * y - qy * x;
  94853. var iw = -qx * x - qy * y - qz * z;
  94854. // calculate result * inverse quat
  94855. this.x = ix * qs + iw * -qx + iy * -qz - iz * -qy;
  94856. this.y = iy * qs + iw * -qy + iz * -qx - ix * -qz;
  94857. this.z = iz * qs + iw * -qz + ix * -qy - iy * -qx;
  94858. return this;
  94859. },
  94860. testZero: function () {
  94861. if (this.x !== 0 || this.y !== 0 || this.z !== 0) return true;
  94862. else return false;
  94863. },
  94864. testDiff: function (v) {
  94865. return ((v.x !== this.x) || (v.y !== this.y) || (v.z !== this.z));
  94866. //if(this.x!==v.x || this.y!==v.y || this.z!==v.z) return true;
  94867. //else return false;
  94868. },
  94869. equals: function (v) {
  94870. return ((v.x === this.x) && (v.y === this.y) && (v.z === this.z));
  94871. },
  94872. clone: function () {
  94873. return new this.constructor(this.x, this.y, this.z);
  94874. },
  94875. toString: function () {
  94876. return "Vec3[" + this.x.toFixed(4) + ", " + this.y.toFixed(4) + ", " + this.z.toFixed(4) + "]";
  94877. },
  94878. multiplyScalar: function (scalar) {
  94879. if (isFinite(scalar)) {
  94880. this.x *= scalar;
  94881. this.y *= scalar;
  94882. this.z *= scalar;
  94883. } else {
  94884. this.x = 0;
  94885. this.y = 0;
  94886. this.z = 0;
  94887. }
  94888. return this;
  94889. },
  94890. divideScalar: function (scalar) {
  94891. return this.multiplyScalar(1 / scalar);
  94892. },
  94893. // TODO rename to normalize
  94894. norm: function () {
  94895. return this.divideScalar(this.length());
  94896. },
  94897. }
  94898. OIMO.Euler = function (x, y, z, order) {
  94899. this._x = x || 0;
  94900. this._y = y || 0;
  94901. this._z = z || 0;
  94902. this._order = order || OIMO.Euler.DefaultOrder;
  94903. };
  94904. OIMO.Euler.RotationOrders = ['XYZ', 'YZX', 'ZXY', 'XZY', 'YXZ', 'ZYX'];
  94905. OIMO.Euler.DefaultOrder = 'XYZ';
  94906. OIMO.clamp = function (x, a, b) {
  94907. return (x < a) ? a : ((x > b) ? b : x);
  94908. }
  94909. OIMO.Euler.prototype = {
  94910. constructor: OIMO.Euler,
  94911. _x: 0, _y: 0, _z: 0, _order: OIMO.Euler.DefaultOrder,
  94912. get x() {
  94913. return this._x;
  94914. },
  94915. set x(value) {
  94916. this._x = value;
  94917. this.onChangeCallback();
  94918. },
  94919. get y() {
  94920. return this._y;
  94921. },
  94922. set y(value) {
  94923. this._y = value;
  94924. this.onChangeCallback();
  94925. },
  94926. get z() {
  94927. return this._z;
  94928. },
  94929. set z(value) {
  94930. this._z = value;
  94931. this.onChangeCallback();
  94932. },
  94933. get order() {
  94934. return this._order;
  94935. },
  94936. set order(value) {
  94937. this._order = value;
  94938. this.onChangeCallback();
  94939. },
  94940. set: function (x, y, z, order) {
  94941. this._x = x;
  94942. this._y = y;
  94943. this._z = z;
  94944. this._order = order || this._order;
  94945. this.onChangeCallback();
  94946. return this;
  94947. },
  94948. copy: function (euler) {
  94949. this._x = euler._x;
  94950. this._y = euler._y;
  94951. this._z = euler._z;
  94952. this._order = euler._order;
  94953. this.onChangeCallback();
  94954. return this;
  94955. },
  94956. setFromRotationMatrix: function (m, order) {
  94957. var clamp = OIMO.clamp;
  94958. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  94959. var te = m.elements;
  94960. /*var m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ];
  94961. var m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ];
  94962. var m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];*/
  94963. var m11 = te[0], m12 = te[1], m13 = te[2],
  94964. m21 = te[3], m22 = te[4], m23 = te[5],
  94965. m31 = te[6], m32 = te[7], m33 = te[8];
  94966. order = order || this._order;
  94967. if (order === 'XYZ') {
  94968. this._y = OIMO.asin(clamp(m13, -1, 1));
  94969. if (OIMO.abs(m13) < 0.99999) {
  94970. this._x = OIMO.atan2(-m23, m33);
  94971. this._z = OIMO.atan2(-m12, m11);
  94972. } else {
  94973. this._x = OIMO.atan2(m32, m22);
  94974. this._z = 0;
  94975. }
  94976. } else if (order === 'YXZ') {
  94977. this._x = OIMO.asin(-clamp(m23, -1, 1));
  94978. if (OIMO.abs(m23) < 0.99999) {
  94979. this._y = OIMO.atan2(m13, m33);
  94980. this._z = OIMO.atan2(m21, m22);
  94981. } else {
  94982. this._y = OIMO.atan2(-m31, m11);
  94983. this._z = 0;
  94984. }
  94985. } else if (order === 'ZXY') {
  94986. this._x = OIMO.asin(clamp(m32, -1, 1));
  94987. if (OIMO.abs(m32) < 0.99999) {
  94988. this._y = OIMO.atan2(-m31, m33);
  94989. this._z = OIMO.atan2(-m12, m22);
  94990. } else {
  94991. this._y = 0;
  94992. this._z = OIMO.atan2(m21, m11);
  94993. }
  94994. } else if (order === 'ZYX') {
  94995. this._y = OIMO.asin(-clamp(m31, -1, 1));
  94996. if (OIMO.abs(m31) < 0.99999) {
  94997. this._x = OIMO.atan2(m32, m33);
  94998. this._z = OIMO.atan2(m21, m11);
  94999. } else {
  95000. this._x = 0;
  95001. this._z = OIMO.atan2(-m12, m22);
  95002. }
  95003. } else if (order === 'YZX') {
  95004. this._z = OIMO.asin(clamp(m21, -1, 1));
  95005. if (OIMO.abs(m21) < 0.99999) {
  95006. this._x = OIMO.atan2(-m23, m22);
  95007. this._y = OIMO.atan2(-m31, m11);
  95008. } else {
  95009. this._x = 0;
  95010. this._y = OIMO.atan2(m13, m33);
  95011. }
  95012. } else if (order === 'XZY') {
  95013. this._z = OIMO.asin(-clamp(m12, -1, 1));
  95014. if (OIMO.abs(m12) < 0.99999) {
  95015. this._x = OIMO.atan2(m32, m22);
  95016. this._y = OIMO.atan2(m13, m11);
  95017. } else {
  95018. this._x = OIMO.atan2(-m23, m33);
  95019. this._y = 0;
  95020. }
  95021. } else {
  95022. console.warn('THREE.Euler: .setFromRotationMatrix() given unsupported order: ' + order)
  95023. }
  95024. this._order = order;
  95025. this.onChangeCallback();
  95026. return this;
  95027. },
  95028. setFromQuaternion: function (q, order, update) {
  95029. var clamp = OIMO.clamp;
  95030. // q is assumed to be normalized
  95031. // http://www.mathworks.com/matlabcentral/fileexchange/20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/content/SpinCalc.m
  95032. var sqx = q.x * q.x;
  95033. var sqy = q.y * q.y;
  95034. var sqz = q.z * q.z;
  95035. var sqw = q.s * q.s;
  95036. order = order || this._order;
  95037. if (order === 'XYZ') {
  95038. this._x = OIMO.atan2(2 * (q.x * q.s - q.y * q.z), (sqw - sqx - sqy + sqz));
  95039. this._y = OIMO.asin(clamp(2 * (q.x * q.z + q.y * q.s), -1, 1));
  95040. this._z = OIMO.atan2(2 * (q.z * q.s - q.x * q.y), (sqw + sqx - sqy - sqz));
  95041. } else if (order === 'YXZ') {
  95042. this._x = OIMO.asin(clamp(2 * (q.x * q.s - q.y * q.z), -1, 1));
  95043. this._y = OIMO.atan2(2 * (q.x * q.z + q.y * q.s), (sqw - sqx - sqy + sqz));
  95044. this._z = OIMO.atan2(2 * (q.x * q.y + q.z * q.s), (sqw - sqx + sqy - sqz));
  95045. } else if (order === 'ZXY') {
  95046. this._x = OIMO.asin(clamp(2 * (q.x * q.s + q.y * q.z), -1, 1));
  95047. this._y = OIMO.atan2(2 * (q.y * q.s - q.z * q.x), (sqw - sqx - sqy + sqz));
  95048. this._z = OIMO.atan2(2 * (q.z * q.s - q.x * q.y), (sqw - sqx + sqy - sqz));
  95049. } else if (order === 'ZYX') {
  95050. this._x = OIMO.atan2(2 * (q.x * q.s + q.z * q.y), (sqw - sqx - sqy + sqz));
  95051. this._y = OIMO.asin(clamp(2 * (q.y * q.s - q.x * q.z), -1, 1));
  95052. this._z = OIMO.atan2(2 * (q.x * q.y + q.z * q.s), (sqw + sqx - sqy - sqz));
  95053. } else if (order === 'YZX') {
  95054. this._x = OIMO.atan2(2 * (q.x * q.s - q.z * q.y), (sqw - sqx + sqy - sqz));
  95055. this._y = OIMO.atan2(2 * (q.y * q.s - q.x * q.z), (sqw + sqx - sqy - sqz));
  95056. this._z = OIMO.asin(clamp(2 * (q.x * q.y + q.z * q.s), -1, 1));
  95057. } else if (order === 'XZY') {
  95058. this._x = OIMO.atan2(2 * (q.x * q.s + q.y * q.z), (sqw - sqx + sqy - sqz));
  95059. this._y = OIMO.atan2(2 * (q.x * q.z + q.y * q.s), (sqw + sqx - sqy - sqz));
  95060. this._z = OIMO.asin(clamp(2 * (q.z * q.s - q.x * q.y), -1, 1));
  95061. } else {
  95062. console.warn('OIMO.Euler: .setFromQuaternion() given unsupported order: ' + order)
  95063. }
  95064. this._order = order;
  95065. if (update !== false) this.onChangeCallback();
  95066. return this;
  95067. },
  95068. reorder: function () {
  95069. // WARNING: this discards revolution information -bhouston
  95070. var q = new OIMO.Quat();
  95071. return function (newOrder) {
  95072. q.setFromEuler(this);
  95073. this.setFromQuaternion(q, newOrder);
  95074. };
  95075. }(),
  95076. equals: function (euler) {
  95077. return (euler._x === this._x) && (euler._y === this._y) && (euler._z === this._z) && (euler._order === this._order);
  95078. },
  95079. fromArray: function (array) {
  95080. this._x = array[0];
  95081. this._y = array[1];
  95082. this._z = array[2];
  95083. if (array[3] !== undefined) this._order = array[3];
  95084. this.onChangeCallback();
  95085. return this;
  95086. },
  95087. toArray: function () {
  95088. return [this._x, this._y, this._z, this._order];
  95089. },
  95090. onChange: function (callback) {
  95091. this.onChangeCallback = callback;
  95092. return this;
  95093. },
  95094. onChangeCallback: function () { },
  95095. clone: function () {
  95096. return new OIMO.Euler(this._x, this._y, this._z, this._order);
  95097. }
  95098. };
  95099. OIMO.EulerToAxis = function (ox, oy, oz) {// angles in radians
  95100. var c1 = OIMO.cos(oy * 0.5);//heading
  95101. var s1 = OIMO.sin(oy * 0.5);
  95102. var c2 = OIMO.cos(oz * 0.5);//altitude
  95103. var s2 = OIMO.sin(oz * 0.5);
  95104. var c3 = OIMO.cos(ox * 0.5);//bank
  95105. var s3 = OIMO.sin(ox * 0.5);
  95106. var c1c2 = c1 * c2;
  95107. var s1s2 = s1 * s2;
  95108. var w = c1c2 * c3 - s1s2 * s3;
  95109. var x = c1c2 * s3 + s1s2 * c3;
  95110. var y = s1 * c2 * c3 + c1 * s2 * s3;
  95111. var z = c1 * s2 * c3 - s1 * c2 * s3;
  95112. var angle = 2 * OIMO.acos(w);
  95113. var norm = x * x + y * y + z * z;
  95114. if (norm < 0.001) {
  95115. x = 1;
  95116. y = z = 0;
  95117. } else {
  95118. norm = OIMO.sqrt(norm);
  95119. x /= norm;
  95120. y /= norm;
  95121. z /= norm;
  95122. }
  95123. return [angle, x, y, z];
  95124. }
  95125. OIMO.EulerToMatrix = function (ox, oy, oz) {// angles in radians
  95126. var ch = OIMO.cos(oy);//heading
  95127. var sh = OIMO.sin(oy);
  95128. var ca = OIMO.cos(oz);//altitude
  95129. var sa = OIMO.sin(oz);
  95130. var cb = OIMO.cos(ox);//bank
  95131. var sb = OIMO.sin(ox);
  95132. var mtx = new OIMO.Mat33();
  95133. var te = mtx.elements;
  95134. te[0] = ch * ca;
  95135. te[1] = sh * sb - ch * sa * cb;
  95136. te[2] = ch * sa * sb + sh * cb;
  95137. te[3] = sa;
  95138. te[4] = ca * cb;
  95139. te[5] = -ca * sb;
  95140. te[6] = -sh * ca;
  95141. te[7] = sh * sa * cb + ch * sb;
  95142. te[8] = -sh * sa * sb + ch * cb;
  95143. return mtx;
  95144. }
  95145. OIMO.MatrixToEuler = function (mtx) {// angles in radians
  95146. var te = mtx.elements;
  95147. var x, y, z;
  95148. if (te[3] > 0.998) { // singularity at north pole
  95149. y = OIMO.atan2(te[2], te[8]);
  95150. z = OIMO.PI / 2;
  95151. x = 0;
  95152. } else if (te[3] < -0.998) { // singularity at south pole
  95153. y = OIMO.atan2(te[2], te[8]);
  95154. z = -OIMO.PI / 2;
  95155. x = 0;
  95156. } else {
  95157. y = OIMO.atan2(-te[6], te[0]);
  95158. x = OIMO.atan2(-te[5], te[4]);
  95159. z = OIMO.asin(te[3]);
  95160. }
  95161. return [x, y, z];
  95162. }
  95163. OIMO.unwrapDegrees = function (r) {
  95164. r = r % 360;
  95165. if (r > 180) r -= 360;
  95166. if (r < -180) r += 360;
  95167. return r;
  95168. }
  95169. OIMO.unwrapRadian = function (r) {
  95170. r = r % OIMO.TwoPI;
  95171. if (r > OIMO.PI) r -= OIMO.TwoPI;
  95172. if (r < -OIMO.PI) r += OIMO.TwoPI;
  95173. return r;
  95174. }
  95175. OIMO.Distance3d = function (p1, p2) {
  95176. var xd = p2[0] - p1[0];
  95177. var yd = p2[1] - p1[1];
  95178. var zd = p2[2] - p1[2];
  95179. return OIMO.sqrt(xd * xd + yd * yd + zd * zd);
  95180. }
  95181. /**
  95182. * The base class of all type of the constraints.
  95183. * @author saharan
  95184. */
  95185. OIMO.Constraint = function () {
  95186. // The parent world of the constraint.
  95187. this.parent = null;
  95188. // The first body of the constraint.
  95189. this.body1 = null;
  95190. // The second body of the constraint.
  95191. this.body2 = null;
  95192. // Internal
  95193. this.addedToIsland = false;
  95194. }
  95195. OIMO.Constraint.prototype = {
  95196. constructor: OIMO.Constraint,
  95197. /**
  95198. * Prepare for solving the constraint.
  95199. * @param timeStep
  95200. * @param invTimeStep
  95201. */
  95202. preSolve: function (timeStep, invTimeStep) {
  95203. OIMO.Error("Constraint", "Inheritance error.");
  95204. },
  95205. /**
  95206. * Solve the constraint.
  95207. * This is usually called iteratively.
  95208. */
  95209. solve: function () {
  95210. OIMO.Error("Constraint", "Inheritance error.");
  95211. },
  95212. /**
  95213. * Do the post-processing.
  95214. */
  95215. postSolve: function () {
  95216. OIMO.Error("Constraint", "Inheritance error.");
  95217. }
  95218. }
  95219. /**
  95220. * Joints are used to constrain the motion between two rigid bodies.
  95221. * @author saharan
  95222. * @author lo-th
  95223. */
  95224. OIMO.Joint = function (config) {
  95225. OIMO.Constraint.call(this);
  95226. // joint name
  95227. this.name = "";
  95228. // The type of the joint.
  95229. this.type = OIMO.JOINT_NULL;
  95230. // The previous joint in the world.
  95231. this.prev = null;
  95232. // The next joint in the world.
  95233. this.next = null;
  95234. this.body1 = config.body1;
  95235. this.body2 = config.body2;
  95236. // The anchor point on the first rigid body in local coordinate system.
  95237. this.localAnchorPoint1 = new OIMO.Vec3().copy(config.localAnchorPoint1);
  95238. // The anchor point on the second rigid body in local coordinate system.
  95239. this.localAnchorPoint2 = new OIMO.Vec3().copy(config.localAnchorPoint2);
  95240. // The anchor point on the first rigid body in world coordinate system relative to the body's origin.
  95241. this.relativeAnchorPoint1 = new OIMO.Vec3();
  95242. // The anchor point on the second rigid body in world coordinate system relative to the body's origin.
  95243. this.relativeAnchorPoint2 = new OIMO.Vec3();
  95244. // The anchor point on the first rigid body in world coordinate system.
  95245. this.anchorPoint1 = new OIMO.Vec3();
  95246. // The anchor point on the second rigid body in world coordinate system.
  95247. this.anchorPoint2 = new OIMO.Vec3();
  95248. // Whether allow collision between connected rigid bodies or not.
  95249. this.allowCollision = config.allowCollision;
  95250. this.b1Link = new OIMO.JointLink(this);
  95251. this.b2Link = new OIMO.JointLink(this);
  95252. this.matrix = new OIMO.Mat44();
  95253. };
  95254. OIMO.Joint.prototype = Object.create(OIMO.Constraint.prototype);
  95255. OIMO.Joint.prototype.constructor = OIMO.Joint;
  95256. // Update all the anchor points.
  95257. OIMO.Joint.prototype.updateAnchorPoints = function () {
  95258. this.relativeAnchorPoint1.mulMat(this.body1.rotation, this.localAnchorPoint1);
  95259. this.relativeAnchorPoint2.mulMat(this.body2.rotation, this.localAnchorPoint2);
  95260. this.anchorPoint1.add(this.relativeAnchorPoint1, this.body1.position);
  95261. this.anchorPoint2.add(this.relativeAnchorPoint2, this.body2.position);
  95262. };
  95263. // Attach the joint from the bodies.
  95264. OIMO.Joint.prototype.attach = function () {
  95265. this.b1Link.body = this.body2;
  95266. this.b2Link.body = this.body1;
  95267. if (this.body1.jointLink != null) (this.b1Link.next = this.body1.jointLink).prev = this.b1Link;
  95268. else this.b1Link.next = null;
  95269. this.body1.jointLink = this.b1Link;
  95270. this.body1.numJoints++;
  95271. if (this.body2.jointLink != null) (this.b2Link.next = this.body2.jointLink).prev = this.b2Link;
  95272. else this.b2Link.next = null;
  95273. this.body2.jointLink = this.b2Link;
  95274. this.body2.numJoints++;
  95275. };
  95276. // Detach the joint from the bodies.
  95277. OIMO.Joint.prototype.detach = function () {
  95278. var prev = this.b1Link.prev;
  95279. var next = this.b1Link.next;
  95280. if (prev != null) prev.next = next;
  95281. if (next != null) next.prev = prev;
  95282. if (this.body1.jointLink == this.b1Link) this.body1.jointLink = next;
  95283. this.b1Link.prev = null;
  95284. this.b1Link.next = null;
  95285. this.b1Link.body = null;
  95286. this.body1.numJoints--;
  95287. prev = this.b2Link.prev;
  95288. next = this.b2Link.next;
  95289. if (prev != null) prev.next = next;
  95290. if (next != null) next.prev = prev;
  95291. if (this.body2.jointLink == this.b2Link) this.body2.jointLink = next;
  95292. this.b2Link.prev = null;
  95293. this.b2Link.next = null;
  95294. this.b2Link.body = null;
  95295. this.body2.numJoints--;
  95296. this.b1Link.body = null;
  95297. this.b2Link.body = null;
  95298. };
  95299. // Awake the bodies.
  95300. OIMO.Joint.prototype.awake = function () {
  95301. this.body1.awake();
  95302. this.body2.awake();
  95303. };
  95304. // calculation function
  95305. OIMO.Joint.prototype.preSolve = function (timeStep, invTimeStep) {
  95306. };
  95307. OIMO.Joint.prototype.solve = function () {
  95308. };
  95309. OIMO.Joint.prototype.postSolve = function () {
  95310. };
  95311. // Delete process
  95312. OIMO.Joint.prototype.remove = function () {
  95313. this.dispose();
  95314. };
  95315. OIMO.Joint.prototype.dispose = function () {
  95316. this.parent.removeJoint(this);
  95317. };
  95318. // Three js add
  95319. OIMO.Joint.prototype.getPosition = function () {
  95320. var p1 = new OIMO.Vec3().scale(this.anchorPoint1, OIMO.WORLD_SCALE);
  95321. var p2 = new OIMO.Vec3().scale(this.anchorPoint2, OIMO.WORLD_SCALE);
  95322. return [p1, p2];
  95323. };
  95324. OIMO.Joint.prototype.getMatrix = function () {
  95325. var m = this.matrix.elements;
  95326. var p1 = this.anchorPoint1;
  95327. var p2 = this.anchorPoint2;
  95328. m[0] = p1.x * OIMO.WORLD_SCALE;
  95329. m[1] = p1.y * OIMO.WORLD_SCALE;
  95330. m[2] = p1.z * OIMO.WORLD_SCALE;
  95331. m[3] = 0;
  95332. m[4] = p2.x * OIMO.WORLD_SCALE;
  95333. m[5] = p2.y * OIMO.WORLD_SCALE;
  95334. m[6] = p2.z * OIMO.WORLD_SCALE;
  95335. m[7] = 0;
  95336. return m;
  95337. };
  95338. /**
  95339. * A joint configuration holds all configuration data for constructing a joint.
  95340. * Joint configurations can be reused safely.
  95341. * @author saharan
  95342. */
  95343. OIMO.JointConfig = function () {
  95344. // The first rigid body of the joint.
  95345. this.body1 = null;
  95346. // The second rigid body of the joint.
  95347. this.body2 = null;
  95348. // The anchor point on the first rigid body in local coordinate system.
  95349. this.localAnchorPoint1 = new OIMO.Vec3();
  95350. // The anchor point on the second rigid body in local coordinate system.
  95351. this.localAnchorPoint2 = new OIMO.Vec3();
  95352. // The axis in the first body's coordinate system.
  95353. // his property is available in some joints.
  95354. this.localAxis1 = new OIMO.Vec3();
  95355. // The axis in the second body's coordinate system.
  95356. // This property is available in some joints.
  95357. this.localAxis2 = new OIMO.Vec3();
  95358. // Whether allow collision between connected rigid bodies or not.
  95359. this.allowCollision = false;
  95360. };
  95361. /**
  95362. * A link list of joints.
  95363. * @author saharan
  95364. */
  95365. OIMO.JointLink = function (joint) {
  95366. // The previous joint link.
  95367. this.prev = null;
  95368. // The next joint link.
  95369. this.next = null;
  95370. // The other rigid body connected to the joint.
  95371. this.body = null;
  95372. // The joint of the link.
  95373. this.joint = joint;
  95374. };
  95375. /**
  95376. * An information of limit and motor.
  95377. * @author saharan
  95378. */
  95379. OIMO.LimitMotor = function (axis, fixed) {
  95380. fixed = fixed || false;
  95381. // The axis of the constraint.
  95382. this.axis = axis;
  95383. // The current angle for rotational constraints.
  95384. this.angle = 0;
  95385. // The lower limit. Set lower > upper to disable
  95386. this.lowerLimit = fixed ? 0 : 1;
  95387. //if(fixed)this.lowerLimit = 0;
  95388. //else this.lowerLimit = 1;
  95389. // The upper limit. Set lower > upper to disable.
  95390. this.upperLimit = 0;
  95391. // The target motor speed.
  95392. this.motorSpeed = 0;
  95393. // The maximum motor force or torque. Set 0 to disable.
  95394. this.maxMotorForce = 0;
  95395. // The frequency of the spring. Set 0 to disable.
  95396. this.frequency = 0;
  95397. // The damping ratio of the spring. Set 0 for no damping, 1 for critical damping.
  95398. this.dampingRatio = 0;
  95399. };
  95400. OIMO.LimitMotor.prototype = {
  95401. constructor: OIMO.LimitMotor,
  95402. /**
  95403. * Set limit data into this constraint.
  95404. * @param lowerLimit
  95405. * @param upperLimit
  95406. */
  95407. setLimit: function (lowerLimit, upperLimit) {
  95408. this.lowerLimit = lowerLimit;
  95409. this.upperLimit = upperLimit;
  95410. },
  95411. /**
  95412. * Set motor data into this constraint.
  95413. * @param motorSpeed
  95414. * @param maxMotorForce
  95415. */
  95416. setMotor: function (motorSpeed, maxMotorForce) {
  95417. this.motorSpeed = motorSpeed;
  95418. this.maxMotorForce = maxMotorForce;
  95419. },
  95420. /**
  95421. * Set spring data into this constraint.
  95422. * @param frequency
  95423. * @param dampingRatio
  95424. */
  95425. setSpring: function (frequency, dampingRatio) {
  95426. this.frequency = frequency;
  95427. this.dampingRatio = dampingRatio;
  95428. }
  95429. };
  95430. /**
  95431. * A ball-and-socket joint limits relative translation on two anchor points on rigid bodies.
  95432. * @author saharan
  95433. * @author lo-th
  95434. */
  95435. OIMO.BallAndSocketJoint = function (config) {
  95436. OIMO.Joint.call(this, config);
  95437. this.type = OIMO.JOINT_BALL_AND_SOCKET;
  95438. this.lc = new OIMO.LinearConstraint(this);
  95439. };
  95440. OIMO.BallAndSocketJoint.prototype = Object.create(OIMO.Joint.prototype);
  95441. OIMO.BallAndSocketJoint.prototype.constructor = OIMO.BallAndSocketJoint;
  95442. OIMO.BallAndSocketJoint.prototype.preSolve = function (timeStep, invTimeStep) {
  95443. this.updateAnchorPoints();
  95444. this.lc.preSolve(timeStep, invTimeStep);
  95445. };
  95446. OIMO.BallAndSocketJoint.prototype.solve = function () {
  95447. this.lc.solve();
  95448. };
  95449. OIMO.BallAndSocketJoint.prototype.postSolve = function () {
  95450. };
  95451. /**
  95452. * A distance joint limits the distance between two anchor points on rigid bodies.
  95453. * @author saharan
  95454. * @author lo-th
  95455. */
  95456. OIMO.DistanceJoint = function (config, minDistance, maxDistance) {
  95457. OIMO.Joint.call(this, config);
  95458. this.type = OIMO.JOINT_DISTANCE;
  95459. this.normal = new OIMO.Vec3();
  95460. this.nr = new OIMO.Vec3();
  95461. // The limit and motor information of the joint.
  95462. this.limitMotor = new OIMO.LimitMotor(this.normal, true);
  95463. this.limitMotor.lowerLimit = minDistance;
  95464. this.limitMotor.upperLimit = maxDistance;
  95465. this.t = new OIMO.TranslationalConstraint(this, this.limitMotor);
  95466. };
  95467. OIMO.DistanceJoint.prototype = Object.create(OIMO.Joint.prototype);
  95468. OIMO.DistanceJoint.prototype.constructor = OIMO.DistanceJoint;
  95469. OIMO.DistanceJoint.prototype.preSolve = function (timeStep, invTimeStep) {
  95470. this.updateAnchorPoints();
  95471. //var nr = this.nr;
  95472. this.nr.sub(this.anchorPoint2, this.anchorPoint1);
  95473. //var len = OIMO.sqrt( nr.x*nr.x + nr.y*nr.y + nr.z*nr.z );
  95474. //if(len>0) len = 1/len;
  95475. //this.normal.scale( nr, len );
  95476. this.normal.normalize(this.nr);
  95477. this.t.preSolve(timeStep, invTimeStep);
  95478. };
  95479. OIMO.DistanceJoint.prototype.solve = function () {
  95480. this.t.solve();
  95481. };
  95482. OIMO.DistanceJoint.prototype.postSolve = function () {
  95483. };
  95484. /**
  95485. * A hinge joint allows only for relative rotation of rigid bodies along the axis.
  95486. * @author saharan
  95487. * @author lo-th
  95488. */
  95489. OIMO.HingeJoint = function (config, lowerAngleLimit, upperAngleLimit) {
  95490. OIMO.Joint.call(this, config);
  95491. this.type = OIMO.JOINT_HINGE;
  95492. // The axis in the first body's coordinate system.
  95493. this.localAxis1 = config.localAxis1.clone().norm();
  95494. // The axis in the second body's coordinate system.
  95495. this.localAxis2 = config.localAxis2.clone().norm();
  95496. // make angle axis 1
  95497. this.localAngle1 = new OIMO.Vec3(
  95498. this.localAxis1.y * this.localAxis1.x - this.localAxis1.z * this.localAxis1.z,
  95499. -this.localAxis1.z * this.localAxis1.y - this.localAxis1.x * this.localAxis1.x,
  95500. this.localAxis1.x * this.localAxis1.z + this.localAxis1.y * this.localAxis1.y
  95501. ).norm();
  95502. // make angle axis 2
  95503. var arc = new OIMO.Mat33().setQuat(new OIMO.Quat().arc(this.localAxis1, this.localAxis2));
  95504. this.localAngle2 = new OIMO.Vec3().mulMat(arc, this.localAngle1);
  95505. this.nor = new OIMO.Vec3();
  95506. this.tan = new OIMO.Vec3();
  95507. this.bin = new OIMO.Vec3();
  95508. this.ax1 = new OIMO.Vec3();
  95509. this.ax2 = new OIMO.Vec3();
  95510. this.an1 = new OIMO.Vec3();
  95511. this.an2 = new OIMO.Vec3();
  95512. // The rotational limit and motor information of the joint.
  95513. this.limitMotor = new OIMO.LimitMotor(this.nor, false);
  95514. this.limitMotor.lowerLimit = lowerAngleLimit;
  95515. this.limitMotor.upperLimit = upperAngleLimit;
  95516. this.lc = new OIMO.LinearConstraint(this);
  95517. this.r3 = new OIMO.Rotational3Constraint(this, this.limitMotor, new OIMO.LimitMotor(this.tan, true), new OIMO.LimitMotor(this.bin, true));
  95518. };
  95519. OIMO.HingeJoint.prototype = Object.create(OIMO.Joint.prototype);
  95520. OIMO.HingeJoint.prototype.constructor = OIMO.HingeJoint;
  95521. OIMO.HingeJoint.prototype.preSolve = function (timeStep, invTimeStep) {
  95522. var tmp1X, tmp1Y, tmp1Z, limite;//, nx, ny, nz, tx, ty, tz, bx, by, bz;
  95523. this.updateAnchorPoints();
  95524. this.ax1.mulMat(this.body1.rotation, this.localAxis1);
  95525. this.ax2.mulMat(this.body2.rotation, this.localAxis2);
  95526. this.an1.mulMat(this.body1.rotation, this.localAngle1);
  95527. this.an2.mulMat(this.body2.rotation, this.localAngle2);
  95528. this.nor.set(
  95529. this.ax1.x * this.body2.inverseMass + this.ax2.x * this.body1.inverseMass,
  95530. this.ax1.y * this.body2.inverseMass + this.ax2.y * this.body1.inverseMass,
  95531. this.ax1.z * this.body2.inverseMass + this.ax2.z * this.body1.inverseMass
  95532. ).norm();
  95533. this.tan.set(
  95534. this.nor.y * this.nor.x - this.nor.z * this.nor.z,
  95535. -this.nor.z * this.nor.y - this.nor.x * this.nor.x,
  95536. this.nor.x * this.nor.z + this.nor.y * this.nor.y
  95537. ).norm();
  95538. this.bin.set(
  95539. this.nor.y * this.tan.z - this.nor.z * this.tan.y,
  95540. this.nor.z * this.tan.x - this.nor.x * this.tan.z,
  95541. this.nor.x * this.tan.y - this.nor.y * this.tan.x
  95542. );
  95543. // calculate hinge angle
  95544. limite = this.acosClamp(this.an1.x * this.an2.x + this.an1.y * this.an2.y + this.an1.z * this.an2.z)
  95545. if (
  95546. this.nor.x * (this.an1.y * this.an2.z - this.an1.z * this.an2.y) +
  95547. this.nor.y * (this.an1.z * this.an2.x - this.an1.x * this.an2.z) +
  95548. this.nor.z * (this.an1.x * this.an2.y - this.an1.y * this.an2.x) < 0
  95549. ) {
  95550. this.limitMotor.angle = -limite;
  95551. } else {
  95552. this.limitMotor.angle = limite;
  95553. }
  95554. tmp1X = this.ax1.y * this.ax2.z - this.ax1.z * this.ax2.y;
  95555. tmp1Y = this.ax1.z * this.ax2.x - this.ax1.x * this.ax2.z;
  95556. tmp1Z = this.ax1.x * this.ax2.y - this.ax1.y * this.ax2.x;
  95557. this.r3.limitMotor2.angle = this.tan.x * tmp1X + this.tan.y * tmp1Y + this.tan.z * tmp1Z;
  95558. this.r3.limitMotor3.angle = this.bin.x * tmp1X + this.bin.y * tmp1Y + this.bin.z * tmp1Z;
  95559. this.r3.preSolve(timeStep, invTimeStep);
  95560. this.lc.preSolve(timeStep, invTimeStep);
  95561. };
  95562. OIMO.HingeJoint.prototype.solve = function () {
  95563. this.r3.solve();
  95564. this.lc.solve();
  95565. };
  95566. OIMO.HingeJoint.prototype.postSolve = function () {
  95567. };
  95568. OIMO.HingeJoint.prototype.acosClamp = function (cos) {
  95569. if (cos > 1) return 0;
  95570. else if (cos < -1) return OIMO.PI;
  95571. else return OIMO.acos(cos);
  95572. };
  95573. /**
  95574. * A prismatic joint allows only for relative translation of rigid bodies along the axis.
  95575. * @author saharan
  95576. * @author lo-th
  95577. */
  95578. OIMO.PrismaticJoint = function (config, lowerTranslation, upperTranslation) {
  95579. OIMO.Joint.call(this, config);
  95580. this.type = OIMO.JOINT_PRISMATIC;
  95581. // The axis in the first body's coordinate system.
  95582. this.localAxis1 = new OIMO.Vec3().normalize(config.localAxis1);
  95583. // The axis in the second body's coordinate system.
  95584. this.localAxis2 = new OIMO.Vec3().normalize(config.localAxis2);
  95585. this.localAxis1X = this.localAxis1.x;
  95586. this.localAxis1Y = this.localAxis1.y;
  95587. this.localAxis1Z = this.localAxis1.z;
  95588. this.localAxis2X = this.localAxis2.x;
  95589. this.localAxis2Y = this.localAxis2.y;
  95590. this.localAxis2Z = this.localAxis2.z;
  95591. this.nor = new OIMO.Vec3();
  95592. this.tan = new OIMO.Vec3();
  95593. this.bin = new OIMO.Vec3();
  95594. this.ac = new OIMO.AngularConstraint(this, new OIMO.Quat().arc(this.localAxis1, this.localAxis2));
  95595. // The translational limit and motor information of the joint.
  95596. this.limitMotor = new OIMO.LimitMotor(this.nor, true);
  95597. this.limitMotor.lowerLimit = lowerTranslation;
  95598. this.limitMotor.upperLimit = upperTranslation;
  95599. this.t3 = new OIMO.Translational3Constraint(this, this.limitMotor, new OIMO.LimitMotor(this.tan, true), new OIMO.LimitMotor(this.bin, true));
  95600. };
  95601. OIMO.PrismaticJoint.prototype = Object.create(OIMO.Joint.prototype);
  95602. OIMO.PrismaticJoint.prototype.constructor = OIMO.PrismaticJoint;
  95603. OIMO.PrismaticJoint.prototype.preSolve = function (timeStep, invTimeStep) {
  95604. var tmpM;
  95605. var tmp1X;
  95606. var tmp1Y;
  95607. var tmp1Z;
  95608. this.updateAnchorPoints();
  95609. tmpM = this.body1.rotation.elements;
  95610. var axis1X = this.localAxis1X * tmpM[0] + this.localAxis1Y * tmpM[1] + this.localAxis1Z * tmpM[2];
  95611. var axis1Y = this.localAxis1X * tmpM[3] + this.localAxis1Y * tmpM[4] + this.localAxis1Z * tmpM[5];
  95612. var axis1Z = this.localAxis1X * tmpM[6] + this.localAxis1Y * tmpM[7] + this.localAxis1Z * tmpM[8];
  95613. tmpM = this.body2.rotation.elements;
  95614. var axis2X = this.localAxis2X * tmpM[0] + this.localAxis2Y * tmpM[1] + this.localAxis2Z * tmpM[2];
  95615. var axis2Y = this.localAxis2X * tmpM[3] + this.localAxis2Y * tmpM[4] + this.localAxis2Z * tmpM[5];
  95616. var axis2Z = this.localAxis2X * tmpM[6] + this.localAxis2Y * tmpM[7] + this.localAxis2Z * tmpM[8];
  95617. var nx = axis1X * this.body2.inverseMass + axis2X * this.body1.inverseMass;
  95618. var ny = axis1Y * this.body2.inverseMass + axis2Y * this.body1.inverseMass;
  95619. var nz = axis1Z * this.body2.inverseMass + axis2Z * this.body1.inverseMass;
  95620. tmp1X = OIMO.sqrt(nx * nx + ny * ny + nz * nz);
  95621. if (tmp1X > 0) tmp1X = 1 / tmp1X;
  95622. nx *= tmp1X;
  95623. ny *= tmp1X;
  95624. nz *= tmp1X;
  95625. var tx = ny * nx - nz * nz;
  95626. var ty = -nz * ny - nx * nx;
  95627. var tz = nx * nz + ny * ny;
  95628. tmp1X = 1 / OIMO.sqrt(tx * tx + ty * ty + tz * tz);
  95629. tx *= tmp1X;
  95630. ty *= tmp1X;
  95631. tz *= tmp1X;
  95632. var bx = ny * tz - nz * ty;
  95633. var by = nz * tx - nx * tz;
  95634. var bz = nx * ty - ny * tx;
  95635. this.nor.init(nx, ny, nz);
  95636. this.tan.init(tx, ty, tz);
  95637. this.bin.init(bx, by, bz);
  95638. this.ac.preSolve(timeStep, invTimeStep);
  95639. this.t3.preSolve(timeStep, invTimeStep);
  95640. };
  95641. OIMO.PrismaticJoint.prototype.solve = function () {
  95642. this.ac.solve();
  95643. this.t3.solve();
  95644. };
  95645. OIMO.PrismaticJoint.prototype.postSolve = function () {
  95646. };
  95647. /**
  95648. * A slider joint allows for relative translation and relative rotation between two rigid bodies along the axis.
  95649. * @author saharan
  95650. * @author lo-th
  95651. */
  95652. OIMO.SliderJoint = function (config, lowerTranslation, upperTranslation) {
  95653. OIMO.Joint.call(this, config);
  95654. this.type = OIMO.JOINT_SLIDER;
  95655. // The first axis in local coordinate system.
  95656. this.localAxis1 = new OIMO.Vec3().normalize(config.localAxis1);
  95657. // The second axis in local coordinate system.
  95658. this.localAxis2 = new OIMO.Vec3().normalize(config.localAxis2);
  95659. var len;
  95660. this.localAxis1X = this.localAxis1.x;
  95661. this.localAxis1Y = this.localAxis1.y;
  95662. this.localAxis1Z = this.localAxis1.z;
  95663. this.localAngAxis1X = this.localAxis1Y * this.localAxis1X - this.localAxis1Z * this.localAxis1Z;
  95664. this.localAngAxis1Y = -this.localAxis1Z * this.localAxis1Y - this.localAxis1X * this.localAxis1X;
  95665. this.localAngAxis1Z = this.localAxis1X * this.localAxis1Z + this.localAxis1Y * this.localAxis1Y;
  95666. len = 1 / OIMO.sqrt(this.localAngAxis1X * this.localAngAxis1X + this.localAngAxis1Y * this.localAngAxis1Y + this.localAngAxis1Z * this.localAngAxis1Z);
  95667. this.localAngAxis1X *= len;
  95668. this.localAngAxis1Y *= len;
  95669. this.localAngAxis1Z *= len;
  95670. this.localAxis2X = this.localAxis2.x;
  95671. this.localAxis2Y = this.localAxis2.y;
  95672. this.localAxis2Z = this.localAxis2.z;
  95673. // make angle axis 2
  95674. var arc = new OIMO.Mat33().setQuat(new OIMO.Quat().arc(this.localAxis1, this.localAxis2));
  95675. var tarc = arc.elements;
  95676. this.localAngAxis2X = this.localAngAxis1X * tarc[0] + this.localAngAxis1Y * tarc[1] + this.localAngAxis1Z * tarc[2];
  95677. this.localAngAxis2Y = this.localAngAxis1X * tarc[3] + this.localAngAxis1Y * tarc[4] + this.localAngAxis1Z * tarc[5];
  95678. this.localAngAxis2Z = this.localAngAxis1X * tarc[6] + this.localAngAxis1Y * tarc[7] + this.localAngAxis1Z * tarc[8];
  95679. this.nor = new OIMO.Vec3();
  95680. this.tan = new OIMO.Vec3();
  95681. this.bin = new OIMO.Vec3();
  95682. // The limit and motor for the rotation
  95683. this.rotationalLimitMotor = new OIMO.LimitMotor(this.nor, false);
  95684. this.r3 = new OIMO.Rotational3Constraint(this, this.rotationalLimitMotor, new OIMO.LimitMotor(this.tan, true), new OIMO.LimitMotor(this.bin, true));
  95685. // The limit and motor for the translation.
  95686. this.translationalLimitMotor = new OIMO.LimitMotor(this.nor, true);
  95687. this.translationalLimitMotor.lowerLimit = lowerTranslation;
  95688. this.translationalLimitMotor.upperLimit = upperTranslation;
  95689. this.t3 = new OIMO.Translational3Constraint(this, this.translationalLimitMotor, new OIMO.LimitMotor(this.tan, true), new OIMO.LimitMotor(this.bin, true));
  95690. };
  95691. OIMO.SliderJoint.prototype = Object.create(OIMO.Joint.prototype);
  95692. OIMO.SliderJoint.prototype.constructor = OIMO.SliderJoint;
  95693. OIMO.SliderJoint.prototype.preSolve = function (timeStep, invTimeStep) {
  95694. var tmpM;
  95695. var tmp1X;
  95696. var tmp1Y;
  95697. var tmp1Z;
  95698. this.updateAnchorPoints();
  95699. tmpM = this.body1.rotation.elements;
  95700. var axis1X = this.localAxis1X * tmpM[0] + this.localAxis1Y * tmpM[1] + this.localAxis1Z * tmpM[2];
  95701. var axis1Y = this.localAxis1X * tmpM[3] + this.localAxis1Y * tmpM[4] + this.localAxis1Z * tmpM[5];
  95702. var axis1Z = this.localAxis1X * tmpM[6] + this.localAxis1Y * tmpM[7] + this.localAxis1Z * tmpM[8];
  95703. var angAxis1X = this.localAngAxis1X * tmpM[0] + this.localAngAxis1Y * tmpM[1] + this.localAngAxis1Z * tmpM[2];
  95704. var angAxis1Y = this.localAngAxis1X * tmpM[3] + this.localAngAxis1Y * tmpM[4] + this.localAngAxis1Z * tmpM[5];
  95705. var angAxis1Z = this.localAngAxis1X * tmpM[6] + this.localAngAxis1Y * tmpM[7] + this.localAngAxis1Z * tmpM[8];
  95706. tmpM = this.body2.rotation.elements;
  95707. var axis2X = this.localAxis2X * tmpM[0] + this.localAxis2Y * tmpM[1] + this.localAxis2Z * tmpM[2];
  95708. var axis2Y = this.localAxis2X * tmpM[3] + this.localAxis2Y * tmpM[4] + this.localAxis2Z * tmpM[5];
  95709. var axis2Z = this.localAxis2X * tmpM[6] + this.localAxis2Y * tmpM[7] + this.localAxis2Z * tmpM[8];
  95710. var angAxis2X = this.localAngAxis2X * tmpM[0] + this.localAngAxis2Y * tmpM[1] + this.localAngAxis2Z * tmpM[2];
  95711. var angAxis2Y = this.localAngAxis2X * tmpM[3] + this.localAngAxis2Y * tmpM[4] + this.localAngAxis2Z * tmpM[5];
  95712. var angAxis2Z = this.localAngAxis2X * tmpM[6] + this.localAngAxis2Y * tmpM[7] + this.localAngAxis2Z * tmpM[8];
  95713. var nx = axis1X * this.body2.inverseMass + axis2X * this.body1.inverseMass;
  95714. var ny = axis1Y * this.body2.inverseMass + axis2Y * this.body1.inverseMass;
  95715. var nz = axis1Z * this.body2.inverseMass + axis2Z * this.body1.inverseMass;
  95716. tmp1X = OIMO.sqrt(nx * nx + ny * ny + nz * nz);
  95717. if (tmp1X > 0) tmp1X = 1 / tmp1X;
  95718. nx *= tmp1X;
  95719. ny *= tmp1X;
  95720. nz *= tmp1X;
  95721. var tx = ny * nx - nz * nz;
  95722. var ty = -nz * ny - nx * nx;
  95723. var tz = nx * nz + ny * ny;
  95724. tmp1X = 1 / OIMO.sqrt(tx * tx + ty * ty + tz * tz);
  95725. tx *= tmp1X;
  95726. ty *= tmp1X;
  95727. tz *= tmp1X;
  95728. var bx = ny * tz - nz * ty;
  95729. var by = nz * tx - nx * tz;
  95730. var bz = nx * ty - ny * tx;
  95731. this.nor.init(nx, ny, nz);
  95732. this.tan.init(tx, ty, tz);
  95733. this.bin.init(bx, by, bz);
  95734. // ----------------------------------------------
  95735. // calculate hinge angle
  95736. // ----------------------------------------------
  95737. if (
  95738. nx * (angAxis1Y * angAxis2Z - angAxis1Z * angAxis2Y) +
  95739. ny * (angAxis1Z * angAxis2X - angAxis1X * angAxis2Z) +
  95740. nz * (angAxis1X * angAxis2Y - angAxis1Y * angAxis2X) < 0
  95741. ) {
  95742. this.rotationalLimitMotor.angle = -this.acosClamp(angAxis1X * angAxis2X + angAxis1Y * angAxis2Y + angAxis1Z * angAxis2Z);
  95743. } else {
  95744. this.rotationalLimitMotor.angle = this.acosClamp(angAxis1X * angAxis2X + angAxis1Y * angAxis2Y + angAxis1Z * angAxis2Z);
  95745. }
  95746. // angular error
  95747. tmp1X = axis1Y * axis2Z - axis1Z * axis2Y;
  95748. tmp1Y = axis1Z * axis2X - axis1X * axis2Z;
  95749. tmp1Z = axis1X * axis2Y - axis1Y * axis2X;
  95750. this.r3.limitMotor2.angle = tx * tmp1X + ty * tmp1Y + tz * tmp1Z;
  95751. this.r3.limitMotor3.angle = bx * tmp1X + by * tmp1Y + bz * tmp1Z;
  95752. this.r3.preSolve(timeStep, invTimeStep);
  95753. this.t3.preSolve(timeStep, invTimeStep);
  95754. };
  95755. OIMO.SliderJoint.prototype.solve = function () {
  95756. this.r3.solve();
  95757. this.t3.solve();
  95758. };
  95759. OIMO.SliderJoint.prototype.postSolve = function () {
  95760. };
  95761. OIMO.SliderJoint.prototype.acosClamp = function (cos) {
  95762. if (cos > 1) return 0;
  95763. else if (cos < -1) return OIMO.PI;
  95764. else return OIMO.acos(cos);
  95765. };
  95766. /**
  95767. * A wheel joint allows for relative rotation between two rigid bodies along two axes.
  95768. * The wheel joint also allows for relative translation for the suspension.
  95769. * @author saharan
  95770. * @author lo-th
  95771. */
  95772. OIMO.WheelJoint = function (config) {
  95773. OIMO.Joint.call(this, config);
  95774. this.type = OIMO.JOINT_WHEEL;
  95775. // The first axis in local coordinate system.
  95776. this.localAxis1 = new OIMO.Vec3().normalize(config.localAxis1);
  95777. // The second axis in local coordinate system.
  95778. this.localAxis2 = new OIMO.Vec3().normalize(config.localAxis2);
  95779. var len;
  95780. this.localAxis1X = this.localAxis1.x;
  95781. this.localAxis1Y = this.localAxis1.y;
  95782. this.localAxis1Z = this.localAxis1.z;
  95783. this.localAxis2X = this.localAxis2.x;
  95784. this.localAxis2Y = this.localAxis2.y;
  95785. this.localAxis2Z = this.localAxis2.z;
  95786. var dot = this.localAxis1X * this.localAxis2X + this.localAxis1Y * this.localAxis2Y + this.localAxis1Z * this.localAxis2Z;
  95787. if (dot > -1 && dot < 1) {
  95788. this.localAngAxis1X = this.localAxis2X - dot * this.localAxis1X;
  95789. this.localAngAxis1Y = this.localAxis2Y - dot * this.localAxis1Y;
  95790. this.localAngAxis1Z = this.localAxis2Z - dot * this.localAxis1Z;
  95791. this.localAngAxis2X = this.localAxis1X - dot * this.localAxis2X;
  95792. this.localAngAxis2Y = this.localAxis1Y - dot * this.localAxis2Y;
  95793. this.localAngAxis2Z = this.localAxis1Z - dot * this.localAxis2Z;
  95794. len = 1 / OIMO.sqrt(this.localAngAxis1X * this.localAngAxis1X + this.localAngAxis1Y * this.localAngAxis1Y + this.localAngAxis1Z * this.localAngAxis1Z);
  95795. this.localAngAxis1X *= len;
  95796. this.localAngAxis1Y *= len;
  95797. this.localAngAxis1Z *= len;
  95798. len = 1 / OIMO.sqrt(this.localAngAxis2X * this.localAngAxis2X + this.localAngAxis2Y * this.localAngAxis2Y + this.localAngAxis2Z * this.localAngAxis2Z);
  95799. this.localAngAxis2X *= len;
  95800. this.localAngAxis2Y *= len;
  95801. this.localAngAxis2Z *= len;
  95802. } else {
  95803. this.localAngAxis1X = this.localAxis1Y * this.localAxis1X - this.localAxis1Z * this.localAxis1Z;
  95804. this.localAngAxis1Y = -this.localAxis1Z * this.localAxis1Y - this.localAxis1X * this.localAxis1X;
  95805. this.localAngAxis1Z = this.localAxis1X * this.localAxis1Z + this.localAxis1Y * this.localAxis1Y;
  95806. len = 1 / OIMO.sqrt(this.localAngAxis1X * this.localAngAxis1X + this.localAngAxis1Y * this.localAngAxis1Y + this.localAngAxis1Z * this.localAngAxis1Z);
  95807. this.localAngAxis1X *= len;
  95808. this.localAngAxis1Y *= len;
  95809. this.localAngAxis1Z *= len;
  95810. var arc = new OIMO.Mat33().setQuat(new OIMO.Quat().arc(this.localAxis1, this.localAxis2));
  95811. var tarc = arc.elements;
  95812. this.localAngAxis2X = this.localAngAxis1X * tarc[0] + this.localAngAxis1Y * tarc[1] + this.localAngAxis1Z * tarc[2];
  95813. this.localAngAxis2Y = this.localAngAxis1X * tarc[3] + this.localAngAxis1Y * tarc[4] + this.localAngAxis1Z * tarc[5];
  95814. this.localAngAxis2Z = this.localAngAxis1X * tarc[6] + this.localAngAxis1Y * tarc[7] + this.localAngAxis1Z * tarc[8];
  95815. }
  95816. this.nor = new OIMO.Vec3();
  95817. this.tan = new OIMO.Vec3();
  95818. this.bin = new OIMO.Vec3();
  95819. // The translational limit and motor information of the joint.
  95820. this.translationalLimitMotor = new OIMO.LimitMotor(this.tan, true);
  95821. this.translationalLimitMotor.frequency = 8;
  95822. this.translationalLimitMotor.dampingRatio = 1;
  95823. // The first rotational limit and motor information of the joint.
  95824. this.rotationalLimitMotor1 = new OIMO.LimitMotor(this.tan, false);
  95825. // The second rotational limit and motor information of the joint.
  95826. this.rotationalLimitMotor2 = new OIMO.LimitMotor(this.bin, false);
  95827. this.t3 = new OIMO.Translational3Constraint(this, new OIMO.LimitMotor(this.nor, true), this.translationalLimitMotor, new OIMO.LimitMotor(this.bin, true));
  95828. this.t3.weight = 1;
  95829. this.r3 = new OIMO.Rotational3Constraint(this, new OIMO.LimitMotor(this.nor, true), this.rotationalLimitMotor1, this.rotationalLimitMotor2);
  95830. };
  95831. OIMO.WheelJoint.prototype = Object.create(OIMO.Joint.prototype);
  95832. OIMO.WheelJoint.prototype.constructor = OIMO.WheelJoint;
  95833. OIMO.WheelJoint.prototype.preSolve = function (timeStep, invTimeStep) {
  95834. var tmpM;
  95835. var tmp1X;
  95836. var tmp1Y;
  95837. var tmp1Z;
  95838. this.updateAnchorPoints();
  95839. tmpM = this.body1.rotation.elements;
  95840. var x1 = this.localAxis1X * tmpM[0] + this.localAxis1Y * tmpM[1] + this.localAxis1Z * tmpM[2];
  95841. var y1 = this.localAxis1X * tmpM[3] + this.localAxis1Y * tmpM[4] + this.localAxis1Z * tmpM[5];
  95842. var z1 = this.localAxis1X * tmpM[6] + this.localAxis1Y * tmpM[7] + this.localAxis1Z * tmpM[8];
  95843. var angAxis1X = this.localAngAxis1X * tmpM[0] + this.localAngAxis1Y * tmpM[1] + this.localAngAxis1Z * tmpM[2];
  95844. var angAxis1Y = this.localAngAxis1X * tmpM[3] + this.localAngAxis1Y * tmpM[4] + this.localAngAxis1Z * tmpM[5];
  95845. var angAxis1Z = this.localAngAxis1X * tmpM[6] + this.localAngAxis1Y * tmpM[7] + this.localAngAxis1Z * tmpM[8];
  95846. tmpM = this.body2.rotation.elements;
  95847. var x2 = this.localAxis2X * tmpM[0] + this.localAxis2Y * tmpM[1] + this.localAxis2Z * tmpM[2];
  95848. var y2 = this.localAxis2X * tmpM[3] + this.localAxis2Y * tmpM[4] + this.localAxis2Z * tmpM[5];
  95849. var z2 = this.localAxis2X * tmpM[6] + this.localAxis2Y * tmpM[7] + this.localAxis2Z * tmpM[8];
  95850. var angAxis2X = this.localAngAxis2X * tmpM[0] + this.localAngAxis2Y * tmpM[1] + this.localAngAxis2Z * tmpM[2];
  95851. var angAxis2Y = this.localAngAxis2X * tmpM[3] + this.localAngAxis2Y * tmpM[4] + this.localAngAxis2Z * tmpM[5];
  95852. var angAxis2Z = this.localAngAxis2X * tmpM[6] + this.localAngAxis2Y * tmpM[7] + this.localAngAxis2Z * tmpM[8];
  95853. this.r3.limitMotor1.angle = x1 * x2 + y1 * y2 + z1 * z2;
  95854. if (x1 * (angAxis1Y * z2 - angAxis1Z * y2) + y1 * (angAxis1Z * x2 - angAxis1X * z2) + z1 * (angAxis1X * y2 - angAxis1Y * x2) < 0) {
  95855. this.rotationalLimitMotor1.angle = -this.acosClamp(angAxis1X * x2 + angAxis1Y * y2 + angAxis1Z * z2);
  95856. } else {
  95857. this.rotationalLimitMotor1.angle = this.acosClamp(angAxis1X * x2 + angAxis1Y * y2 + angAxis1Z * z2);
  95858. }
  95859. if (x2 * (angAxis2Y * z1 - angAxis2Z * y1) + y2 * (angAxis2Z * x1 - angAxis2X * z1) + z2 * (angAxis2X * y1 - angAxis2Y * x1) < 0) {
  95860. this.rotationalLimitMotor2.angle = this.acosClamp(angAxis2X * x1 + angAxis2Y * y1 + angAxis2Z * z1);
  95861. } else {
  95862. this.rotationalLimitMotor2.angle = -this.acosClamp(angAxis2X * x1 + angAxis2Y * y1 + angAxis2Z * z1);
  95863. }
  95864. var nx = y2 * z1 - z2 * y1;
  95865. var ny = z2 * x1 - x2 * z1;
  95866. var nz = x2 * y1 - y2 * x1;
  95867. tmp1X = OIMO.sqrt(nx * nx + ny * ny + nz * nz);
  95868. if (tmp1X > 0) tmp1X = 1 / tmp1X;
  95869. nx *= tmp1X;
  95870. ny *= tmp1X;
  95871. nz *= tmp1X;
  95872. var tx = ny * z2 - nz * y2;
  95873. var ty = nz * x2 - nx * z2;
  95874. var tz = nx * y2 - ny * x2;
  95875. tmp1X = OIMO.sqrt(tx * tx + ty * ty + tz * tz);
  95876. if (tmp1X > 0) tmp1X = 1 / tmp1X;
  95877. tx *= tmp1X;
  95878. ty *= tmp1X;
  95879. tz *= tmp1X;
  95880. var bx = y1 * nz - z1 * ny;
  95881. var by = z1 * nx - x1 * nz;
  95882. var bz = x1 * ny - y1 * nx;
  95883. tmp1X = OIMO.sqrt(bx * bx + by * by + bz * bz);
  95884. if (tmp1X > 0) tmp1X = 1 / tmp1X;
  95885. bx *= tmp1X;
  95886. by *= tmp1X;
  95887. bz *= tmp1X;
  95888. this.nor.init(nx, ny, nz);
  95889. this.tan.init(tx, ty, tz);
  95890. this.bin.init(bx, by, bz);
  95891. this.r3.preSolve(timeStep, invTimeStep);
  95892. this.t3.preSolve(timeStep, invTimeStep);
  95893. };
  95894. OIMO.WheelJoint.prototype.solve = function () {
  95895. this.r3.solve();
  95896. this.t3.solve();
  95897. };
  95898. OIMO.WheelJoint.prototype.postSolve = function () {
  95899. };
  95900. OIMO.WheelJoint.prototype.acosClamp = function (cos) {
  95901. if (cos > 1) return 0;
  95902. else if (cos < -1) return OIMO.PI;
  95903. else return OIMO.acos(cos);
  95904. };
  95905. /**
  95906. * An angular constraint for all axes for various joints.
  95907. * @author saharan
  95908. */
  95909. OIMO.AngularConstraint = function (joint, targetOrientation) {
  95910. this.joint = joint;
  95911. this.targetOrientation = new OIMO.Quat().invert(targetOrientation);
  95912. this.relativeOrientation = new OIMO.Quat();
  95913. this.ii1 = null;
  95914. this.ii2 = null;
  95915. this.dd = null;
  95916. this.vel = new OIMO.Vec3();
  95917. this.imp = new OIMO.Vec3();
  95918. this.rn0 = new OIMO.Vec3();
  95919. this.rn1 = new OIMO.Vec3();
  95920. this.rn2 = new OIMO.Vec3();
  95921. this.b1 = joint.body1;
  95922. this.b2 = joint.body2;
  95923. this.a1 = this.b1.angularVelocity;
  95924. this.a2 = this.b2.angularVelocity;
  95925. this.i1 = this.b1.inverseInertia;
  95926. this.i2 = this.b2.inverseInertia;
  95927. };
  95928. OIMO.AngularConstraint.prototype = {
  95929. constructor: OIMO.AngularConstraint,
  95930. preSolve: function (timeStep, invTimeStep) {
  95931. var inv, len, v, vv;
  95932. this.ii1 = this.i1.clone();
  95933. this.ii2 = this.i2.clone();
  95934. v = new OIMO.Mat33().add(this.ii1, this.ii2).elements;
  95935. 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]));
  95936. this.dd = new OIMO.Mat33(
  95937. v[4] * v[8] - v[5] * v[7], v[2] * v[7] - v[1] * v[8], v[1] * v[5] - v[2] * v[4],
  95938. v[5] * v[6] - v[3] * v[8], v[0] * v[8] - v[2] * v[6], v[2] * v[3] - v[0] * v[5],
  95939. v[3] * v[7] - v[4] * v[6], v[1] * v[6] - v[0] * v[7], v[0] * v[4] - v[1] * v[3]
  95940. ).multiply(inv);
  95941. this.relativeOrientation.invert(this.b1.orientation);
  95942. this.relativeOrientation.mul(this.targetOrientation, this.relativeOrientation);
  95943. this.relativeOrientation.mul(this.b2.orientation, this.relativeOrientation);
  95944. inv = this.relativeOrientation.s * 2;
  95945. this.vel.scale(this.relativeOrientation, inv);
  95946. len = this.vel.length();
  95947. if (len > 0.02) {
  95948. len = (0.02 - len) / len * invTimeStep * 0.05;
  95949. this.vel.scaleEqual(len);
  95950. } else {
  95951. this.vel.init();
  95952. }
  95953. this.rn1.mulMat(this.ii1, this.imp);
  95954. this.rn2.mulMat(this.ii2, this.imp);
  95955. this.a1.addEqual(this.rn1);
  95956. this.a2.subEqual(this.rn2);
  95957. },
  95958. solve: function () {
  95959. var r = this.a2.clone().subEqual(this.a1).subEqual(this.vel);
  95960. this.rn0.mulMat(this.dd, r);
  95961. this.rn1.mulMat(this.ii1, this.rn0);
  95962. this.rn2.mulMat(this.ii2, this.rn0);
  95963. this.imp.addEqual(this.rn0);
  95964. this.a1.addEqual(this.rn1);
  95965. this.a2.subEqual(this.rn2);
  95966. }
  95967. };
  95968. /**
  95969. * A linear constraint for all axes for various joints.
  95970. * @author saharan
  95971. */
  95972. OIMO.LinearConstraint = function (joint) {
  95973. this.m1 = NaN;
  95974. this.m2 = NaN;
  95975. this.ii1 = null;
  95976. this.ii2 = null;
  95977. this.dd = null;
  95978. this.r1x = NaN;
  95979. this.r1y = NaN;
  95980. this.r1z = NaN;
  95981. this.r2x = NaN;
  95982. this.r2y = NaN;
  95983. this.r2z = NaN;
  95984. this.ax1x = NaN;
  95985. this.ax1y = NaN;
  95986. this.ax1z = NaN;
  95987. this.ay1x = NaN;
  95988. this.ay1y = NaN;
  95989. this.ay1z = NaN;
  95990. this.az1x = NaN;
  95991. this.az1y = NaN;
  95992. this.az1z = NaN;
  95993. this.ax2x = NaN;
  95994. this.ax2y = NaN;
  95995. this.ax2z = NaN;
  95996. this.ay2x = NaN;
  95997. this.ay2y = NaN;
  95998. this.ay2z = NaN;
  95999. this.az2x = NaN;
  96000. this.az2y = NaN;
  96001. this.az2z = NaN;
  96002. this.vel = NaN;
  96003. this.velx = NaN;
  96004. this.vely = NaN;
  96005. this.velz = NaN;
  96006. this.joint = joint;
  96007. this.r1 = joint.relativeAnchorPoint1;
  96008. this.r2 = joint.relativeAnchorPoint2;
  96009. this.p1 = joint.anchorPoint1;
  96010. this.p2 = joint.anchorPoint2;
  96011. this.b1 = joint.body1;
  96012. this.b2 = joint.body2;
  96013. this.l1 = this.b1.linearVelocity;
  96014. this.l2 = this.b2.linearVelocity;
  96015. this.a1 = this.b1.angularVelocity;
  96016. this.a2 = this.b2.angularVelocity;
  96017. this.i1 = this.b1.inverseInertia;
  96018. this.i2 = this.b2.inverseInertia;
  96019. this.impx = 0;
  96020. this.impy = 0;
  96021. this.impz = 0;
  96022. }
  96023. OIMO.LinearConstraint.prototype = {
  96024. constructor: OIMO.LinearConstraint,
  96025. preSolve: function (timeStep, invTimeStep) {
  96026. this.r1x = this.r1.x;
  96027. this.r1y = this.r1.y;
  96028. this.r1z = this.r1.z;
  96029. this.r2x = this.r2.x;
  96030. this.r2y = this.r2.y;
  96031. this.r2z = this.r2.z;
  96032. this.m1 = this.b1.inverseMass;
  96033. this.m2 = this.b2.inverseMass;
  96034. this.ii1 = this.i1.clone();
  96035. this.ii2 = this.i2.clone();
  96036. var ii1 = this.ii1.elements;
  96037. var ii2 = this.ii2.elements;
  96038. this.ax1x = this.r1z * ii1[1] + -this.r1y * ii1[2];
  96039. this.ax1y = this.r1z * ii1[4] + -this.r1y * ii1[5];
  96040. this.ax1z = this.r1z * ii1[7] + -this.r1y * ii1[8];
  96041. this.ay1x = -this.r1z * ii1[0] + this.r1x * ii1[2];
  96042. this.ay1y = -this.r1z * ii1[3] + this.r1x * ii1[5];
  96043. this.ay1z = -this.r1z * ii1[6] + this.r1x * ii1[8];
  96044. this.az1x = this.r1y * ii1[0] + -this.r1x * ii1[1];
  96045. this.az1y = this.r1y * ii1[3] + -this.r1x * ii1[4];
  96046. this.az1z = this.r1y * ii1[6] + -this.r1x * ii1[7];
  96047. this.ax2x = this.r2z * ii2[1] + -this.r2y * ii2[2];
  96048. this.ax2y = this.r2z * ii2[4] + -this.r2y * ii2[5];
  96049. this.ax2z = this.r2z * ii2[7] + -this.r2y * ii2[8];
  96050. this.ay2x = -this.r2z * ii2[0] + this.r2x * ii2[2];
  96051. this.ay2y = -this.r2z * ii2[3] + this.r2x * ii2[5];
  96052. this.ay2z = -this.r2z * ii2[6] + this.r2x * ii2[8];
  96053. this.az2x = this.r2y * ii2[0] + -this.r2x * ii2[1];
  96054. this.az2y = this.r2y * ii2[3] + -this.r2x * ii2[4];
  96055. this.az2z = this.r2y * ii2[6] + -this.r2x * ii2[7];
  96056. // calculate point-to-point mass matrix
  96057. // from impulse equation
  96058. //
  96059. // M = ([/m] - [r^][/I][r^]) ^ -1
  96060. //
  96061. // where
  96062. //
  96063. // [/m] = |1/m, 0, 0|
  96064. // |0, 1/m, 0|
  96065. // |0, 0, 1/m|
  96066. //
  96067. // [r^] = |0, -rz, ry|
  96068. // |rz, 0, -rx|
  96069. // |-ry, rx, 0|
  96070. //
  96071. // [/I] = Inverted moment inertia
  96072. var rxx = this.m1 + this.m2;
  96073. var kk = new OIMO.Mat33(rxx, 0, 0, 0, rxx, 0, 0, 0, rxx);
  96074. var k = kk.elements;
  96075. k[0] += ii1[4] * this.r1z * this.r1z - (ii1[7] + ii1[5]) * this.r1y * this.r1z + ii1[8] * this.r1y * this.r1y;
  96076. k[1] += (ii1[6] * this.r1y + ii1[5] * this.r1x) * this.r1z - ii1[3] * this.r1z * this.r1z - ii1[8] * this.r1x * this.r1y;
  96077. k[2] += (ii1[3] * this.r1y - ii1[4] * this.r1x) * this.r1z - ii1[6] * this.r1y * this.r1y + ii1[7] * this.r1x * this.r1y;
  96078. k[3] += (ii1[2] * this.r1y + ii1[7] * this.r1x) * this.r1z - ii1[1] * this.r1z * this.r1z - ii1[8] * this.r1x * this.r1y;
  96079. k[4] += ii1[0] * this.r1z * this.r1z - (ii1[6] + ii1[2]) * this.r1x * this.r1z + ii1[8] * this.r1x * this.r1x;
  96080. k[5] += (ii1[1] * this.r1x - ii1[0] * this.r1y) * this.r1z - ii1[7] * this.r1x * this.r1x + ii1[6] * this.r1x * this.r1y;
  96081. k[6] += (ii1[1] * this.r1y - ii1[4] * this.r1x) * this.r1z - ii1[2] * this.r1y * this.r1y + ii1[5] * this.r1x * this.r1y;
  96082. k[7] += (ii1[3] * this.r1x - ii1[0] * this.r1y) * this.r1z - ii1[5] * this.r1x * this.r1x + ii1[2] * this.r1x * this.r1y;
  96083. k[8] += ii1[0] * this.r1y * this.r1y - (ii1[3] + ii1[1]) * this.r1x * this.r1y + ii1[4] * this.r1x * this.r1x;
  96084. k[0] += ii2[4] * this.r2z * this.r2z - (ii2[7] + ii2[5]) * this.r2y * this.r2z + ii2[8] * this.r2y * this.r2y;
  96085. k[1] += (ii2[6] * this.r2y + ii2[5] * this.r2x) * this.r2z - ii2[3] * this.r2z * this.r2z - ii2[8] * this.r2x * this.r2y;
  96086. k[2] += (ii2[3] * this.r2y - ii2[4] * this.r2x) * this.r2z - ii2[6] * this.r2y * this.r2y + ii2[7] * this.r2x * this.r2y;
  96087. k[3] += (ii2[2] * this.r2y + ii2[7] * this.r2x) * this.r2z - ii2[1] * this.r2z * this.r2z - ii2[8] * this.r2x * this.r2y;
  96088. k[4] += ii2[0] * this.r2z * this.r2z - (ii2[6] + ii2[2]) * this.r2x * this.r2z + ii2[8] * this.r2x * this.r2x;
  96089. k[5] += (ii2[1] * this.r2x - ii2[0] * this.r2y) * this.r2z - ii2[7] * this.r2x * this.r2x + ii2[6] * this.r2x * this.r2y;
  96090. k[6] += (ii2[1] * this.r2y - ii2[4] * this.r2x) * this.r2z - ii2[2] * this.r2y * this.r2y + ii2[5] * this.r2x * this.r2y;
  96091. k[7] += (ii2[3] * this.r2x - ii2[0] * this.r2y) * this.r2z - ii2[5] * this.r2x * this.r2x + ii2[2] * this.r2x * this.r2y;
  96092. k[8] += ii2[0] * this.r2y * this.r2y - (ii2[3] + ii2[1]) * this.r2x * this.r2y + ii2[4] * this.r2x * this.r2x;
  96093. 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]));
  96094. this.dd = new OIMO.Mat33(
  96095. k[4] * k[8] - k[5] * k[7], k[2] * k[7] - k[1] * k[8], k[1] * k[5] - k[2] * k[4],
  96096. k[5] * k[6] - k[3] * k[8], k[0] * k[8] - k[2] * k[6], k[2] * k[3] - k[0] * k[5],
  96097. k[3] * k[7] - k[4] * k[6], k[1] * k[6] - k[0] * k[7], k[0] * k[4] - k[1] * k[3]
  96098. ).multiply(inv);
  96099. this.velx = this.p2.x - this.p1.x;
  96100. this.vely = this.p2.y - this.p1.y;
  96101. this.velz = this.p2.z - this.p1.z;
  96102. var len = OIMO.sqrt(this.velx * this.velx + this.vely * this.vely + this.velz * this.velz);
  96103. if (len > 0.005) {
  96104. len = (0.005 - len) / len * invTimeStep * 0.05;
  96105. this.velx *= len;
  96106. this.vely *= len;
  96107. this.velz *= len;
  96108. } else {
  96109. this.velx = 0;
  96110. this.vely = 0;
  96111. this.velz = 0;
  96112. }
  96113. this.impx *= 0.95;
  96114. this.impy *= 0.95;
  96115. this.impz *= 0.95;
  96116. this.l1.x += this.impx * this.m1;
  96117. this.l1.y += this.impy * this.m1;
  96118. this.l1.z += this.impz * this.m1;
  96119. this.a1.x += this.impx * this.ax1x + this.impy * this.ay1x + this.impz * this.az1x;
  96120. this.a1.y += this.impx * this.ax1y + this.impy * this.ay1y + this.impz * this.az1y;
  96121. this.a1.z += this.impx * this.ax1z + this.impy * this.ay1z + this.impz * this.az1z;
  96122. this.l2.x -= this.impx * this.m2;
  96123. this.l2.y -= this.impy * this.m2;
  96124. this.l2.z -= this.impz * this.m2;
  96125. this.a2.x -= this.impx * this.ax2x + this.impy * this.ay2x + this.impz * this.az2x;
  96126. this.a2.y -= this.impx * this.ax2y + this.impy * this.ay2y + this.impz * this.az2y;
  96127. this.a2.z -= this.impx * this.ax2z + this.impy * this.ay2z + this.impz * this.az2z;
  96128. },
  96129. solve: function () {
  96130. var d = this.dd.elements;
  96131. 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;
  96132. 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;
  96133. 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;
  96134. var nimpx = rvx * d[0] + rvy * d[1] + rvz * d[2];
  96135. var nimpy = rvx * d[3] + rvy * d[4] + rvz * d[5];
  96136. var nimpz = rvx * d[6] + rvy * d[7] + rvz * d[8];
  96137. this.impx += nimpx;
  96138. this.impy += nimpy;
  96139. this.impz += nimpz;
  96140. this.l1.x += nimpx * this.m1;
  96141. this.l1.y += nimpy * this.m1;
  96142. this.l1.z += nimpz * this.m1;
  96143. this.a1.x += nimpx * this.ax1x + nimpy * this.ay1x + nimpz * this.az1x;
  96144. this.a1.y += nimpx * this.ax1y + nimpy * this.ay1y + nimpz * this.az1y;
  96145. this.a1.z += nimpx * this.ax1z + nimpy * this.ay1z + nimpz * this.az1z;
  96146. this.l2.x -= nimpx * this.m2;
  96147. this.l2.y -= nimpy * this.m2;
  96148. this.l2.z -= nimpz * this.m2;
  96149. this.a2.x -= nimpx * this.ax2x + nimpy * this.ay2x + nimpz * this.az2x;
  96150. this.a2.y -= nimpx * this.ax2y + nimpy * this.ay2y + nimpz * this.az2y;
  96151. this.a2.z -= nimpx * this.ax2z + nimpy * this.ay2z + nimpz * this.az2z;
  96152. }
  96153. }
  96154. /**
  96155. * A three-axis rotational constraint for various joints.
  96156. * @author saharan
  96157. */
  96158. OIMO.Rotational3Constraint = function (joint, limitMotor1, limitMotor2, limitMotor3) {
  96159. this.cfm1 = NaN;
  96160. this.cfm2 = NaN;
  96161. this.cfm3 = NaN;
  96162. this.i1e00 = NaN;
  96163. this.i1e01 = NaN;
  96164. this.i1e02 = NaN;
  96165. this.i1e10 = NaN;
  96166. this.i1e11 = NaN;
  96167. this.i1e12 = NaN;
  96168. this.i1e20 = NaN;
  96169. this.i1e21 = NaN;
  96170. this.i1e22 = NaN;
  96171. this.i2e00 = NaN;
  96172. this.i2e01 = NaN;
  96173. this.i2e02 = NaN;
  96174. this.i2e10 = NaN;
  96175. this.i2e11 = NaN;
  96176. this.i2e12 = NaN;
  96177. this.i2e20 = NaN;
  96178. this.i2e21 = NaN;
  96179. this.i2e22 = NaN;
  96180. this.ax1 = NaN;
  96181. this.ay1 = NaN;
  96182. this.az1 = NaN;
  96183. this.ax2 = NaN;
  96184. this.ay2 = NaN;
  96185. this.az2 = NaN;
  96186. this.ax3 = NaN;
  96187. this.ay3 = NaN;
  96188. this.az3 = NaN;
  96189. this.a1x1 = NaN; // jacoians
  96190. this.a1y1 = NaN;
  96191. this.a1z1 = NaN;
  96192. this.a2x1 = NaN;
  96193. this.a2y1 = NaN;
  96194. this.a2z1 = NaN;
  96195. this.a1x2 = NaN;
  96196. this.a1y2 = NaN;
  96197. this.a1z2 = NaN;
  96198. this.a2x2 = NaN;
  96199. this.a2y2 = NaN;
  96200. this.a2z2 = NaN;
  96201. this.a1x3 = NaN;
  96202. this.a1y3 = NaN;
  96203. this.a1z3 = NaN;
  96204. this.a2x3 = NaN;
  96205. this.a2y3 = NaN;
  96206. this.a2z3 = NaN;
  96207. this.lowerLimit1 = NaN;
  96208. this.upperLimit1 = NaN;
  96209. this.limitVelocity1 = NaN;
  96210. this.limitState1 = 0; // -1: at lower, 0: locked, 1: at upper, 2: free
  96211. this.enableMotor1 = false;
  96212. this.motorSpeed1 = NaN;
  96213. this.maxMotorForce1 = NaN;
  96214. this.maxMotorImpulse1 = NaN;
  96215. this.lowerLimit2 = NaN;
  96216. this.upperLimit2 = NaN;
  96217. this.limitVelocity2 = NaN;
  96218. this.limitState2 = 0; // -1: at lower, 0: locked, 1: at upper, 2: free
  96219. this.enableMotor2 = false;
  96220. this.motorSpeed2 = NaN;
  96221. this.maxMotorForce2 = NaN;
  96222. this.maxMotorImpulse2 = NaN;
  96223. this.lowerLimit3 = NaN;
  96224. this.upperLimit3 = NaN;
  96225. this.limitVelocity3 = NaN;
  96226. this.limitState3 = 0; // -1: at lower, 0: locked, 1: at upper, 2: free
  96227. this.enableMotor3 = false;
  96228. this.motorSpeed3 = NaN;
  96229. this.maxMotorForce3 = NaN;
  96230. this.maxMotorImpulse3 = NaN;
  96231. this.k00 = NaN; // K = J*M*JT
  96232. this.k01 = NaN;
  96233. this.k02 = NaN;
  96234. this.k10 = NaN;
  96235. this.k11 = NaN;
  96236. this.k12 = NaN;
  96237. this.k20 = NaN;
  96238. this.k21 = NaN;
  96239. this.k22 = NaN;
  96240. this.kv00 = NaN; // diagonals without CFMs
  96241. this.kv11 = NaN;
  96242. this.kv22 = NaN;
  96243. this.dv00 = NaN; // ...inverted
  96244. this.dv11 = NaN;
  96245. this.dv22 = NaN;
  96246. this.d00 = NaN; // K^-1
  96247. this.d01 = NaN;
  96248. this.d02 = NaN;
  96249. this.d10 = NaN;
  96250. this.d11 = NaN;
  96251. this.d12 = NaN;
  96252. this.d20 = NaN;
  96253. this.d21 = NaN;
  96254. this.d22 = NaN;
  96255. this.limitMotor1 = limitMotor1;
  96256. this.limitMotor2 = limitMotor2;
  96257. this.limitMotor3 = limitMotor3;
  96258. this.b1 = joint.body1;
  96259. this.b2 = joint.body2;
  96260. this.a1 = this.b1.angularVelocity;
  96261. this.a2 = this.b2.angularVelocity;
  96262. this.i1 = this.b1.inverseInertia;
  96263. this.i2 = this.b2.inverseInertia;
  96264. this.limitImpulse1 = 0;
  96265. this.motorImpulse1 = 0;
  96266. this.limitImpulse2 = 0;
  96267. this.motorImpulse2 = 0;
  96268. this.limitImpulse3 = 0;
  96269. this.motorImpulse3 = 0;
  96270. }
  96271. OIMO.Rotational3Constraint.prototype = {
  96272. constructor: OIMO.Rotational3Constraint,
  96273. preSolve: function (timeStep, invTimeStep) {
  96274. this.ax1 = this.limitMotor1.axis.x;
  96275. this.ay1 = this.limitMotor1.axis.y;
  96276. this.az1 = this.limitMotor1.axis.z;
  96277. this.ax2 = this.limitMotor2.axis.x;
  96278. this.ay2 = this.limitMotor2.axis.y;
  96279. this.az2 = this.limitMotor2.axis.z;
  96280. this.ax3 = this.limitMotor3.axis.x;
  96281. this.ay3 = this.limitMotor3.axis.y;
  96282. this.az3 = this.limitMotor3.axis.z;
  96283. this.lowerLimit1 = this.limitMotor1.lowerLimit;
  96284. this.upperLimit1 = this.limitMotor1.upperLimit;
  96285. this.motorSpeed1 = this.limitMotor1.motorSpeed;
  96286. this.maxMotorForce1 = this.limitMotor1.maxMotorForce;
  96287. this.enableMotor1 = this.maxMotorForce1 > 0;
  96288. this.lowerLimit2 = this.limitMotor2.lowerLimit;
  96289. this.upperLimit2 = this.limitMotor2.upperLimit;
  96290. this.motorSpeed2 = this.limitMotor2.motorSpeed;
  96291. this.maxMotorForce2 = this.limitMotor2.maxMotorForce;
  96292. this.enableMotor2 = this.maxMotorForce2 > 0;
  96293. this.lowerLimit3 = this.limitMotor3.lowerLimit;
  96294. this.upperLimit3 = this.limitMotor3.upperLimit;
  96295. this.motorSpeed3 = this.limitMotor3.motorSpeed;
  96296. this.maxMotorForce3 = this.limitMotor3.maxMotorForce;
  96297. this.enableMotor3 = this.maxMotorForce3 > 0;
  96298. var ti1 = this.i1.elements;
  96299. var ti2 = this.i2.elements;
  96300. this.i1e00 = ti1[0];
  96301. this.i1e01 = ti1[1];
  96302. this.i1e02 = ti1[2];
  96303. this.i1e10 = ti1[3];
  96304. this.i1e11 = ti1[4];
  96305. this.i1e12 = ti1[5];
  96306. this.i1e20 = ti1[6];
  96307. this.i1e21 = ti1[7];
  96308. this.i1e22 = ti1[8];
  96309. this.i2e00 = ti2[0];
  96310. this.i2e01 = ti2[1];
  96311. this.i2e02 = ti2[2];
  96312. this.i2e10 = ti2[3];
  96313. this.i2e11 = ti2[4];
  96314. this.i2e12 = ti2[5];
  96315. this.i2e20 = ti2[6];
  96316. this.i2e21 = ti2[7];
  96317. this.i2e22 = ti2[8];
  96318. var frequency1 = this.limitMotor1.frequency;
  96319. var frequency2 = this.limitMotor2.frequency;
  96320. var frequency3 = this.limitMotor3.frequency;
  96321. var enableSpring1 = frequency1 > 0;
  96322. var enableSpring2 = frequency2 > 0;
  96323. var enableSpring3 = frequency3 > 0;
  96324. var enableLimit1 = this.lowerLimit1 <= this.upperLimit1;
  96325. var enableLimit2 = this.lowerLimit2 <= this.upperLimit2;
  96326. var enableLimit3 = this.lowerLimit3 <= this.upperLimit3;
  96327. var angle1 = this.limitMotor1.angle;
  96328. if (enableLimit1) {
  96329. if (this.lowerLimit1 == this.upperLimit1) {
  96330. if (this.limitState1 != 0) {
  96331. this.limitState1 = 0;
  96332. this.limitImpulse1 = 0;
  96333. }
  96334. this.limitVelocity1 = this.lowerLimit1 - angle1;
  96335. } else if (angle1 < this.lowerLimit1) {
  96336. if (this.limitState1 != -1) {
  96337. this.limitState1 = -1;
  96338. this.limitImpulse1 = 0;
  96339. }
  96340. this.limitVelocity1 = this.lowerLimit1 - angle1;
  96341. } else if (angle1 > this.upperLimit1) {
  96342. if (this.limitState1 != 1) {
  96343. this.limitState1 = 1;
  96344. this.limitImpulse1 = 0;
  96345. }
  96346. this.limitVelocity1 = this.upperLimit1 - angle1;
  96347. } else {
  96348. this.limitState1 = 2;
  96349. this.limitImpulse1 = 0;
  96350. this.limitVelocity1 = 0;
  96351. }
  96352. if (!enableSpring1) {
  96353. if (this.limitVelocity1 > 0.02) this.limitVelocity1 -= 0.02;
  96354. else if (this.limitVelocity1 < -0.02) this.limitVelocity1 += 0.02;
  96355. else this.limitVelocity1 = 0;
  96356. }
  96357. } else {
  96358. this.limitState1 = 2;
  96359. this.limitImpulse1 = 0;
  96360. }
  96361. var angle2 = this.limitMotor2.angle;
  96362. if (enableLimit2) {
  96363. if (this.lowerLimit2 == this.upperLimit2) {
  96364. if (this.limitState2 != 0) {
  96365. this.limitState2 = 0;
  96366. this.limitImpulse2 = 0;
  96367. }
  96368. this.limitVelocity2 = this.lowerLimit2 - angle2;
  96369. } else if (angle2 < this.lowerLimit2) {
  96370. if (this.limitState2 != -1) {
  96371. this.limitState2 = -1;
  96372. this.limitImpulse2 = 0;
  96373. }
  96374. this.limitVelocity2 = this.lowerLimit2 - angle2;
  96375. } else if (angle2 > this.upperLimit2) {
  96376. if (this.limitState2 != 1) {
  96377. this.limitState2 = 1;
  96378. this.limitImpulse2 = 0;
  96379. }
  96380. this.limitVelocity2 = this.upperLimit2 - angle2;
  96381. } else {
  96382. this.limitState2 = 2;
  96383. this.limitImpulse2 = 0;
  96384. this.limitVelocity2 = 0;
  96385. }
  96386. if (!enableSpring2) {
  96387. if (this.limitVelocity2 > 0.02) this.limitVelocity2 -= 0.02;
  96388. else if (this.limitVelocity2 < -0.02) this.limitVelocity2 += 0.02;
  96389. else this.limitVelocity2 = 0;
  96390. }
  96391. } else {
  96392. this.limitState2 = 2;
  96393. this.limitImpulse2 = 0;
  96394. }
  96395. var angle3 = this.limitMotor3.angle;
  96396. if (enableLimit3) {
  96397. if (this.lowerLimit3 == this.upperLimit3) {
  96398. if (this.limitState3 != 0) {
  96399. this.limitState3 = 0;
  96400. this.limitImpulse3 = 0;
  96401. }
  96402. this.limitVelocity3 = this.lowerLimit3 - angle3;
  96403. } else if (angle3 < this.lowerLimit3) {
  96404. if (this.limitState3 != -1) {
  96405. this.limitState3 = -1;
  96406. this.limitImpulse3 = 0;
  96407. }
  96408. this.limitVelocity3 = this.lowerLimit3 - angle3;
  96409. } else if (angle3 > this.upperLimit3) {
  96410. if (this.limitState3 != 1) {
  96411. this.limitState3 = 1;
  96412. this.limitImpulse3 = 0;
  96413. }
  96414. this.limitVelocity3 = this.upperLimit3 - angle3;
  96415. } else {
  96416. this.limitState3 = 2;
  96417. this.limitImpulse3 = 0;
  96418. this.limitVelocity3 = 0;
  96419. }
  96420. if (!enableSpring3) {
  96421. if (this.limitVelocity3 > 0.02) this.limitVelocity3 -= 0.02;
  96422. else if (this.limitVelocity3 < -0.02) this.limitVelocity3 += 0.02;
  96423. else this.limitVelocity3 = 0;
  96424. }
  96425. } else {
  96426. this.limitState3 = 2;
  96427. this.limitImpulse3 = 0;
  96428. }
  96429. if (this.enableMotor1 && (this.limitState1 != 0 || enableSpring1)) {
  96430. this.maxMotorImpulse1 = this.maxMotorForce1 * timeStep;
  96431. } else {
  96432. this.motorImpulse1 = 0;
  96433. this.maxMotorImpulse1 = 0;
  96434. }
  96435. if (this.enableMotor2 && (this.limitState2 != 0 || enableSpring2)) {
  96436. this.maxMotorImpulse2 = this.maxMotorForce2 * timeStep;
  96437. } else {
  96438. this.motorImpulse2 = 0;
  96439. this.maxMotorImpulse2 = 0;
  96440. }
  96441. if (this.enableMotor3 && (this.limitState3 != 0 || enableSpring3)) {
  96442. this.maxMotorImpulse3 = this.maxMotorForce3 * timeStep;
  96443. } else {
  96444. this.motorImpulse3 = 0;
  96445. this.maxMotorImpulse3 = 0;
  96446. }
  96447. // build jacobians
  96448. this.a1x1 = this.ax1 * this.i1e00 + this.ay1 * this.i1e01 + this.az1 * this.i1e02;
  96449. this.a1y1 = this.ax1 * this.i1e10 + this.ay1 * this.i1e11 + this.az1 * this.i1e12;
  96450. this.a1z1 = this.ax1 * this.i1e20 + this.ay1 * this.i1e21 + this.az1 * this.i1e22;
  96451. this.a2x1 = this.ax1 * this.i2e00 + this.ay1 * this.i2e01 + this.az1 * this.i2e02;
  96452. this.a2y1 = this.ax1 * this.i2e10 + this.ay1 * this.i2e11 + this.az1 * this.i2e12;
  96453. this.a2z1 = this.ax1 * this.i2e20 + this.ay1 * this.i2e21 + this.az1 * this.i2e22;
  96454. this.a1x2 = this.ax2 * this.i1e00 + this.ay2 * this.i1e01 + this.az2 * this.i1e02;
  96455. this.a1y2 = this.ax2 * this.i1e10 + this.ay2 * this.i1e11 + this.az2 * this.i1e12;
  96456. this.a1z2 = this.ax2 * this.i1e20 + this.ay2 * this.i1e21 + this.az2 * this.i1e22;
  96457. this.a2x2 = this.ax2 * this.i2e00 + this.ay2 * this.i2e01 + this.az2 * this.i2e02;
  96458. this.a2y2 = this.ax2 * this.i2e10 + this.ay2 * this.i2e11 + this.az2 * this.i2e12;
  96459. this.a2z2 = this.ax2 * this.i2e20 + this.ay2 * this.i2e21 + this.az2 * this.i2e22;
  96460. this.a1x3 = this.ax3 * this.i1e00 + this.ay3 * this.i1e01 + this.az3 * this.i1e02;
  96461. this.a1y3 = this.ax3 * this.i1e10 + this.ay3 * this.i1e11 + this.az3 * this.i1e12;
  96462. this.a1z3 = this.ax3 * this.i1e20 + this.ay3 * this.i1e21 + this.az3 * this.i1e22;
  96463. this.a2x3 = this.ax3 * this.i2e00 + this.ay3 * this.i2e01 + this.az3 * this.i2e02;
  96464. this.a2y3 = this.ax3 * this.i2e10 + this.ay3 * this.i2e11 + this.az3 * this.i2e12;
  96465. this.a2z3 = this.ax3 * this.i2e20 + this.ay3 * this.i2e21 + this.az3 * this.i2e22;
  96466. // build an impulse matrix
  96467. this.k00 = this.ax1 * (this.a1x1 + this.a2x1) + this.ay1 * (this.a1y1 + this.a2y1) + this.az1 * (this.a1z1 + this.a2z1);
  96468. this.k01 = this.ax1 * (this.a1x2 + this.a2x2) + this.ay1 * (this.a1y2 + this.a2y2) + this.az1 * (this.a1z2 + this.a2z2);
  96469. this.k02 = this.ax1 * (this.a1x3 + this.a2x3) + this.ay1 * (this.a1y3 + this.a2y3) + this.az1 * (this.a1z3 + this.a2z3);
  96470. this.k10 = this.ax2 * (this.a1x1 + this.a2x1) + this.ay2 * (this.a1y1 + this.a2y1) + this.az2 * (this.a1z1 + this.a2z1);
  96471. this.k11 = this.ax2 * (this.a1x2 + this.a2x2) + this.ay2 * (this.a1y2 + this.a2y2) + this.az2 * (this.a1z2 + this.a2z2);
  96472. this.k12 = this.ax2 * (this.a1x3 + this.a2x3) + this.ay2 * (this.a1y3 + this.a2y3) + this.az2 * (this.a1z3 + this.a2z3);
  96473. this.k20 = this.ax3 * (this.a1x1 + this.a2x1) + this.ay3 * (this.a1y1 + this.a2y1) + this.az3 * (this.a1z1 + this.a2z1);
  96474. this.k21 = this.ax3 * (this.a1x2 + this.a2x2) + this.ay3 * (this.a1y2 + this.a2y2) + this.az3 * (this.a1z2 + this.a2z2);
  96475. this.k22 = this.ax3 * (this.a1x3 + this.a2x3) + this.ay3 * (this.a1y3 + this.a2y3) + this.az3 * (this.a1z3 + this.a2z3);
  96476. this.kv00 = this.k00;
  96477. this.kv11 = this.k11;
  96478. this.kv22 = this.k22;
  96479. this.dv00 = 1 / this.kv00;
  96480. this.dv11 = 1 / this.kv11;
  96481. this.dv22 = 1 / this.kv22;
  96482. if (enableSpring1 && this.limitState1 != 2) {
  96483. var omega = 6.2831853 * frequency1;
  96484. var k = omega * omega * timeStep;
  96485. var dmp = invTimeStep / (k + 2 * this.limitMotor1.dampingRatio * omega);
  96486. this.cfm1 = this.kv00 * dmp;
  96487. this.limitVelocity1 *= k * dmp;
  96488. } else {
  96489. this.cfm1 = 0;
  96490. this.limitVelocity1 *= invTimeStep * 0.05;
  96491. }
  96492. if (enableSpring2 && this.limitState2 != 2) {
  96493. omega = 6.2831853 * frequency2;
  96494. k = omega * omega * timeStep;
  96495. dmp = invTimeStep / (k + 2 * this.limitMotor2.dampingRatio * omega);
  96496. this.cfm2 = this.kv11 * dmp;
  96497. this.limitVelocity2 *= k * dmp;
  96498. } else {
  96499. this.cfm2 = 0;
  96500. this.limitVelocity2 *= invTimeStep * 0.05;
  96501. }
  96502. if (enableSpring3 && this.limitState3 != 2) {
  96503. omega = 6.2831853 * frequency3;
  96504. k = omega * omega * timeStep;
  96505. dmp = invTimeStep / (k + 2 * this.limitMotor3.dampingRatio * omega);
  96506. this.cfm3 = this.kv22 * dmp;
  96507. this.limitVelocity3 *= k * dmp;
  96508. } else {
  96509. this.cfm3 = 0;
  96510. this.limitVelocity3 *= invTimeStep * 0.05;
  96511. }
  96512. this.k00 += this.cfm1;
  96513. this.k11 += this.cfm2;
  96514. this.k22 += this.cfm3;
  96515. var inv = 1 / (
  96516. this.k00 * (this.k11 * this.k22 - this.k21 * this.k12) +
  96517. this.k10 * (this.k21 * this.k02 - this.k01 * this.k22) +
  96518. this.k20 * (this.k01 * this.k12 - this.k11 * this.k02)
  96519. );
  96520. this.d00 = (this.k11 * this.k22 - this.k12 * this.k21) * inv;
  96521. this.d01 = (this.k02 * this.k21 - this.k01 * this.k22) * inv;
  96522. this.d02 = (this.k01 * this.k12 - this.k02 * this.k11) * inv;
  96523. this.d10 = (this.k12 * this.k20 - this.k10 * this.k22) * inv;
  96524. this.d11 = (this.k00 * this.k22 - this.k02 * this.k20) * inv;
  96525. this.d12 = (this.k02 * this.k10 - this.k00 * this.k12) * inv;
  96526. this.d20 = (this.k10 * this.k21 - this.k11 * this.k20) * inv;
  96527. this.d21 = (this.k01 * this.k20 - this.k00 * this.k21) * inv;
  96528. this.d22 = (this.k00 * this.k11 - this.k01 * this.k10) * inv;
  96529. this.limitImpulse1 *= 0.95;
  96530. this.motorImpulse1 *= 0.95;
  96531. this.limitImpulse2 *= 0.95;
  96532. this.motorImpulse2 *= 0.95;
  96533. this.limitImpulse3 *= 0.95;
  96534. this.motorImpulse3 *= 0.95;
  96535. var totalImpulse1 = this.limitImpulse1 + this.motorImpulse1;
  96536. var totalImpulse2 = this.limitImpulse2 + this.motorImpulse2;
  96537. var totalImpulse3 = this.limitImpulse3 + this.motorImpulse3;
  96538. this.a1.x += totalImpulse1 * this.a1x1 + totalImpulse2 * this.a1x2 + totalImpulse3 * this.a1x3;
  96539. this.a1.y += totalImpulse1 * this.a1y1 + totalImpulse2 * this.a1y2 + totalImpulse3 * this.a1y3;
  96540. this.a1.z += totalImpulse1 * this.a1z1 + totalImpulse2 * this.a1z2 + totalImpulse3 * this.a1z3;
  96541. this.a2.x -= totalImpulse1 * this.a2x1 + totalImpulse2 * this.a2x2 + totalImpulse3 * this.a2x3;
  96542. this.a2.y -= totalImpulse1 * this.a2y1 + totalImpulse2 * this.a2y2 + totalImpulse3 * this.a2y3;
  96543. this.a2.z -= totalImpulse1 * this.a2z1 + totalImpulse2 * this.a2z2 + totalImpulse3 * this.a2z3;
  96544. },
  96545. solve_: function () {
  96546. var rvx = this.a2.x - this.a1.x;
  96547. var rvy = this.a2.y - this.a1.y;
  96548. var rvz = this.a2.z - this.a1.z;
  96549. this.limitVelocity3 = 30;
  96550. var rvn1 = rvx * this.ax1 + rvy * this.ay1 + rvz * this.az1 - this.limitVelocity1;
  96551. var rvn2 = rvx * this.ax2 + rvy * this.ay2 + rvz * this.az2 - this.limitVelocity2;
  96552. var rvn3 = rvx * this.ax3 + rvy * this.ay3 + rvz * this.az3 - this.limitVelocity3;
  96553. var dLimitImpulse1 = rvn1 * this.d00 + rvn2 * this.d01 + rvn3 * this.d02;
  96554. var dLimitImpulse2 = rvn1 * this.d10 + rvn2 * this.d11 + rvn3 * this.d12;
  96555. var dLimitImpulse3 = rvn1 * this.d20 + rvn2 * this.d21 + rvn3 * this.d22;
  96556. this.limitImpulse1 += dLimitImpulse1;
  96557. this.limitImpulse2 += dLimitImpulse2;
  96558. this.limitImpulse3 += dLimitImpulse3;
  96559. this.a1.x += dLimitImpulse1 * this.a1x1 + dLimitImpulse2 * this.a1x2 + dLimitImpulse3 * this.a1x3;
  96560. this.a1.y += dLimitImpulse1 * this.a1y1 + dLimitImpulse2 * this.a1y2 + dLimitImpulse3 * this.a1y3;
  96561. this.a1.z += dLimitImpulse1 * this.a1z1 + dLimitImpulse2 * this.a1z2 + dLimitImpulse3 * this.a1z3;
  96562. this.a2.x -= dLimitImpulse1 * this.a2x1 + dLimitImpulse2 * this.a2x2 + dLimitImpulse3 * this.a2x3;
  96563. this.a2.y -= dLimitImpulse1 * this.a2y1 + dLimitImpulse2 * this.a2y2 + dLimitImpulse3 * this.a2y3;
  96564. this.a2.z -= dLimitImpulse1 * this.a2z1 + dLimitImpulse2 * this.a2z2 + dLimitImpulse3 * this.a2z3;
  96565. },
  96566. solve: function () {
  96567. var rvx = this.a2.x - this.a1.x;
  96568. var rvy = this.a2.y - this.a1.y;
  96569. var rvz = this.a2.z - this.a1.z;
  96570. var rvn1 = rvx * this.ax1 + rvy * this.ay1 + rvz * this.az1;
  96571. var rvn2 = rvx * this.ax2 + rvy * this.ay2 + rvz * this.az2;
  96572. var rvn3 = rvx * this.ax3 + rvy * this.ay3 + rvz * this.az3;
  96573. var oldMotorImpulse1 = this.motorImpulse1;
  96574. var oldMotorImpulse2 = this.motorImpulse2;
  96575. var oldMotorImpulse3 = this.motorImpulse3;
  96576. var dMotorImpulse1 = 0;
  96577. var dMotorImpulse2 = 0;
  96578. var dMotorImpulse3 = 0;
  96579. if (this.enableMotor1) {
  96580. dMotorImpulse1 = (rvn1 - this.motorSpeed1) * this.dv00;
  96581. this.motorImpulse1 += dMotorImpulse1;
  96582. if (this.motorImpulse1 > this.maxMotorImpulse1) { // clamp motor impulse
  96583. this.motorImpulse1 = this.maxMotorImpulse1;
  96584. } else if (this.motorImpulse1 < -this.maxMotorImpulse1) {
  96585. this.motorImpulse1 = -this.maxMotorImpulse1;
  96586. }
  96587. dMotorImpulse1 = this.motorImpulse1 - oldMotorImpulse1;
  96588. }
  96589. if (this.enableMotor2) {
  96590. dMotorImpulse2 = (rvn2 - this.motorSpeed2) * this.dv11;
  96591. this.motorImpulse2 += dMotorImpulse2;
  96592. if (this.motorImpulse2 > this.maxMotorImpulse2) { // clamp motor impulse
  96593. this.motorImpulse2 = this.maxMotorImpulse2;
  96594. } else if (this.motorImpulse2 < -this.maxMotorImpulse2) {
  96595. this.motorImpulse2 = -this.maxMotorImpulse2;
  96596. }
  96597. dMotorImpulse2 = this.motorImpulse2 - oldMotorImpulse2;
  96598. }
  96599. if (this.enableMotor3) {
  96600. dMotorImpulse3 = (rvn3 - this.motorSpeed3) * this.dv22;
  96601. this.motorImpulse3 += dMotorImpulse3;
  96602. if (this.motorImpulse3 > this.maxMotorImpulse3) { // clamp motor impulse
  96603. this.motorImpulse3 = this.maxMotorImpulse3;
  96604. } else if (this.motorImpulse3 < -this.maxMotorImpulse3) {
  96605. this.motorImpulse3 = -this.maxMotorImpulse3;
  96606. }
  96607. dMotorImpulse3 = this.motorImpulse3 - oldMotorImpulse3;
  96608. }
  96609. // apply motor impulse to relative velocity
  96610. rvn1 += dMotorImpulse1 * this.kv00 + dMotorImpulse2 * this.k01 + dMotorImpulse3 * this.k02;
  96611. rvn2 += dMotorImpulse1 * this.k10 + dMotorImpulse2 * this.kv11 + dMotorImpulse3 * this.k12;
  96612. rvn3 += dMotorImpulse1 * this.k20 + dMotorImpulse2 * this.k21 + dMotorImpulse3 * this.kv22;
  96613. // subtract target velocity and applied impulse
  96614. rvn1 -= this.limitVelocity1 + this.limitImpulse1 * this.cfm1;
  96615. rvn2 -= this.limitVelocity2 + this.limitImpulse2 * this.cfm2;
  96616. rvn3 -= this.limitVelocity3 + this.limitImpulse3 * this.cfm3;
  96617. var oldLimitImpulse1 = this.limitImpulse1;
  96618. var oldLimitImpulse2 = this.limitImpulse2;
  96619. var oldLimitImpulse3 = this.limitImpulse3;
  96620. var dLimitImpulse1 = rvn1 * this.d00 + rvn2 * this.d01 + rvn3 * this.d02;
  96621. var dLimitImpulse2 = rvn1 * this.d10 + rvn2 * this.d11 + rvn3 * this.d12;
  96622. var dLimitImpulse3 = rvn1 * this.d20 + rvn2 * this.d21 + rvn3 * this.d22;
  96623. this.limitImpulse1 += dLimitImpulse1;
  96624. this.limitImpulse2 += dLimitImpulse2;
  96625. this.limitImpulse3 += dLimitImpulse3;
  96626. // clamp
  96627. var clampState = 0;
  96628. if (this.limitState1 == 2 || this.limitImpulse1 * this.limitState1 < 0) {
  96629. dLimitImpulse1 = -oldLimitImpulse1;
  96630. rvn2 += dLimitImpulse1 * this.k10;
  96631. rvn3 += dLimitImpulse1 * this.k20;
  96632. clampState |= 1;
  96633. }
  96634. if (this.limitState2 == 2 || this.limitImpulse2 * this.limitState2 < 0) {
  96635. dLimitImpulse2 = -oldLimitImpulse2;
  96636. rvn1 += dLimitImpulse2 * this.k01;
  96637. rvn3 += dLimitImpulse2 * this.k21;
  96638. clampState |= 2;
  96639. }
  96640. if (this.limitState3 == 2 || this.limitImpulse3 * this.limitState3 < 0) {
  96641. dLimitImpulse3 = -oldLimitImpulse3;
  96642. rvn1 += dLimitImpulse3 * this.k02;
  96643. rvn2 += dLimitImpulse3 * this.k12;
  96644. clampState |= 4;
  96645. }
  96646. // update un-clamped impulse
  96647. // TODO: isolate division
  96648. var det;
  96649. switch (clampState) {
  96650. case 1: // update 2 3
  96651. det = 1 / (this.k11 * this.k22 - this.k12 * this.k21);
  96652. dLimitImpulse2 = (this.k22 * rvn2 + -this.k12 * rvn3) * det;
  96653. dLimitImpulse3 = (-this.k21 * rvn2 + this.k11 * rvn3) * det;
  96654. break;
  96655. case 2: // update 1 3
  96656. det = 1 / (this.k00 * this.k22 - this.k02 * this.k20);
  96657. dLimitImpulse1 = (this.k22 * rvn1 + -this.k02 * rvn3) * det;
  96658. dLimitImpulse3 = (-this.k20 * rvn1 + this.k00 * rvn3) * det;
  96659. break;
  96660. case 3: // update 3
  96661. dLimitImpulse3 = rvn3 / this.k22;
  96662. break;
  96663. case 4: // update 1 2
  96664. det = 1 / (this.k00 * this.k11 - this.k01 * this.k10);
  96665. dLimitImpulse1 = (this.k11 * rvn1 + -this.k01 * rvn2) * det;
  96666. dLimitImpulse2 = (-this.k10 * rvn1 + this.k00 * rvn2) * det;
  96667. break;
  96668. case 5: // update 2
  96669. dLimitImpulse2 = rvn2 / this.k11;
  96670. break;
  96671. case 6: // update 1
  96672. dLimitImpulse1 = rvn1 / this.k00;
  96673. break;
  96674. }
  96675. this.limitImpulse1 = dLimitImpulse1 + oldLimitImpulse1;
  96676. this.limitImpulse2 = dLimitImpulse2 + oldLimitImpulse2;
  96677. this.limitImpulse3 = dLimitImpulse3 + oldLimitImpulse3;
  96678. var dImpulse1 = dMotorImpulse1 + dLimitImpulse1;
  96679. var dImpulse2 = dMotorImpulse2 + dLimitImpulse2;
  96680. var dImpulse3 = dMotorImpulse3 + dLimitImpulse3;
  96681. // apply impulse
  96682. this.a1.x += dImpulse1 * this.a1x1 + dImpulse2 * this.a1x2 + dImpulse3 * this.a1x3;
  96683. this.a1.y += dImpulse1 * this.a1y1 + dImpulse2 * this.a1y2 + dImpulse3 * this.a1y3;
  96684. this.a1.z += dImpulse1 * this.a1z1 + dImpulse2 * this.a1z2 + dImpulse3 * this.a1z3;
  96685. this.a2.x -= dImpulse1 * this.a2x1 + dImpulse2 * this.a2x2 + dImpulse3 * this.a2x3;
  96686. this.a2.y -= dImpulse1 * this.a2y1 + dImpulse2 * this.a2y2 + dImpulse3 * this.a2y3;
  96687. this.a2.z -= dImpulse1 * this.a2z1 + dImpulse2 * this.a2z2 + dImpulse3 * this.a2z3;
  96688. rvx = this.a2.x - this.a1.x;
  96689. rvy = this.a2.y - this.a1.y;
  96690. rvz = this.a2.z - this.a1.z;
  96691. rvn2 = rvx * this.ax2 + rvy * this.ay2 + rvz * this.az2;
  96692. }
  96693. }
  96694. /**
  96695. * A rotational constraint for various joints.
  96696. * @author saharan
  96697. */
  96698. OIMO.RotationalConstraint = function (joint, limitMotor) {
  96699. this.cfm = NaN;
  96700. this.i1e00 = NaN;
  96701. this.i1e01 = NaN;
  96702. this.i1e02 = NaN;
  96703. this.i1e10 = NaN;
  96704. this.i1e11 = NaN;
  96705. this.i1e12 = NaN;
  96706. this.i1e20 = NaN;
  96707. this.i1e21 = NaN;
  96708. this.i1e22 = NaN;
  96709. this.i2e00 = NaN;
  96710. this.i2e01 = NaN;
  96711. this.i2e02 = NaN;
  96712. this.i2e10 = NaN;
  96713. this.i2e11 = NaN;
  96714. this.i2e12 = NaN;
  96715. this.i2e20 = NaN;
  96716. this.i2e21 = NaN;
  96717. this.i2e22 = NaN;
  96718. this.motorDenom = NaN;
  96719. this.invMotorDenom = NaN;
  96720. this.invDenom = NaN;
  96721. this.ax = NaN;
  96722. this.ay = NaN;
  96723. this.az = NaN;
  96724. this.a1x = NaN;
  96725. this.a1y = NaN;
  96726. this.a1z = NaN;
  96727. this.a2x = NaN;
  96728. this.a2y = NaN;
  96729. this.a2z = NaN;
  96730. this.enableLimit = false;
  96731. this.lowerLimit = NaN;
  96732. this.upperLimit = NaN;
  96733. this.limitVelocity = NaN;
  96734. this.limitState = 0; // -1: at lower, 0: locked, 1: at upper, 2: free
  96735. this.enableMotor = false;
  96736. this.motorSpeed = NaN;
  96737. this.maxMotorForce = NaN;
  96738. this.maxMotorImpulse = NaN;
  96739. this.limitMotor = limitMotor;
  96740. this.b1 = joint.body1;
  96741. this.b2 = joint.body2;
  96742. this.a1 = this.b1.angularVelocity;
  96743. this.a2 = this.b2.angularVelocity;
  96744. this.i1 = this.b1.inverseInertia;
  96745. this.i2 = this.b2.inverseInertia;
  96746. this.limitImpulse = 0;
  96747. this.motorImpulse = 0;
  96748. }
  96749. OIMO.RotationalConstraint.prototype = {
  96750. constructor: OIMO.RotationalConstraint,
  96751. preSolve: function (timeStep, invTimeStep) {
  96752. this.ax = this.limitMotor.axis.x;
  96753. this.ay = this.limitMotor.axis.y;
  96754. this.az = this.limitMotor.axis.z;
  96755. this.lowerLimit = this.limitMotor.lowerLimit;
  96756. this.upperLimit = this.limitMotor.upperLimit;
  96757. this.motorSpeed = this.limitMotor.motorSpeed;
  96758. this.maxMotorForce = this.limitMotor.maxMotorForce;
  96759. this.enableMotor = this.maxMotorForce > 0;
  96760. var ti1 = this.i1.elements;
  96761. var ti2 = this.i2.elements;
  96762. this.i1e00 = ti1[0];
  96763. this.i1e01 = ti1[1];
  96764. this.i1e02 = ti1[2];
  96765. this.i1e10 = ti1[3];
  96766. this.i1e11 = ti1[4];
  96767. this.i1e12 = ti1[5];
  96768. this.i1e20 = ti1[6];
  96769. this.i1e21 = ti1[7];
  96770. this.i1e22 = ti1[8];
  96771. this.i2e00 = ti2[0];
  96772. this.i2e01 = ti2[1];
  96773. this.i2e02 = ti2[2];
  96774. this.i2e10 = ti2[3];
  96775. this.i2e11 = ti2[4];
  96776. this.i2e12 = ti2[5];
  96777. this.i2e20 = ti2[6];
  96778. this.i2e21 = ti2[7];
  96779. this.i2e22 = ti2[8];
  96780. var frequency = this.limitMotor.frequency;
  96781. var enableSpring = frequency > 0;
  96782. var enableLimit = this.lowerLimit <= this.upperLimit;
  96783. var angle = this.limitMotor.angle;
  96784. if (enableLimit) {
  96785. if (this.lowerLimit == this.upperLimit) {
  96786. if (this.limitState != 0) {
  96787. this.limitState = 0;
  96788. this.limitImpulse = 0;
  96789. }
  96790. this.limitVelocity = this.lowerLimit - angle;
  96791. } else if (angle < this.lowerLimit) {
  96792. if (this.limitState != -1) {
  96793. this.limitState = -1;
  96794. this.limitImpulse = 0;
  96795. }
  96796. this.limitVelocity = this.lowerLimit - angle;
  96797. } else if (angle > this.upperLimit) {
  96798. if (this.limitState != 1) {
  96799. this.limitState = 1;
  96800. this.limitImpulse = 0;
  96801. }
  96802. this.limitVelocity = this.upperLimit - angle;
  96803. } else {
  96804. this.limitState = 2;
  96805. this.limitImpulse = 0;
  96806. this.limitVelocity = 0;
  96807. }
  96808. if (!enableSpring) {
  96809. if (this.limitVelocity > 0.02) this.limitVelocity -= 0.02;
  96810. else if (this.limitVelocity < -0.02) this.limitVelocity += 0.02;
  96811. else this.limitVelocity = 0;
  96812. }
  96813. } else {
  96814. this.limitState = 2;
  96815. this.limitImpulse = 0;
  96816. }
  96817. if (this.enableMotor && (this.limitState != 0 || enableSpring)) {
  96818. this.maxMotorImpulse = this.maxMotorForce * timeStep;
  96819. } else {
  96820. this.motorImpulse = 0;
  96821. this.maxMotorImpulse = 0;
  96822. }
  96823. this.a1x = this.ax * this.i1e00 + this.ay * this.i1e01 + this.az * this.i1e02;
  96824. this.a1y = this.ax * this.i1e10 + this.ay * this.i1e11 + this.az * this.i1e12;
  96825. this.a1z = this.ax * this.i1e20 + this.ay * this.i1e21 + this.az * this.i1e22;
  96826. this.a2x = this.ax * this.i2e00 + this.ay * this.i2e01 + this.az * this.i2e02;
  96827. this.a2y = this.ax * this.i2e10 + this.ay * this.i2e11 + this.az * this.i2e12;
  96828. this.a2z = this.ax * this.i2e20 + this.ay * this.i2e21 + this.az * this.i2e22;
  96829. this.motorDenom = this.ax * (this.a1x + this.a2x) + this.ay * (this.a1y + this.a2y) + this.az * (this.a1z + this.a2z);
  96830. this.invMotorDenom = 1 / this.motorDenom;
  96831. if (enableSpring && this.limitState != 2) {
  96832. var omega = 6.2831853 * frequency;
  96833. var k = omega * omega * timeStep;
  96834. var dmp = invTimeStep / (k + 2 * this.limitMotor.dampingRatio * omega);
  96835. this.cfm = this.motorDenom * dmp;
  96836. this.limitVelocity *= k * dmp;
  96837. } else {
  96838. this.cfm = 0;
  96839. this.limitVelocity *= invTimeStep * 0.05;
  96840. }
  96841. this.invDenom = 1 / (this.motorDenom + this.cfm);
  96842. this.limitImpulse *= 0.95;
  96843. this.motorImpulse *= 0.95;
  96844. var totalImpulse = this.limitImpulse + this.motorImpulse;
  96845. this.a1.x += totalImpulse * this.a1x;
  96846. this.a1.y += totalImpulse * this.a1y;
  96847. this.a1.z += totalImpulse * this.a1z;
  96848. this.a2.x -= totalImpulse * this.a2x;
  96849. this.a2.y -= totalImpulse * this.a2y;
  96850. this.a2.z -= totalImpulse * this.a2z;
  96851. },
  96852. solve: function () {
  96853. 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);
  96854. // motor part
  96855. var newMotorImpulse;
  96856. if (this.enableMotor) {
  96857. newMotorImpulse = (rvn - this.motorSpeed) * this.invMotorDenom;
  96858. var oldMotorImpulse = this.motorImpulse;
  96859. this.motorImpulse += newMotorImpulse;
  96860. if (this.motorImpulse > this.maxMotorImpulse) this.motorImpulse = this.maxMotorImpulse;
  96861. else if (this.motorImpulse < -this.maxMotorImpulse) this.motorImpulse = -this.maxMotorImpulse;
  96862. newMotorImpulse = this.motorImpulse - oldMotorImpulse;
  96863. rvn -= newMotorImpulse * this.motorDenom;
  96864. } else newMotorImpulse = 0;
  96865. // limit part
  96866. var newLimitImpulse;
  96867. if (this.limitState != 2) {
  96868. newLimitImpulse = (rvn - this.limitVelocity - this.limitImpulse * this.cfm) * this.invDenom;
  96869. var oldLimitImpulse = this.limitImpulse;
  96870. this.limitImpulse += newLimitImpulse;
  96871. if (this.limitImpulse * this.limitState < 0) this.limitImpulse = 0;
  96872. newLimitImpulse = this.limitImpulse - oldLimitImpulse;
  96873. } else newLimitImpulse = 0;
  96874. var totalImpulse = newLimitImpulse + newMotorImpulse;
  96875. this.a1.x += totalImpulse * this.a1x;
  96876. this.a1.y += totalImpulse * this.a1y;
  96877. this.a1.z += totalImpulse * this.a1z;
  96878. this.a2.x -= totalImpulse * this.a2x;
  96879. this.a2.y -= totalImpulse * this.a2y;
  96880. this.a2.z -= totalImpulse * this.a2z;
  96881. }
  96882. }
  96883. /**
  96884. * A three-axis translational constraint for various joints.
  96885. * @author saharan
  96886. */
  96887. OIMO.Translational3Constraint = function (joint, limitMotor1, limitMotor2, limitMotor3) {
  96888. this.m1 = NaN;
  96889. this.m2 = NaN;
  96890. this.i1e00 = NaN;
  96891. this.i1e01 = NaN;
  96892. this.i1e02 = NaN;
  96893. this.i1e10 = NaN;
  96894. this.i1e11 = NaN;
  96895. this.i1e12 = NaN;
  96896. this.i1e20 = NaN;
  96897. this.i1e21 = NaN;
  96898. this.i1e22 = NaN;
  96899. this.i2e00 = NaN;
  96900. this.i2e01 = NaN;
  96901. this.i2e02 = NaN;
  96902. this.i2e10 = NaN;
  96903. this.i2e11 = NaN;
  96904. this.i2e12 = NaN;
  96905. this.i2e20 = NaN;
  96906. this.i2e21 = NaN;
  96907. this.i2e22 = NaN;
  96908. this.ax1 = NaN;
  96909. this.ay1 = NaN;
  96910. this.az1 = NaN;
  96911. this.ax2 = NaN;
  96912. this.ay2 = NaN;
  96913. this.az2 = NaN;
  96914. this.ax3 = NaN;
  96915. this.ay3 = NaN;
  96916. this.az3 = NaN;
  96917. this.r1x = NaN;
  96918. this.r1y = NaN;
  96919. this.r1z = NaN;
  96920. this.r2x = NaN;
  96921. this.r2y = NaN;
  96922. this.r2z = NaN;
  96923. this.t1x1 = NaN;// jacobians
  96924. this.t1y1 = NaN;
  96925. this.t1z1 = NaN;
  96926. this.t2x1 = NaN;
  96927. this.t2y1 = NaN;
  96928. this.t2z1 = NaN;
  96929. this.l1x1 = NaN;
  96930. this.l1y1 = NaN;
  96931. this.l1z1 = NaN;
  96932. this.l2x1 = NaN;
  96933. this.l2y1 = NaN;
  96934. this.l2z1 = NaN;
  96935. this.a1x1 = NaN;
  96936. this.a1y1 = NaN;
  96937. this.a1z1 = NaN;
  96938. this.a2x1 = NaN;
  96939. this.a2y1 = NaN;
  96940. this.a2z1 = NaN;
  96941. this.t1x2 = NaN;
  96942. this.t1y2 = NaN;
  96943. this.t1z2 = NaN;
  96944. this.t2x2 = NaN;
  96945. this.t2y2 = NaN;
  96946. this.t2z2 = NaN;
  96947. this.l1x2 = NaN;
  96948. this.l1y2 = NaN;
  96949. this.l1z2 = NaN;
  96950. this.l2x2 = NaN;
  96951. this.l2y2 = NaN;
  96952. this.l2z2 = NaN;
  96953. this.a1x2 = NaN;
  96954. this.a1y2 = NaN;
  96955. this.a1z2 = NaN;
  96956. this.a2x2 = NaN;
  96957. this.a2y2 = NaN;
  96958. this.a2z2 = NaN;
  96959. this.t1x3 = NaN;
  96960. this.t1y3 = NaN;
  96961. this.t1z3 = NaN;
  96962. this.t2x3 = NaN;
  96963. this.t2y3 = NaN;
  96964. this.t2z3 = NaN;
  96965. this.l1x3 = NaN;
  96966. this.l1y3 = NaN;
  96967. this.l1z3 = NaN;
  96968. this.l2x3 = NaN;
  96969. this.l2y3 = NaN;
  96970. this.l2z3 = NaN;
  96971. this.a1x3 = NaN;
  96972. this.a1y3 = NaN;
  96973. this.a1z3 = NaN;
  96974. this.a2x3 = NaN;
  96975. this.a2y3 = NaN;
  96976. this.a2z3 = NaN;
  96977. this.lowerLimit1 = NaN;
  96978. this.upperLimit1 = NaN;
  96979. this.limitVelocity1 = NaN;
  96980. this.limitState1 = 0; // -1: at lower, 0: locked, 1: at upper, 2: unlimited
  96981. this.enableMotor1 = false;
  96982. this.motorSpeed1 = NaN;
  96983. this.maxMotorForce1 = NaN;
  96984. this.maxMotorImpulse1 = NaN;
  96985. this.lowerLimit2 = NaN;
  96986. this.upperLimit2 = NaN;
  96987. this.limitVelocity2 = NaN;
  96988. this.limitState2 = 0; // -1: at lower, 0: locked, 1: at upper, 2: unlimited
  96989. this.enableMotor2 = false;
  96990. this.motorSpeed2 = NaN;
  96991. this.maxMotorForce2 = NaN;
  96992. this.maxMotorImpulse2 = NaN;
  96993. this.lowerLimit3 = NaN;
  96994. this.upperLimit3 = NaN;
  96995. this.limitVelocity3 = NaN;
  96996. this.limitState3 = 0; // -1: at lower, 0: locked, 1: at upper, 2: unlimited
  96997. this.enableMotor3 = false;
  96998. this.motorSpeed3 = NaN;
  96999. this.maxMotorForce3 = NaN;
  97000. this.maxMotorImpulse3 = NaN;
  97001. this.k00 = NaN; // K = J*M*JT
  97002. this.k01 = NaN;
  97003. this.k02 = NaN;
  97004. this.k10 = NaN;
  97005. this.k11 = NaN;
  97006. this.k12 = NaN;
  97007. this.k20 = NaN;
  97008. this.k21 = NaN;
  97009. this.k22 = NaN;
  97010. this.kv00 = NaN; // diagonals without CFMs
  97011. this.kv11 = NaN;
  97012. this.kv22 = NaN;
  97013. this.dv00 = NaN; // ...inverted
  97014. this.dv11 = NaN;
  97015. this.dv22 = NaN;
  97016. this.d00 = NaN; // K^-1
  97017. this.d01 = NaN;
  97018. this.d02 = NaN;
  97019. this.d10 = NaN;
  97020. this.d11 = NaN;
  97021. this.d12 = NaN;
  97022. this.d20 = NaN;
  97023. this.d21 = NaN;
  97024. this.d22 = NaN;
  97025. this.limitMotor1 = limitMotor1;
  97026. this.limitMotor2 = limitMotor2;
  97027. this.limitMotor3 = limitMotor3;
  97028. this.b1 = joint.body1;
  97029. this.b2 = joint.body2;
  97030. this.p1 = joint.anchorPoint1;
  97031. this.p2 = joint.anchorPoint2;
  97032. this.r1 = joint.relativeAnchorPoint1;
  97033. this.r2 = joint.relativeAnchorPoint2;
  97034. this.l1 = this.b1.linearVelocity;
  97035. this.l2 = this.b2.linearVelocity;
  97036. this.a1 = this.b1.angularVelocity;
  97037. this.a2 = this.b2.angularVelocity;
  97038. this.i1 = this.b1.inverseInertia;
  97039. this.i2 = this.b2.inverseInertia;
  97040. this.limitImpulse1 = 0;
  97041. this.motorImpulse1 = 0;
  97042. this.limitImpulse2 = 0;
  97043. this.motorImpulse2 = 0;
  97044. this.limitImpulse3 = 0;
  97045. this.motorImpulse3 = 0;
  97046. this.cfm1 = 0;// Constraint Force Mixing
  97047. this.cfm2 = 0;
  97048. this.cfm3 = 0;
  97049. this.weight = -1;
  97050. }
  97051. OIMO.Translational3Constraint.prototype = {
  97052. constructor: OIMO.Translational3Constraint,
  97053. preSolve: function (timeStep, invTimeStep) {
  97054. this.ax1 = this.limitMotor1.axis.x;
  97055. this.ay1 = this.limitMotor1.axis.y;
  97056. this.az1 = this.limitMotor1.axis.z;
  97057. this.ax2 = this.limitMotor2.axis.x;
  97058. this.ay2 = this.limitMotor2.axis.y;
  97059. this.az2 = this.limitMotor2.axis.z;
  97060. this.ax3 = this.limitMotor3.axis.x;
  97061. this.ay3 = this.limitMotor3.axis.y;
  97062. this.az3 = this.limitMotor3.axis.z;
  97063. this.lowerLimit1 = this.limitMotor1.lowerLimit;
  97064. this.upperLimit1 = this.limitMotor1.upperLimit;
  97065. this.motorSpeed1 = this.limitMotor1.motorSpeed;
  97066. this.maxMotorForce1 = this.limitMotor1.maxMotorForce;
  97067. this.enableMotor1 = this.maxMotorForce1 > 0;
  97068. this.lowerLimit2 = this.limitMotor2.lowerLimit;
  97069. this.upperLimit2 = this.limitMotor2.upperLimit;
  97070. this.motorSpeed2 = this.limitMotor2.motorSpeed;
  97071. this.maxMotorForce2 = this.limitMotor2.maxMotorForce;
  97072. this.enableMotor2 = this.maxMotorForce2 > 0;
  97073. this.lowerLimit3 = this.limitMotor3.lowerLimit;
  97074. this.upperLimit3 = this.limitMotor3.upperLimit;
  97075. this.motorSpeed3 = this.limitMotor3.motorSpeed;
  97076. this.maxMotorForce3 = this.limitMotor3.maxMotorForce;
  97077. this.enableMotor3 = this.maxMotorForce3 > 0;
  97078. this.m1 = this.b1.inverseMass;
  97079. this.m2 = this.b2.inverseMass;
  97080. var ti1 = this.i1.elements;
  97081. var ti2 = this.i2.elements;
  97082. this.i1e00 = ti1[0];
  97083. this.i1e01 = ti1[1];
  97084. this.i1e02 = ti1[2];
  97085. this.i1e10 = ti1[3];
  97086. this.i1e11 = ti1[4];
  97087. this.i1e12 = ti1[5];
  97088. this.i1e20 = ti1[6];
  97089. this.i1e21 = ti1[7];
  97090. this.i1e22 = ti1[8];
  97091. this.i2e00 = ti2[0];
  97092. this.i2e01 = ti2[1];
  97093. this.i2e02 = ti2[2];
  97094. this.i2e10 = ti2[3];
  97095. this.i2e11 = ti2[4];
  97096. this.i2e12 = ti2[5];
  97097. this.i2e20 = ti2[6];
  97098. this.i2e21 = ti2[7];
  97099. this.i2e22 = ti2[8];
  97100. var dx = this.p2.x - this.p1.x;
  97101. var dy = this.p2.y - this.p1.y;
  97102. var dz = this.p2.z - this.p1.z;
  97103. var d1 = dx * this.ax1 + dy * this.ay1 + dz * this.az1;
  97104. var d2 = dx * this.ax2 + dy * this.ay2 + dz * this.az2;
  97105. var d3 = dx * this.ax3 + dy * this.ay3 + dz * this.az3;
  97106. var frequency1 = this.limitMotor1.frequency;
  97107. var frequency2 = this.limitMotor2.frequency;
  97108. var frequency3 = this.limitMotor3.frequency;
  97109. var enableSpring1 = frequency1 > 0;
  97110. var enableSpring2 = frequency2 > 0;
  97111. var enableSpring3 = frequency3 > 0;
  97112. var enableLimit1 = this.lowerLimit1 <= this.upperLimit1;
  97113. var enableLimit2 = this.lowerLimit2 <= this.upperLimit2;
  97114. var enableLimit3 = this.lowerLimit3 <= this.upperLimit3;
  97115. // for stability
  97116. if (enableSpring1 && d1 > 20 || d1 < -20) {
  97117. enableSpring1 = false;
  97118. }
  97119. if (enableSpring2 && d2 > 20 || d2 < -20) {
  97120. enableSpring2 = false;
  97121. }
  97122. if (enableSpring3 && d3 > 20 || d3 < -20) {
  97123. enableSpring3 = false;
  97124. }
  97125. if (enableLimit1) {
  97126. if (this.lowerLimit1 == this.upperLimit1) {
  97127. if (this.limitState1 != 0) {
  97128. this.limitState1 = 0;
  97129. this.limitImpulse1 = 0;
  97130. }
  97131. this.limitVelocity1 = this.lowerLimit1 - d1;
  97132. if (!enableSpring1) d1 = this.lowerLimit1;
  97133. } else if (d1 < this.lowerLimit1) {
  97134. if (this.limitState1 != -1) {
  97135. this.limitState1 = -1;
  97136. this.limitImpulse1 = 0;
  97137. }
  97138. this.limitVelocity1 = this.lowerLimit1 - d1;
  97139. if (!enableSpring1) d1 = this.lowerLimit1;
  97140. } else if (d1 > this.upperLimit1) {
  97141. if (this.limitState1 != 1) {
  97142. this.limitState1 = 1;
  97143. this.limitImpulse1 = 0;
  97144. }
  97145. this.limitVelocity1 = this.upperLimit1 - d1;
  97146. if (!enableSpring1) d1 = this.upperLimit1;
  97147. } else {
  97148. this.limitState1 = 2;
  97149. this.limitImpulse1 = 0;
  97150. this.limitVelocity1 = 0;
  97151. }
  97152. if (!enableSpring1) {
  97153. if (this.limitVelocity1 > 0.005) this.limitVelocity1 -= 0.005;
  97154. else if (this.limitVelocity1 < -0.005) this.limitVelocity1 += 0.005;
  97155. else this.limitVelocity1 = 0;
  97156. }
  97157. } else {
  97158. this.limitState1 = 2;
  97159. this.limitImpulse1 = 0;
  97160. }
  97161. if (enableLimit2) {
  97162. if (this.lowerLimit2 == this.upperLimit2) {
  97163. if (this.limitState2 != 0) {
  97164. this.limitState2 = 0;
  97165. this.limitImpulse2 = 0;
  97166. }
  97167. this.limitVelocity2 = this.lowerLimit2 - d2;
  97168. if (!enableSpring2) d2 = this.lowerLimit2;
  97169. } else if (d2 < this.lowerLimit2) {
  97170. if (this.limitState2 != -1) {
  97171. this.limitState2 = -1;
  97172. this.limitImpulse2 = 0;
  97173. }
  97174. this.limitVelocity2 = this.lowerLimit2 - d2;
  97175. if (!enableSpring2) d2 = this.lowerLimit2;
  97176. } else if (d2 > this.upperLimit2) {
  97177. if (this.limitState2 != 1) {
  97178. this.limitState2 = 1;
  97179. this.limitImpulse2 = 0;
  97180. }
  97181. this.limitVelocity2 = this.upperLimit2 - d2;
  97182. if (!enableSpring2) d2 = this.upperLimit2;
  97183. } else {
  97184. this.limitState2 = 2;
  97185. this.limitImpulse2 = 0;
  97186. this.limitVelocity2 = 0;
  97187. }
  97188. if (!enableSpring2) {
  97189. if (this.limitVelocity2 > 0.005) this.limitVelocity2 -= 0.005;
  97190. else if (this.limitVelocity2 < -0.005) this.limitVelocity2 += 0.005;
  97191. else this.limitVelocity2 = 0;
  97192. }
  97193. } else {
  97194. this.limitState2 = 2;
  97195. this.limitImpulse2 = 0;
  97196. }
  97197. if (enableLimit3) {
  97198. if (this.lowerLimit3 == this.upperLimit3) {
  97199. if (this.limitState3 != 0) {
  97200. this.limitState3 = 0;
  97201. this.limitImpulse3 = 0;
  97202. }
  97203. this.limitVelocity3 = this.lowerLimit3 - d3;
  97204. if (!enableSpring3) d3 = this.lowerLimit3;
  97205. } else if (d3 < this.lowerLimit3) {
  97206. if (this.limitState3 != -1) {
  97207. this.limitState3 = -1;
  97208. this.limitImpulse3 = 0;
  97209. }
  97210. this.limitVelocity3 = this.lowerLimit3 - d3;
  97211. if (!enableSpring3) d3 = this.lowerLimit3;
  97212. } else if (d3 > this.upperLimit3) {
  97213. if (this.limitState3 != 1) {
  97214. this.limitState3 = 1;
  97215. this.limitImpulse3 = 0;
  97216. }
  97217. this.limitVelocity3 = this.upperLimit3 - d3;
  97218. if (!enableSpring3) d3 = this.upperLimit3;
  97219. } else {
  97220. this.limitState3 = 2;
  97221. this.limitImpulse3 = 0;
  97222. this.limitVelocity3 = 0;
  97223. }
  97224. if (!enableSpring3) {
  97225. if (this.limitVelocity3 > 0.005) this.limitVelocity3 -= 0.005;
  97226. else if (this.limitVelocity3 < -0.005) this.limitVelocity3 += 0.005;
  97227. else this.limitVelocity3 = 0;
  97228. }
  97229. } else {
  97230. this.limitState3 = 2;
  97231. this.limitImpulse3 = 0;
  97232. }
  97233. if (this.enableMotor1 && (this.limitState1 != 0 || enableSpring1)) {
  97234. this.maxMotorImpulse1 = this.maxMotorForce1 * timeStep;
  97235. } else {
  97236. this.motorImpulse1 = 0;
  97237. this.maxMotorImpulse1 = 0;
  97238. }
  97239. if (this.enableMotor2 && (this.limitState2 != 0 || enableSpring2)) {
  97240. this.maxMotorImpulse2 = this.maxMotorForce2 * timeStep;
  97241. } else {
  97242. this.motorImpulse2 = 0;
  97243. this.maxMotorImpulse2 = 0;
  97244. }
  97245. if (this.enableMotor3 && (this.limitState3 != 0 || enableSpring3)) {
  97246. this.maxMotorImpulse3 = this.maxMotorForce3 * timeStep;
  97247. } else {
  97248. this.motorImpulse3 = 0;
  97249. this.maxMotorImpulse3 = 0;
  97250. }
  97251. var rdx = d1 * this.ax1 + d2 * this.ax2 + d3 * this.ax2;
  97252. var rdy = d1 * this.ay1 + d2 * this.ay2 + d3 * this.ay2;
  97253. var rdz = d1 * this.az1 + d2 * this.az2 + d3 * this.az2;
  97254. var w1 = this.m2 / (this.m1 + this.m2);
  97255. if (this.weight >= 0) w1 = this.weight; // use given weight
  97256. var w2 = 1 - w1;
  97257. this.r1x = this.r1.x + rdx * w1;
  97258. this.r1y = this.r1.y + rdy * w1;
  97259. this.r1z = this.r1.z + rdz * w1;
  97260. this.r2x = this.r2.x - rdx * w2;
  97261. this.r2y = this.r2.y - rdy * w2;
  97262. this.r2z = this.r2.z - rdz * w2;
  97263. // build jacobians
  97264. this.t1x1 = this.r1y * this.az1 - this.r1z * this.ay1;
  97265. this.t1y1 = this.r1z * this.ax1 - this.r1x * this.az1;
  97266. this.t1z1 = this.r1x * this.ay1 - this.r1y * this.ax1;
  97267. this.t2x1 = this.r2y * this.az1 - this.r2z * this.ay1;
  97268. this.t2y1 = this.r2z * this.ax1 - this.r2x * this.az1;
  97269. this.t2z1 = this.r2x * this.ay1 - this.r2y * this.ax1;
  97270. this.l1x1 = this.ax1 * this.m1;
  97271. this.l1y1 = this.ay1 * this.m1;
  97272. this.l1z1 = this.az1 * this.m1;
  97273. this.l2x1 = this.ax1 * this.m2;
  97274. this.l2y1 = this.ay1 * this.m2;
  97275. this.l2z1 = this.az1 * this.m2;
  97276. this.a1x1 = this.t1x1 * this.i1e00 + this.t1y1 * this.i1e01 + this.t1z1 * this.i1e02;
  97277. this.a1y1 = this.t1x1 * this.i1e10 + this.t1y1 * this.i1e11 + this.t1z1 * this.i1e12;
  97278. this.a1z1 = this.t1x1 * this.i1e20 + this.t1y1 * this.i1e21 + this.t1z1 * this.i1e22;
  97279. this.a2x1 = this.t2x1 * this.i2e00 + this.t2y1 * this.i2e01 + this.t2z1 * this.i2e02;
  97280. this.a2y1 = this.t2x1 * this.i2e10 + this.t2y1 * this.i2e11 + this.t2z1 * this.i2e12;
  97281. this.a2z1 = this.t2x1 * this.i2e20 + this.t2y1 * this.i2e21 + this.t2z1 * this.i2e22;
  97282. this.t1x2 = this.r1y * this.az2 - this.r1z * this.ay2;
  97283. this.t1y2 = this.r1z * this.ax2 - this.r1x * this.az2;
  97284. this.t1z2 = this.r1x * this.ay2 - this.r1y * this.ax2;
  97285. this.t2x2 = this.r2y * this.az2 - this.r2z * this.ay2;
  97286. this.t2y2 = this.r2z * this.ax2 - this.r2x * this.az2;
  97287. this.t2z2 = this.r2x * this.ay2 - this.r2y * this.ax2;
  97288. this.l1x2 = this.ax2 * this.m1;
  97289. this.l1y2 = this.ay2 * this.m1;
  97290. this.l1z2 = this.az2 * this.m1;
  97291. this.l2x2 = this.ax2 * this.m2;
  97292. this.l2y2 = this.ay2 * this.m2;
  97293. this.l2z2 = this.az2 * this.m2;
  97294. this.a1x2 = this.t1x2 * this.i1e00 + this.t1y2 * this.i1e01 + this.t1z2 * this.i1e02;
  97295. this.a1y2 = this.t1x2 * this.i1e10 + this.t1y2 * this.i1e11 + this.t1z2 * this.i1e12;
  97296. this.a1z2 = this.t1x2 * this.i1e20 + this.t1y2 * this.i1e21 + this.t1z2 * this.i1e22;
  97297. this.a2x2 = this.t2x2 * this.i2e00 + this.t2y2 * this.i2e01 + this.t2z2 * this.i2e02;
  97298. this.a2y2 = this.t2x2 * this.i2e10 + this.t2y2 * this.i2e11 + this.t2z2 * this.i2e12;
  97299. this.a2z2 = this.t2x2 * this.i2e20 + this.t2y2 * this.i2e21 + this.t2z2 * this.i2e22;
  97300. this.t1x3 = this.r1y * this.az3 - this.r1z * this.ay3;
  97301. this.t1y3 = this.r1z * this.ax3 - this.r1x * this.az3;
  97302. this.t1z3 = this.r1x * this.ay3 - this.r1y * this.ax3;
  97303. this.t2x3 = this.r2y * this.az3 - this.r2z * this.ay3;
  97304. this.t2y3 = this.r2z * this.ax3 - this.r2x * this.az3;
  97305. this.t2z3 = this.r2x * this.ay3 - this.r2y * this.ax3;
  97306. this.l1x3 = this.ax3 * this.m1;
  97307. this.l1y3 = this.ay3 * this.m1;
  97308. this.l1z3 = this.az3 * this.m1;
  97309. this.l2x3 = this.ax3 * this.m2;
  97310. this.l2y3 = this.ay3 * this.m2;
  97311. this.l2z3 = this.az3 * this.m2;
  97312. this.a1x3 = this.t1x3 * this.i1e00 + this.t1y3 * this.i1e01 + this.t1z3 * this.i1e02;
  97313. this.a1y3 = this.t1x3 * this.i1e10 + this.t1y3 * this.i1e11 + this.t1z3 * this.i1e12;
  97314. this.a1z3 = this.t1x3 * this.i1e20 + this.t1y3 * this.i1e21 + this.t1z3 * this.i1e22;
  97315. this.a2x3 = this.t2x3 * this.i2e00 + this.t2y3 * this.i2e01 + this.t2z3 * this.i2e02;
  97316. this.a2y3 = this.t2x3 * this.i2e10 + this.t2y3 * this.i2e11 + this.t2z3 * this.i2e12;
  97317. this.a2z3 = this.t2x3 * this.i2e20 + this.t2y3 * this.i2e21 + this.t2z3 * this.i2e22;
  97318. // build an impulse matrix
  97319. var m12 = this.m1 + this.m2;
  97320. this.k00 = (this.ax1 * this.ax1 + this.ay1 * this.ay1 + this.az1 * this.az1) * m12;
  97321. this.k01 = (this.ax1 * this.ax2 + this.ay1 * this.ay2 + this.az1 * this.az2) * m12;
  97322. this.k02 = (this.ax1 * this.ax3 + this.ay1 * this.ay3 + this.az1 * this.az3) * m12;
  97323. this.k10 = (this.ax2 * this.ax1 + this.ay2 * this.ay1 + this.az2 * this.az1) * m12;
  97324. this.k11 = (this.ax2 * this.ax2 + this.ay2 * this.ay2 + this.az2 * this.az2) * m12;
  97325. this.k12 = (this.ax2 * this.ax3 + this.ay2 * this.ay3 + this.az2 * this.az3) * m12;
  97326. this.k20 = (this.ax3 * this.ax1 + this.ay3 * this.ay1 + this.az3 * this.az1) * m12;
  97327. this.k21 = (this.ax3 * this.ax2 + this.ay3 * this.ay2 + this.az3 * this.az2) * m12;
  97328. this.k22 = (this.ax3 * this.ax3 + this.ay3 * this.ay3 + this.az3 * this.az3) * m12;
  97329. this.k00 += this.t1x1 * this.a1x1 + this.t1y1 * this.a1y1 + this.t1z1 * this.a1z1;
  97330. this.k01 += this.t1x1 * this.a1x2 + this.t1y1 * this.a1y2 + this.t1z1 * this.a1z2;
  97331. this.k02 += this.t1x1 * this.a1x3 + this.t1y1 * this.a1y3 + this.t1z1 * this.a1z3;
  97332. this.k10 += this.t1x2 * this.a1x1 + this.t1y2 * this.a1y1 + this.t1z2 * this.a1z1;
  97333. this.k11 += this.t1x2 * this.a1x2 + this.t1y2 * this.a1y2 + this.t1z2 * this.a1z2;
  97334. this.k12 += this.t1x2 * this.a1x3 + this.t1y2 * this.a1y3 + this.t1z2 * this.a1z3;
  97335. this.k20 += this.t1x3 * this.a1x1 + this.t1y3 * this.a1y1 + this.t1z3 * this.a1z1;
  97336. this.k21 += this.t1x3 * this.a1x2 + this.t1y3 * this.a1y2 + this.t1z3 * this.a1z2;
  97337. this.k22 += this.t1x3 * this.a1x3 + this.t1y3 * this.a1y3 + this.t1z3 * this.a1z3;
  97338. this.k00 += this.t2x1 * this.a2x1 + this.t2y1 * this.a2y1 + this.t2z1 * this.a2z1;
  97339. this.k01 += this.t2x1 * this.a2x2 + this.t2y1 * this.a2y2 + this.t2z1 * this.a2z2;
  97340. this.k02 += this.t2x1 * this.a2x3 + this.t2y1 * this.a2y3 + this.t2z1 * this.a2z3;
  97341. this.k10 += this.t2x2 * this.a2x1 + this.t2y2 * this.a2y1 + this.t2z2 * this.a2z1;
  97342. this.k11 += this.t2x2 * this.a2x2 + this.t2y2 * this.a2y2 + this.t2z2 * this.a2z2;
  97343. this.k12 += this.t2x2 * this.a2x3 + this.t2y2 * this.a2y3 + this.t2z2 * this.a2z3;
  97344. this.k20 += this.t2x3 * this.a2x1 + this.t2y3 * this.a2y1 + this.t2z3 * this.a2z1;
  97345. this.k21 += this.t2x3 * this.a2x2 + this.t2y3 * this.a2y2 + this.t2z3 * this.a2z2;
  97346. this.k22 += this.t2x3 * this.a2x3 + this.t2y3 * this.a2y3 + this.t2z3 * this.a2z3;
  97347. this.kv00 = this.k00;
  97348. this.kv11 = this.k11;
  97349. this.kv22 = this.k22;
  97350. this.dv00 = 1 / this.kv00;
  97351. this.dv11 = 1 / this.kv11;
  97352. this.dv22 = 1 / this.kv22;
  97353. if (enableSpring1 && this.limitState1 != 2) {
  97354. var omega = 6.2831853 * frequency1;
  97355. var k = omega * omega * timeStep;
  97356. var dmp = invTimeStep / (k + 2 * this.limitMotor1.dampingRatio * omega);
  97357. this.cfm1 = this.kv00 * dmp;
  97358. this.limitVelocity1 *= k * dmp;
  97359. } else {
  97360. this.cfm1 = 0;
  97361. this.limitVelocity1 *= invTimeStep * 0.05;
  97362. }
  97363. if (enableSpring2 && this.limitState2 != 2) {
  97364. omega = 6.2831853 * frequency2;
  97365. k = omega * omega * timeStep;
  97366. dmp = invTimeStep / (k + 2 * this.limitMotor2.dampingRatio * omega);
  97367. this.cfm2 = this.kv11 * dmp;
  97368. this.limitVelocity2 *= k * dmp;
  97369. } else {
  97370. this.cfm2 = 0;
  97371. this.limitVelocity2 *= invTimeStep * 0.05;
  97372. }
  97373. if (enableSpring3 && this.limitState3 != 2) {
  97374. omega = 6.2831853 * frequency3;
  97375. k = omega * omega * timeStep;
  97376. dmp = invTimeStep / (k + 2 * this.limitMotor3.dampingRatio * omega);
  97377. this.cfm3 = this.kv22 * dmp;
  97378. this.limitVelocity3 *= k * dmp;
  97379. } else {
  97380. this.cfm3 = 0;
  97381. this.limitVelocity3 *= invTimeStep * 0.05;
  97382. }
  97383. this.k00 += this.cfm1;
  97384. this.k11 += this.cfm2;
  97385. this.k22 += this.cfm3;
  97386. var inv = 1 / (
  97387. this.k00 * (this.k11 * this.k22 - this.k21 * this.k12) +
  97388. this.k10 * (this.k21 * this.k02 - this.k01 * this.k22) +
  97389. this.k20 * (this.k01 * this.k12 - this.k11 * this.k02)
  97390. );
  97391. this.d00 = (this.k11 * this.k22 - this.k12 * this.k21) * inv;
  97392. this.d01 = (this.k02 * this.k21 - this.k01 * this.k22) * inv;
  97393. this.d02 = (this.k01 * this.k12 - this.k02 * this.k11) * inv;
  97394. this.d10 = (this.k12 * this.k20 - this.k10 * this.k22) * inv;
  97395. this.d11 = (this.k00 * this.k22 - this.k02 * this.k20) * inv;
  97396. this.d12 = (this.k02 * this.k10 - this.k00 * this.k12) * inv;
  97397. this.d20 = (this.k10 * this.k21 - this.k11 * this.k20) * inv;
  97398. this.d21 = (this.k01 * this.k20 - this.k00 * this.k21) * inv;
  97399. this.d22 = (this.k00 * this.k11 - this.k01 * this.k10) * inv;
  97400. // warm starting
  97401. var totalImpulse1 = this.limitImpulse1 + this.motorImpulse1;
  97402. var totalImpulse2 = this.limitImpulse2 + this.motorImpulse2;
  97403. var totalImpulse3 = this.limitImpulse3 + this.motorImpulse3;
  97404. this.l1.x += totalImpulse1 * this.l1x1 + totalImpulse2 * this.l1x2 + totalImpulse3 * this.l1x3;
  97405. this.l1.y += totalImpulse1 * this.l1y1 + totalImpulse2 * this.l1y2 + totalImpulse3 * this.l1y3;
  97406. this.l1.z += totalImpulse1 * this.l1z1 + totalImpulse2 * this.l1z2 + totalImpulse3 * this.l1z3;
  97407. this.a1.x += totalImpulse1 * this.a1x1 + totalImpulse2 * this.a1x2 + totalImpulse3 * this.a1x3;
  97408. this.a1.y += totalImpulse1 * this.a1y1 + totalImpulse2 * this.a1y2 + totalImpulse3 * this.a1y3;
  97409. this.a1.z += totalImpulse1 * this.a1z1 + totalImpulse2 * this.a1z2 + totalImpulse3 * this.a1z3;
  97410. this.l2.x -= totalImpulse1 * this.l2x1 + totalImpulse2 * this.l2x2 + totalImpulse3 * this.l2x3;
  97411. this.l2.y -= totalImpulse1 * this.l2y1 + totalImpulse2 * this.l2y2 + totalImpulse3 * this.l2y3;
  97412. this.l2.z -= totalImpulse1 * this.l2z1 + totalImpulse2 * this.l2z2 + totalImpulse3 * this.l2z3;
  97413. this.a2.x -= totalImpulse1 * this.a2x1 + totalImpulse2 * this.a2x2 + totalImpulse3 * this.a2x3;
  97414. this.a2.y -= totalImpulse1 * this.a2y1 + totalImpulse2 * this.a2y2 + totalImpulse3 * this.a2y3;
  97415. this.a2.z -= totalImpulse1 * this.a2z1 + totalImpulse2 * this.a2z2 + totalImpulse3 * this.a2z3;
  97416. },
  97417. solve: function () {
  97418. 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;
  97419. 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;
  97420. 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;
  97421. var rvn1 = rvx * this.ax1 + rvy * this.ay1 + rvz * this.az1;
  97422. var rvn2 = rvx * this.ax2 + rvy * this.ay2 + rvz * this.az2;
  97423. var rvn3 = rvx * this.ax3 + rvy * this.ay3 + rvz * this.az3;
  97424. var oldMotorImpulse1 = this.motorImpulse1;
  97425. var oldMotorImpulse2 = this.motorImpulse2;
  97426. var oldMotorImpulse3 = this.motorImpulse3;
  97427. var dMotorImpulse1 = 0;
  97428. var dMotorImpulse2 = 0;
  97429. var dMotorImpulse3 = 0;
  97430. if (this.enableMotor1) {
  97431. dMotorImpulse1 = (rvn1 - this.motorSpeed1) * this.dv00;
  97432. this.motorImpulse1 += dMotorImpulse1;
  97433. if (this.motorImpulse1 > this.maxMotorImpulse1) { // clamp motor impulse
  97434. this.motorImpulse1 = this.maxMotorImpulse1;
  97435. } else if (this.motorImpulse1 < -this.maxMotorImpulse1) {
  97436. this.motorImpulse1 = -this.maxMotorImpulse1;
  97437. }
  97438. dMotorImpulse1 = this.motorImpulse1 - oldMotorImpulse1;
  97439. }
  97440. if (this.enableMotor2) {
  97441. dMotorImpulse2 = (rvn2 - this.motorSpeed2) * this.dv11;
  97442. this.motorImpulse2 += dMotorImpulse2;
  97443. if (this.motorImpulse2 > this.maxMotorImpulse2) { // clamp motor impulse
  97444. this.motorImpulse2 = this.maxMotorImpulse2;
  97445. } else if (this.motorImpulse2 < -this.maxMotorImpulse2) {
  97446. this.motorImpulse2 = -this.maxMotorImpulse2;
  97447. }
  97448. dMotorImpulse2 = this.motorImpulse2 - oldMotorImpulse2;
  97449. }
  97450. if (this.enableMotor3) {
  97451. dMotorImpulse3 = (rvn3 - this.motorSpeed3) * this.dv22;
  97452. this.motorImpulse3 += dMotorImpulse3;
  97453. if (this.motorImpulse3 > this.maxMotorImpulse3) { // clamp motor impulse
  97454. this.motorImpulse3 = this.maxMotorImpulse3;
  97455. } else if (this.motorImpulse3 < -this.maxMotorImpulse3) {
  97456. this.motorImpulse3 = -this.maxMotorImpulse3;
  97457. }
  97458. dMotorImpulse3 = this.motorImpulse3 - oldMotorImpulse3;
  97459. }
  97460. // apply motor impulse to relative velocity
  97461. rvn1 += dMotorImpulse1 * this.kv00 + dMotorImpulse2 * this.k01 + dMotorImpulse3 * this.k02;
  97462. rvn2 += dMotorImpulse1 * this.k10 + dMotorImpulse2 * this.kv11 + dMotorImpulse3 * this.k12;
  97463. rvn3 += dMotorImpulse1 * this.k20 + dMotorImpulse2 * this.k21 + dMotorImpulse3 * this.kv22;
  97464. // subtract target velocity and applied impulse
  97465. rvn1 -= this.limitVelocity1 + this.limitImpulse1 * this.cfm1;
  97466. rvn2 -= this.limitVelocity2 + this.limitImpulse2 * this.cfm2;
  97467. rvn3 -= this.limitVelocity3 + this.limitImpulse3 * this.cfm3;
  97468. var oldLimitImpulse1 = this.limitImpulse1;
  97469. var oldLimitImpulse2 = this.limitImpulse2;
  97470. var oldLimitImpulse3 = this.limitImpulse3;
  97471. var dLimitImpulse1 = rvn1 * this.d00 + rvn2 * this.d01 + rvn3 * this.d02;
  97472. var dLimitImpulse2 = rvn1 * this.d10 + rvn2 * this.d11 + rvn3 * this.d12;
  97473. var dLimitImpulse3 = rvn1 * this.d20 + rvn2 * this.d21 + rvn3 * this.d22;
  97474. this.limitImpulse1 += dLimitImpulse1;
  97475. this.limitImpulse2 += dLimitImpulse2;
  97476. this.limitImpulse3 += dLimitImpulse3;
  97477. // clamp
  97478. var clampState = 0;
  97479. if (this.limitState1 == 2 || this.limitImpulse1 * this.limitState1 < 0) {
  97480. dLimitImpulse1 = -oldLimitImpulse1;
  97481. rvn2 += dLimitImpulse1 * this.k10;
  97482. rvn3 += dLimitImpulse1 * this.k20;
  97483. clampState |= 1;
  97484. }
  97485. if (this.limitState2 == 2 || this.limitImpulse2 * this.limitState2 < 0) {
  97486. dLimitImpulse2 = -oldLimitImpulse2;
  97487. rvn1 += dLimitImpulse2 * this.k01;
  97488. rvn3 += dLimitImpulse2 * this.k21;
  97489. clampState |= 2;
  97490. }
  97491. if (this.limitState3 == 2 || this.limitImpulse3 * this.limitState3 < 0) {
  97492. dLimitImpulse3 = -oldLimitImpulse3;
  97493. rvn1 += dLimitImpulse3 * this.k02;
  97494. rvn2 += dLimitImpulse3 * this.k12;
  97495. clampState |= 4;
  97496. }
  97497. // update un-clamped impulse
  97498. // TODO: isolate division
  97499. var det;
  97500. switch (clampState) {
  97501. case 1:// update 2 3
  97502. det = 1 / (this.k11 * this.k22 - this.k12 * this.k21);
  97503. dLimitImpulse2 = (this.k22 * rvn2 + -this.k12 * rvn3) * det;
  97504. dLimitImpulse3 = (-this.k21 * rvn2 + this.k11 * rvn3) * det;
  97505. break;
  97506. case 2:// update 1 3
  97507. det = 1 / (this.k00 * this.k22 - this.k02 * this.k20);
  97508. dLimitImpulse1 = (this.k22 * rvn1 + -this.k02 * rvn3) * det;
  97509. dLimitImpulse3 = (-this.k20 * rvn1 + this.k00 * rvn3) * det;
  97510. break;
  97511. case 3:// update 3
  97512. dLimitImpulse3 = rvn3 / this.k22;
  97513. break;
  97514. case 4:// update 1 2
  97515. det = 1 / (this.k00 * this.k11 - this.k01 * this.k10);
  97516. dLimitImpulse1 = (this.k11 * rvn1 + -this.k01 * rvn2) * det;
  97517. dLimitImpulse2 = (-this.k10 * rvn1 + this.k00 * rvn2) * det;
  97518. break;
  97519. case 5:// update 2
  97520. dLimitImpulse2 = rvn2 / this.k11;
  97521. break;
  97522. case 6:// update 1
  97523. dLimitImpulse1 = rvn1 / this.k00;
  97524. break;
  97525. }
  97526. this.limitImpulse1 = oldLimitImpulse1 + dLimitImpulse1;
  97527. this.limitImpulse2 = oldLimitImpulse2 + dLimitImpulse2;
  97528. this.limitImpulse3 = oldLimitImpulse3 + dLimitImpulse3;
  97529. var dImpulse1 = dMotorImpulse1 + dLimitImpulse1;
  97530. var dImpulse2 = dMotorImpulse2 + dLimitImpulse2;
  97531. var dImpulse3 = dMotorImpulse3 + dLimitImpulse3;
  97532. // apply impulse
  97533. this.l1.x += dImpulse1 * this.l1x1 + dImpulse2 * this.l1x2 + dImpulse3 * this.l1x3;
  97534. this.l1.y += dImpulse1 * this.l1y1 + dImpulse2 * this.l1y2 + dImpulse3 * this.l1y3;
  97535. this.l1.z += dImpulse1 * this.l1z1 + dImpulse2 * this.l1z2 + dImpulse3 * this.l1z3;
  97536. this.a1.x += dImpulse1 * this.a1x1 + dImpulse2 * this.a1x2 + dImpulse3 * this.a1x3;
  97537. this.a1.y += dImpulse1 * this.a1y1 + dImpulse2 * this.a1y2 + dImpulse3 * this.a1y3;
  97538. this.a1.z += dImpulse1 * this.a1z1 + dImpulse2 * this.a1z2 + dImpulse3 * this.a1z3;
  97539. this.l2.x -= dImpulse1 * this.l2x1 + dImpulse2 * this.l2x2 + dImpulse3 * this.l2x3;
  97540. this.l2.y -= dImpulse1 * this.l2y1 + dImpulse2 * this.l2y2 + dImpulse3 * this.l2y3;
  97541. this.l2.z -= dImpulse1 * this.l2z1 + dImpulse2 * this.l2z2 + dImpulse3 * this.l2z3;
  97542. this.a2.x -= dImpulse1 * this.a2x1 + dImpulse2 * this.a2x2 + dImpulse3 * this.a2x3;
  97543. this.a2.y -= dImpulse1 * this.a2y1 + dImpulse2 * this.a2y2 + dImpulse3 * this.a2y3;
  97544. this.a2.z -= dImpulse1 * this.a2z1 + dImpulse2 * this.a2z2 + dImpulse3 * this.a2z3;
  97545. }
  97546. }
  97547. /**
  97548. * A translational constraint for various joints.
  97549. * @author saharan
  97550. */
  97551. OIMO.TranslationalConstraint = function (joint, limitMotor) {
  97552. this.cfm = NaN;
  97553. this.m1 = NaN;
  97554. this.m2 = NaN;
  97555. this.i1e00 = NaN;
  97556. this.i1e01 = NaN;
  97557. this.i1e02 = NaN;
  97558. this.i1e10 = NaN;
  97559. this.i1e11 = NaN;
  97560. this.i1e12 = NaN;
  97561. this.i1e20 = NaN;
  97562. this.i1e21 = NaN;
  97563. this.i1e22 = NaN;
  97564. this.i2e00 = NaN;
  97565. this.i2e01 = NaN;
  97566. this.i2e02 = NaN;
  97567. this.i2e10 = NaN;
  97568. this.i2e11 = NaN;
  97569. this.i2e12 = NaN;
  97570. this.i2e20 = NaN;
  97571. this.i2e21 = NaN;
  97572. this.i2e22 = NaN;
  97573. this.motorDenom = NaN;
  97574. this.invMotorDenom = NaN;
  97575. this.invDenom = NaN;
  97576. this.ax = NaN;
  97577. this.ay = NaN;
  97578. this.az = NaN;
  97579. this.r1x = NaN;
  97580. this.r1y = NaN;
  97581. this.r1z = NaN;
  97582. this.r2x = NaN;
  97583. this.r2y = NaN;
  97584. this.r2z = NaN;
  97585. this.t1x = NaN;
  97586. this.t1y = NaN;
  97587. this.t1z = NaN;
  97588. this.t2x = NaN;
  97589. this.t2y = NaN;
  97590. this.t2z = NaN;
  97591. this.l1x = NaN;
  97592. this.l1y = NaN;
  97593. this.l1z = NaN;
  97594. this.l2x = NaN;
  97595. this.l2y = NaN;
  97596. this.l2z = NaN;
  97597. this.a1x = NaN;
  97598. this.a1y = NaN;
  97599. this.a1z = NaN;
  97600. this.a2x = NaN;
  97601. this.a2y = NaN;
  97602. this.a2z = NaN;
  97603. this.lowerLimit = NaN;
  97604. this.upperLimit = NaN;
  97605. this.limitVelocity = NaN;
  97606. this.limitState = 0; // -1: at lower, 0: locked, 1: at upper, 2: free
  97607. this.enableMotor = false;
  97608. this.motorSpeed = NaN;
  97609. this.maxMotorForce = NaN;
  97610. this.maxMotorImpulse = NaN;
  97611. this.limitMotor = limitMotor;
  97612. this.b1 = joint.body1;
  97613. this.b2 = joint.body2;
  97614. this.p1 = joint.anchorPoint1;
  97615. this.p2 = joint.anchorPoint2;
  97616. this.r1 = joint.relativeAnchorPoint1;
  97617. this.r2 = joint.relativeAnchorPoint2;
  97618. this.l1 = this.b1.linearVelocity;
  97619. this.l2 = this.b2.linearVelocity;
  97620. this.a1 = this.b1.angularVelocity;
  97621. this.a2 = this.b2.angularVelocity;
  97622. this.i1 = this.b1.inverseInertia;
  97623. this.i2 = this.b2.inverseInertia;
  97624. this.limitImpulse = 0;
  97625. this.motorImpulse = 0;
  97626. }
  97627. OIMO.TranslationalConstraint.prototype = {
  97628. constructor: OIMO.TranslationalConstraint,
  97629. preSolve: function (timeStep, invTimeStep) {
  97630. this.ax = this.limitMotor.axis.x;
  97631. this.ay = this.limitMotor.axis.y;
  97632. this.az = this.limitMotor.axis.z;
  97633. this.lowerLimit = this.limitMotor.lowerLimit;
  97634. this.upperLimit = this.limitMotor.upperLimit;
  97635. this.motorSpeed = this.limitMotor.motorSpeed;
  97636. this.maxMotorForce = this.limitMotor.maxMotorForce;
  97637. this.enableMotor = this.maxMotorForce > 0;
  97638. this.m1 = this.b1.inverseMass;
  97639. this.m2 = this.b2.inverseMass;
  97640. var ti1 = this.i1.elements;
  97641. var ti2 = this.i2.elements;
  97642. this.i1e00 = ti1[0];
  97643. this.i1e01 = ti1[1];
  97644. this.i1e02 = ti1[2];
  97645. this.i1e10 = ti1[3];
  97646. this.i1e11 = ti1[4];
  97647. this.i1e12 = ti1[5];
  97648. this.i1e20 = ti1[6];
  97649. this.i1e21 = ti1[7];
  97650. this.i1e22 = ti1[8];
  97651. this.i2e00 = ti2[0];
  97652. this.i2e01 = ti2[1];
  97653. this.i2e02 = ti2[2];
  97654. this.i2e10 = ti2[3];
  97655. this.i2e11 = ti2[4];
  97656. this.i2e12 = ti2[5];
  97657. this.i2e20 = ti2[6];
  97658. this.i2e21 = ti2[7];
  97659. this.i2e22 = ti2[8];
  97660. var dx = this.p2.x - this.p1.x;
  97661. var dy = this.p2.y - this.p1.y;
  97662. var dz = this.p2.z - this.p1.z;
  97663. var d = dx * this.ax + dy * this.ay + dz * this.az;
  97664. var frequency = this.limitMotor.frequency;
  97665. var enableSpring = frequency > 0;
  97666. var enableLimit = this.lowerLimit <= this.upperLimit;
  97667. if (enableSpring && d > 20 || d < -20) {
  97668. enableSpring = false;
  97669. }
  97670. if (enableLimit) {
  97671. if (this.lowerLimit == this.upperLimit) {
  97672. if (this.limitState != 0) {
  97673. this.limitState = 0;
  97674. this.limitImpulse = 0;
  97675. }
  97676. this.limitVelocity = this.lowerLimit - d;
  97677. if (!enableSpring) d = this.lowerLimit;
  97678. } else if (d < this.lowerLimit) {
  97679. if (this.limitState != -1) {
  97680. this.limitState = -1;
  97681. this.limitImpulse = 0;
  97682. }
  97683. this.limitVelocity = this.lowerLimit - d;
  97684. if (!enableSpring) d = this.lowerLimit;
  97685. } else if (d > this.upperLimit) {
  97686. if (this.limitState != 1) {
  97687. this.limitState = 1;
  97688. this.limitImpulse = 0;
  97689. }
  97690. this.limitVelocity = this.upperLimit - d;
  97691. if (!enableSpring) d = this.upperLimit;
  97692. } else {
  97693. this.limitState = 2;
  97694. this.limitImpulse = 0;
  97695. this.limitVelocity = 0;
  97696. }
  97697. if (!enableSpring) {
  97698. if (this.limitVelocity > 0.005) this.limitVelocity -= 0.005;
  97699. else if (this.limitVelocity < -0.005) this.limitVelocity += 0.005;
  97700. else this.limitVelocity = 0;
  97701. }
  97702. } else {
  97703. this.limitState = 2;
  97704. this.limitImpulse = 0;
  97705. }
  97706. if (this.enableMotor && (this.limitState != 0 || enableSpring)) {
  97707. this.maxMotorImpulse = this.maxMotorForce * timeStep;
  97708. } else {
  97709. this.motorImpulse = 0;
  97710. this.maxMotorImpulse = 0;
  97711. }
  97712. var rdx = d * this.ax;
  97713. var rdy = d * this.ay;
  97714. var rdz = d * this.az;
  97715. var w1 = this.m1 / (this.m1 + this.m2);
  97716. var w2 = 1 - w1;
  97717. this.r1x = this.r1.x + rdx * w1;
  97718. this.r1y = this.r1.y + rdy * w1;
  97719. this.r1z = this.r1.z + rdz * w1;
  97720. this.r2x = this.r2.x - rdx * w2;
  97721. this.r2y = this.r2.y - rdy * w2;
  97722. this.r2z = this.r2.z - rdz * w2;
  97723. this.t1x = this.r1y * this.az - this.r1z * this.ay;
  97724. this.t1y = this.r1z * this.ax - this.r1x * this.az;
  97725. this.t1z = this.r1x * this.ay - this.r1y * this.ax;
  97726. this.t2x = this.r2y * this.az - this.r2z * this.ay;
  97727. this.t2y = this.r2z * this.ax - this.r2x * this.az;
  97728. this.t2z = this.r2x * this.ay - this.r2y * this.ax;
  97729. this.l1x = this.ax * this.m1;
  97730. this.l1y = this.ay * this.m1;
  97731. this.l1z = this.az * this.m1;
  97732. this.l2x = this.ax * this.m2;
  97733. this.l2y = this.ay * this.m2;
  97734. this.l2z = this.az * this.m2;
  97735. this.a1x = this.t1x * this.i1e00 + this.t1y * this.i1e01 + this.t1z * this.i1e02;
  97736. this.a1y = this.t1x * this.i1e10 + this.t1y * this.i1e11 + this.t1z * this.i1e12;
  97737. this.a1z = this.t1x * this.i1e20 + this.t1y * this.i1e21 + this.t1z * this.i1e22;
  97738. this.a2x = this.t2x * this.i2e00 + this.t2y * this.i2e01 + this.t2z * this.i2e02;
  97739. this.a2y = this.t2x * this.i2e10 + this.t2y * this.i2e11 + this.t2z * this.i2e12;
  97740. this.a2z = this.t2x * this.i2e20 + this.t2y * this.i2e21 + this.t2z * this.i2e22;
  97741. this.motorDenom =
  97742. this.m1 + this.m2 +
  97743. this.ax * (this.a1y * this.r1z - this.a1z * this.r1y + this.a2y * this.r2z - this.a2z * this.r2y) +
  97744. this.ay * (this.a1z * this.r1x - this.a1x * this.r1z + this.a2z * this.r2x - this.a2x * this.r2z) +
  97745. this.az * (this.a1x * this.r1y - this.a1y * this.r1x + this.a2x * this.r2y - this.a2y * this.r2x);
  97746. this.invMotorDenom = 1 / this.motorDenom;
  97747. if (enableSpring && this.limitState != 2) {
  97748. var omega = 6.2831853 * frequency;
  97749. var k = omega * omega * timeStep;
  97750. var dmp = invTimeStep / (k + 2 * this.limitMotor.dampingRatio * omega);
  97751. this.cfm = this.motorDenom * dmp;
  97752. this.limitVelocity *= k * dmp;
  97753. } else {
  97754. this.cfm = 0;
  97755. this.limitVelocity *= invTimeStep * 0.05;
  97756. }
  97757. this.invDenom = 1 / (this.motorDenom + this.cfm);
  97758. var totalImpulse = this.limitImpulse + this.motorImpulse;
  97759. this.l1.x += totalImpulse * this.l1x;
  97760. this.l1.y += totalImpulse * this.l1y;
  97761. this.l1.z += totalImpulse * this.l1z;
  97762. this.a1.x += totalImpulse * this.a1x;
  97763. this.a1.y += totalImpulse * this.a1y;
  97764. this.a1.z += totalImpulse * this.a1z;
  97765. this.l2.x -= totalImpulse * this.l2x;
  97766. this.l2.y -= totalImpulse * this.l2y;
  97767. this.l2.z -= totalImpulse * this.l2z;
  97768. this.a2.x -= totalImpulse * this.a2x;
  97769. this.a2.y -= totalImpulse * this.a2y;
  97770. this.a2.z -= totalImpulse * this.a2z;
  97771. },
  97772. solve: function () {
  97773. var rvn =
  97774. this.ax * (this.l2.x - this.l1.x) + this.ay * (this.l2.y - this.l1.y) + this.az * (this.l2.z - this.l1.z) +
  97775. 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;
  97776. // motor part
  97777. var newMotorImpulse;
  97778. if (this.enableMotor) {
  97779. newMotorImpulse = (rvn - this.motorSpeed) * this.invMotorDenom;
  97780. var oldMotorImpulse = this.motorImpulse;
  97781. this.motorImpulse += newMotorImpulse;
  97782. if (this.motorImpulse > this.maxMotorImpulse) this.motorImpulse = this.maxMotorImpulse;
  97783. else if (this.motorImpulse < -this.maxMotorImpulse) this.motorImpulse = -this.maxMotorImpulse;
  97784. newMotorImpulse = this.motorImpulse - oldMotorImpulse;
  97785. rvn -= newMotorImpulse * this.motorDenom;
  97786. } else newMotorImpulse = 0;
  97787. // limit part
  97788. var newLimitImpulse;
  97789. if (this.limitState != 2) {
  97790. newLimitImpulse = (rvn - this.limitVelocity - this.limitImpulse * this.cfm) * this.invDenom;
  97791. var oldLimitImpulse = this.limitImpulse;
  97792. this.limitImpulse += newLimitImpulse;
  97793. if (this.limitImpulse * this.limitState < 0) this.limitImpulse = 0;
  97794. newLimitImpulse = this.limitImpulse - oldLimitImpulse;
  97795. } else newLimitImpulse = 0;
  97796. var totalImpulse = newLimitImpulse + newMotorImpulse;
  97797. this.l1.x += totalImpulse * this.l1x;
  97798. this.l1.y += totalImpulse * this.l1y;
  97799. this.l1.z += totalImpulse * this.l1z;
  97800. this.a1.x += totalImpulse * this.a1x;
  97801. this.a1.y += totalImpulse * this.a1y;
  97802. this.a1.z += totalImpulse * this.a1z;
  97803. this.l2.x -= totalImpulse * this.l2x;
  97804. this.l2.y -= totalImpulse * this.l2y;
  97805. this.l2.z -= totalImpulse * this.l2z;
  97806. this.a2.x -= totalImpulse * this.a2x;
  97807. this.a2.y -= totalImpulse * this.a2y;
  97808. this.a2.z -= totalImpulse * this.a2z;
  97809. }
  97810. }
  97811. /**
  97812. * A contact is a pair of shapes whose axis-aligned bounding boxes are overlapping.
  97813. * @author saharan
  97814. */
  97815. OIMO.Contact = function () {
  97816. // The first shape.
  97817. this.shape1 = null;
  97818. // The second shape.
  97819. this.shape2 = null;
  97820. // The first rigid body.
  97821. this.body1 = null;
  97822. // The second rigid body.
  97823. this.body2 = null;
  97824. // The previous contact in the world.
  97825. this.prev = null;
  97826. // The next contact in the world.
  97827. this.next = null;
  97828. // Internal
  97829. this.persisting = false;
  97830. // Whether both the rigid bodies are sleeping or not.
  97831. this.sleeping = false;
  97832. // The collision detector between two shapes.
  97833. this.detector = null;
  97834. // The contact constraint of the contact.
  97835. this.constraint = null;
  97836. // Whether the shapes are touching or not.
  97837. this.touching = false;
  97838. this.b1Link = new OIMO.ContactLink(this);
  97839. this.b2Link = new OIMO.ContactLink(this);
  97840. this.s1Link = new OIMO.ContactLink(this);
  97841. this.s2Link = new OIMO.ContactLink(this);
  97842. // The contact manifold of the contact.
  97843. this.manifold = new OIMO.ContactManifold();
  97844. this.buffer = [];// vector 4
  97845. this.buffer.length = 4;
  97846. this.buffer[0] = new OIMO.ImpulseDataBuffer();
  97847. this.buffer[1] = new OIMO.ImpulseDataBuffer();
  97848. this.buffer[2] = new OIMO.ImpulseDataBuffer();
  97849. this.buffer[3] = new OIMO.ImpulseDataBuffer();
  97850. this.points = this.manifold.points;
  97851. this.constraint = new OIMO.ContactConstraint(this.manifold);
  97852. }
  97853. OIMO.Contact.prototype = {
  97854. constructor: OIMO.Contact,
  97855. mixRestitution: function (restitution1, restitution2) {
  97856. return OIMO.sqrt(restitution1 * restitution2);
  97857. },
  97858. mixFriction: function (friction1, friction2) {
  97859. return OIMO.sqrt(friction1 * friction2);
  97860. },
  97861. /**
  97862. * Update the contact manifold.
  97863. */
  97864. updateManifold: function () {
  97865. this.constraint.restitution = this.mixRestitution(this.shape1.restitution, this.shape2.restitution);
  97866. this.constraint.friction = this.mixFriction(this.shape1.friction, this.shape2.friction);
  97867. var numBuffers = this.manifold.numPoints;
  97868. var i = numBuffers;
  97869. while (i--) {
  97870. //for(var i=0;i<numBuffers;i++){
  97871. var b = this.buffer[i];
  97872. var p = this.points[i];
  97873. b.lp1X = p.localPoint1.x;
  97874. b.lp1Y = p.localPoint1.y;
  97875. b.lp1Z = p.localPoint1.z;
  97876. b.lp2X = p.localPoint2.x;
  97877. b.lp2Y = p.localPoint2.y;
  97878. b.lp2Z = p.localPoint2.z;
  97879. b.impulse = p.normalImpulse;
  97880. }
  97881. this.manifold.numPoints = 0;
  97882. this.detector.detectCollision(this.shape1, this.shape2, this.manifold);
  97883. var num = this.manifold.numPoints;
  97884. if (num == 0) {
  97885. this.touching = false;
  97886. return;
  97887. }
  97888. this.touching = true;
  97889. i = num;
  97890. while (i--) {
  97891. //for(i=0; i<num; i++){
  97892. p = this.points[i];
  97893. var lp1x = p.localPoint1.x;
  97894. var lp1y = p.localPoint1.y;
  97895. var lp1z = p.localPoint1.z;
  97896. var lp2x = p.localPoint2.x;
  97897. var lp2y = p.localPoint2.y;
  97898. var lp2z = p.localPoint2.z;
  97899. var index = -1;
  97900. var minDistance = 0.0004;
  97901. var j = numBuffers;
  97902. while (j--) {
  97903. //for(var j=0;j<numBuffers;j++){
  97904. b = this.buffer[j];
  97905. var dx = b.lp1X - lp1x;
  97906. var dy = b.lp1Y - lp1y;
  97907. var dz = b.lp1Z - lp1z;
  97908. var distance1 = dx * dx + dy * dy + dz * dz;
  97909. dx = b.lp2X - lp2x;
  97910. dy = b.lp2Y - lp2y;
  97911. dz = b.lp2Z - lp2z;
  97912. var distance2 = dx * dx + dy * dy + dz * dz;
  97913. if (distance1 < distance2) {
  97914. if (distance1 < minDistance) {
  97915. minDistance = distance1;
  97916. index = j;
  97917. }
  97918. } else {
  97919. if (distance2 < minDistance) {
  97920. minDistance = distance2;
  97921. index = j;
  97922. }
  97923. }
  97924. }
  97925. if (index != -1) {
  97926. var tmp = this.buffer[index];
  97927. this.buffer[index] = this.buffer[--numBuffers];
  97928. this.buffer[numBuffers] = tmp;
  97929. p.normalImpulse = tmp.impulse;
  97930. p.warmStarted = true;
  97931. } else {
  97932. p.normalImpulse = 0;
  97933. p.warmStarted = false;
  97934. }
  97935. }
  97936. },
  97937. /**
  97938. * Attach the contact to the shapes.
  97939. * @param shape1
  97940. * @param shape2
  97941. */
  97942. attach: function (shape1, shape2) {
  97943. this.shape1 = shape1;
  97944. this.shape2 = shape2;
  97945. this.body1 = shape1.parent;
  97946. this.body2 = shape2.parent;
  97947. this.manifold.body1 = this.body1;
  97948. this.manifold.body2 = this.body2;
  97949. this.constraint.body1 = this.body1;
  97950. this.constraint.body2 = this.body2;
  97951. this.constraint.attach();
  97952. this.s1Link.shape = shape2;
  97953. this.s1Link.body = this.body2;
  97954. this.s2Link.shape = shape1;
  97955. this.s2Link.body = this.body1;
  97956. if (shape1.contactLink != null) (this.s1Link.next = shape1.contactLink).prev = this.s1Link;
  97957. else this.s1Link.next = null;
  97958. shape1.contactLink = this.s1Link;
  97959. shape1.numContacts++;
  97960. if (shape2.contactLink != null) (this.s2Link.next = shape2.contactLink).prev = this.s2Link;
  97961. else this.s2Link.next = null;
  97962. shape2.contactLink = this.s2Link;
  97963. shape2.numContacts++;
  97964. this.b1Link.shape = shape2;
  97965. this.b1Link.body = this.body2;
  97966. this.b2Link.shape = shape1;
  97967. this.b2Link.body = this.body1;
  97968. if (this.body1.contactLink != null) (this.b1Link.next = this.body1.contactLink).prev = this.b1Link;
  97969. else this.b1Link.next = null;
  97970. this.body1.contactLink = this.b1Link;
  97971. this.body1.numContacts++;
  97972. if (this.body2.contactLink != null) (this.b2Link.next = this.body2.contactLink).prev = this.b2Link;
  97973. else this.b2Link.next = null;
  97974. this.body2.contactLink = this.b2Link;
  97975. this.body2.numContacts++;
  97976. this.prev = null;
  97977. this.next = null;
  97978. this.persisting = true;
  97979. this.sleeping = this.body1.sleeping && this.body2.sleeping;
  97980. this.manifold.numPoints = 0;
  97981. },
  97982. /**
  97983. * Detach the contact from the shapes.
  97984. */
  97985. detach: function () {
  97986. var prev = this.s1Link.prev;
  97987. var next = this.s1Link.next;
  97988. if (prev !== null) prev.next = next;
  97989. if (next !== null) next.prev = prev;
  97990. if (this.shape1.contactLink == this.s1Link) this.shape1.contactLink = next;
  97991. this.s1Link.prev = null;
  97992. this.s1Link.next = null;
  97993. this.s1Link.shape = null;
  97994. this.s1Link.body = null;
  97995. this.shape1.numContacts--;
  97996. prev = this.s2Link.prev;
  97997. next = this.s2Link.next;
  97998. if (prev !== null) prev.next = next;
  97999. if (next !== null) next.prev = prev;
  98000. if (this.shape2.contactLink == this.s2Link) this.shape2.contactLink = next;
  98001. this.s2Link.prev = null;
  98002. this.s2Link.next = null;
  98003. this.s2Link.shape = null;
  98004. this.s2Link.body = null;
  98005. this.shape2.numContacts--;
  98006. prev = this.b1Link.prev;
  98007. next = this.b1Link.next;
  98008. if (prev !== null) prev.next = next;
  98009. if (next !== null) next.prev = prev;
  98010. if (this.body1.contactLink == this.b1Link) this.body1.contactLink = next;
  98011. this.b1Link.prev = null;
  98012. this.b1Link.next = null;
  98013. this.b1Link.shape = null;
  98014. this.b1Link.body = null;
  98015. this.body1.numContacts--;
  98016. prev = this.b2Link.prev;
  98017. next = this.b2Link.next;
  98018. if (prev !== null) prev.next = next;
  98019. if (next !== null) next.prev = prev;
  98020. if (this.body2.contactLink == this.b2Link) this.body2.contactLink = next;
  98021. this.b2Link.prev = null;
  98022. this.b2Link.next = null;
  98023. this.b2Link.shape = null;
  98024. this.b2Link.body = null;
  98025. this.body2.numContacts--;
  98026. this.manifold.body1 = null;
  98027. this.manifold.body2 = null;
  98028. this.constraint.body1 = null;
  98029. this.constraint.body2 = null;
  98030. this.constraint.detach();
  98031. this.shape1 = null;
  98032. this.shape2 = null;
  98033. this.body1 = null;
  98034. this.body2 = null;
  98035. }
  98036. }
  98037. /**
  98038. * ...
  98039. * @author saharan
  98040. */
  98041. OIMO.ContactConstraint = function (manifold) {
  98042. OIMO.Constraint.call(this);
  98043. // The contact manifold of the constraint.
  98044. this.manifold = manifold;
  98045. // The coefficient of restitution of the constraint.
  98046. this.restitution = NaN;
  98047. // The coefficient of friction of the constraint.
  98048. this.friction = NaN;
  98049. this.p1 = null;
  98050. this.p2 = null;
  98051. this.lv1 = null;
  98052. this.lv2 = null;
  98053. this.av1 = null;
  98054. this.av2 = null;
  98055. this.i1 = null;
  98056. this.i2 = null;
  98057. this.ii1 = null;
  98058. this.ii2 = null;
  98059. this.m1 = NaN;
  98060. this.m2 = NaN;
  98061. this.num = 0;
  98062. this.ps = manifold.points;
  98063. this.cs = new OIMO.ContactPointDataBuffer();
  98064. this.cs.next = new OIMO.ContactPointDataBuffer();
  98065. this.cs.next.next = new OIMO.ContactPointDataBuffer();
  98066. this.cs.next.next.next = new OIMO.ContactPointDataBuffer();
  98067. }
  98068. OIMO.ContactConstraint.prototype = Object.create(OIMO.Constraint.prototype);
  98069. /**
  98070. * Attach the constraint to the bodies.
  98071. */
  98072. OIMO.ContactConstraint.prototype.attach = function () {
  98073. this.p1 = this.body1.position;
  98074. this.p2 = this.body2.position;
  98075. this.lv1 = this.body1.linearVelocity;
  98076. this.av1 = this.body1.angularVelocity;
  98077. this.lv2 = this.body2.linearVelocity;
  98078. this.av2 = this.body2.angularVelocity;
  98079. this.i1 = this.body1.inverseInertia;
  98080. this.i2 = this.body2.inverseInertia;
  98081. }
  98082. /**
  98083. * Detach the constraint from the bodies.
  98084. */
  98085. OIMO.ContactConstraint.prototype.detach = function () {
  98086. this.p1 = null;
  98087. this.p2 = null;
  98088. this.lv1 = null;
  98089. this.lv2 = null;
  98090. this.av1 = null;
  98091. this.av2 = null;
  98092. this.i1 = null;
  98093. this.i2 = null;
  98094. }
  98095. OIMO.ContactConstraint.prototype.preSolve = function (timeStep, invTimeStep) {
  98096. this.m1 = this.body1.inverseMass;
  98097. this.m2 = this.body2.inverseMass;
  98098. this.ii1 = this.i1.clone();
  98099. this.ii2 = this.i2.clone();
  98100. var ii1 = this.ii1.elements;
  98101. var ii2 = this.ii2.elements;
  98102. var p1x = this.p1.x;
  98103. var p1y = this.p1.y;
  98104. var p1z = this.p1.z;
  98105. var p2x = this.p2.x;
  98106. var p2y = this.p2.y;
  98107. var p2z = this.p2.z;
  98108. var m1m2 = this.m1 + this.m2;
  98109. this.num = this.manifold.numPoints;
  98110. var c = this.cs;
  98111. for (var i = 0; i < this.num; i++) {
  98112. var p = this.ps[i];
  98113. var tmp1X;
  98114. var tmp1Y;
  98115. var tmp1Z;
  98116. var tmp2X;
  98117. var tmp2Y;
  98118. var tmp2Z;
  98119. tmp1X = p.position.x;
  98120. tmp1Y = p.position.y;
  98121. tmp1Z = p.position.z;
  98122. var rp1X = tmp1X - p1x;
  98123. var rp1Y = tmp1Y - p1y;
  98124. var rp1Z = tmp1Z - p1z;
  98125. var rp2X = tmp1X - p2x;
  98126. var rp2Y = tmp1Y - p2y;
  98127. var rp2Z = tmp1Z - p2z;
  98128. c.rp1X = rp1X;
  98129. c.rp1Y = rp1Y;
  98130. c.rp1Z = rp1Z;
  98131. c.rp2X = rp2X;
  98132. c.rp2Y = rp2Y;
  98133. c.rp2Z = rp2Z;
  98134. c.norImp = p.normalImpulse;
  98135. c.tanImp = p.tangentImpulse;
  98136. c.binImp = p.binormalImpulse;
  98137. var norX = p.normal.x;
  98138. var norY = p.normal.y;
  98139. var norZ = p.normal.z;
  98140. var rvX = (this.lv2.x + this.av2.y * rp2Z - this.av2.z * rp2Y) - (this.lv1.x + this.av1.y * rp1Z - this.av1.z * rp1Y);
  98141. var rvY = (this.lv2.y + this.av2.z * rp2X - this.av2.x * rp2Z) - (this.lv1.y + this.av1.z * rp1X - this.av1.x * rp1Z);
  98142. var rvZ = (this.lv2.z + this.av2.x * rp2Y - this.av2.y * rp2X) - (this.lv1.z + this.av1.x * rp1Y - this.av1.y * rp1X);
  98143. var rvn = norX * rvX + norY * rvY + norZ * rvZ;
  98144. var tanX = rvX - rvn * norX;
  98145. var tanY = rvY - rvn * norY;
  98146. var tanZ = rvZ - rvn * norZ;
  98147. var len = tanX * tanX + tanY * tanY + tanZ * tanZ;
  98148. if (len > 0.04) {
  98149. len = 1 / OIMO.sqrt(len);
  98150. } else {
  98151. tanX = norY * norX - norZ * norZ;
  98152. tanY = -norZ * norY - norX * norX;
  98153. tanZ = norX * norZ + norY * norY;
  98154. len = 1 / OIMO.sqrt(tanX * tanX + tanY * tanY + tanZ * tanZ);
  98155. }
  98156. tanX *= len;
  98157. tanY *= len;
  98158. tanZ *= len;
  98159. var binX = norY * tanZ - norZ * tanY;
  98160. var binY = norZ * tanX - norX * tanZ;
  98161. var binZ = norX * tanY - norY * tanX;
  98162. c.norX = norX;
  98163. c.norY = norY;
  98164. c.norZ = norZ;
  98165. c.tanX = tanX;
  98166. c.tanY = tanY;
  98167. c.tanZ = tanZ;
  98168. c.binX = binX;
  98169. c.binY = binY;
  98170. c.binZ = binZ;
  98171. c.norU1X = norX * this.m1;
  98172. c.norU1Y = norY * this.m1;
  98173. c.norU1Z = norZ * this.m1;
  98174. c.norU2X = norX * this.m2;
  98175. c.norU2Y = norY * this.m2;
  98176. c.norU2Z = norZ * this.m2;
  98177. c.tanU1X = tanX * this.m1;
  98178. c.tanU1Y = tanY * this.m1;
  98179. c.tanU1Z = tanZ * this.m1;
  98180. c.tanU2X = tanX * this.m2;
  98181. c.tanU2Y = tanY * this.m2;
  98182. c.tanU2Z = tanZ * this.m2;
  98183. c.binU1X = binX * this.m1;
  98184. c.binU1Y = binY * this.m1;
  98185. c.binU1Z = binZ * this.m1;
  98186. c.binU2X = binX * this.m2;
  98187. c.binU2Y = binY * this.m2;
  98188. c.binU2Z = binZ * this.m2;
  98189. var norT1X = rp1Y * norZ - rp1Z * norY;
  98190. var norT1Y = rp1Z * norX - rp1X * norZ;
  98191. var norT1Z = rp1X * norY - rp1Y * norX;
  98192. var norT2X = rp2Y * norZ - rp2Z * norY;
  98193. var norT2Y = rp2Z * norX - rp2X * norZ;
  98194. var norT2Z = rp2X * norY - rp2Y * norX;
  98195. var tanT1X = rp1Y * tanZ - rp1Z * tanY;
  98196. var tanT1Y = rp1Z * tanX - rp1X * tanZ;
  98197. var tanT1Z = rp1X * tanY - rp1Y * tanX;
  98198. var tanT2X = rp2Y * tanZ - rp2Z * tanY;
  98199. var tanT2Y = rp2Z * tanX - rp2X * tanZ;
  98200. var tanT2Z = rp2X * tanY - rp2Y * tanX;
  98201. var binT1X = rp1Y * binZ - rp1Z * binY;
  98202. var binT1Y = rp1Z * binX - rp1X * binZ;
  98203. var binT1Z = rp1X * binY - rp1Y * binX;
  98204. var binT2X = rp2Y * binZ - rp2Z * binY;
  98205. var binT2Y = rp2Z * binX - rp2X * binZ;
  98206. var binT2Z = rp2X * binY - rp2Y * binX;
  98207. var norTU1X = norT1X * ii1[0] + norT1Y * ii1[1] + norT1Z * ii1[2];
  98208. var norTU1Y = norT1X * ii1[3] + norT1Y * ii1[4] + norT1Z * ii1[5];
  98209. var norTU1Z = norT1X * ii1[6] + norT1Y * ii1[7] + norT1Z * ii1[8];
  98210. var norTU2X = norT2X * ii2[0] + norT2Y * ii2[1] + norT2Z * ii2[2];
  98211. var norTU2Y = norT2X * ii2[3] + norT2Y * ii2[4] + norT2Z * ii2[5];
  98212. var norTU2Z = norT2X * ii2[6] + norT2Y * ii2[7] + norT2Z * ii2[8];
  98213. var tanTU1X = tanT1X * ii1[0] + tanT1Y * ii1[1] + tanT1Z * ii1[2];
  98214. var tanTU1Y = tanT1X * ii1[3] + tanT1Y * ii1[4] + tanT1Z * ii1[5];
  98215. var tanTU1Z = tanT1X * ii1[6] + tanT1Y * ii1[7] + tanT1Z * ii1[8];
  98216. var tanTU2X = tanT2X * ii2[0] + tanT2Y * ii2[1] + tanT2Z * ii2[2];
  98217. var tanTU2Y = tanT2X * ii2[3] + tanT2Y * ii2[4] + tanT2Z * ii2[5];
  98218. var tanTU2Z = tanT2X * ii2[6] + tanT2Y * ii2[7] + tanT2Z * ii2[8];
  98219. var binTU1X = binT1X * ii1[0] + binT1Y * ii1[1] + binT1Z * ii1[2];
  98220. var binTU1Y = binT1X * ii1[3] + binT1Y * ii1[4] + binT1Z * ii1[5];
  98221. var binTU1Z = binT1X * ii1[6] + binT1Y * ii1[7] + binT1Z * ii1[8];
  98222. var binTU2X = binT2X * ii2[0] + binT2Y * ii2[1] + binT2Z * ii2[2];
  98223. var binTU2Y = binT2X * ii2[3] + binT2Y * ii2[4] + binT2Z * ii2[5];
  98224. var binTU2Z = binT2X * ii2[6] + binT2Y * ii2[7] + binT2Z * ii2[8];
  98225. c.norT1X = norT1X;
  98226. c.norT1Y = norT1Y;
  98227. c.norT1Z = norT1Z;
  98228. c.tanT1X = tanT1X;
  98229. c.tanT1Y = tanT1Y;
  98230. c.tanT1Z = tanT1Z;
  98231. c.binT1X = binT1X;
  98232. c.binT1Y = binT1Y;
  98233. c.binT1Z = binT1Z;
  98234. c.norT2X = norT2X;
  98235. c.norT2Y = norT2Y;
  98236. c.norT2Z = norT2Z;
  98237. c.tanT2X = tanT2X;
  98238. c.tanT2Y = tanT2Y;
  98239. c.tanT2Z = tanT2Z;
  98240. c.binT2X = binT2X;
  98241. c.binT2Y = binT2Y;
  98242. c.binT2Z = binT2Z;
  98243. c.norTU1X = norTU1X;
  98244. c.norTU1Y = norTU1Y;
  98245. c.norTU1Z = norTU1Z;
  98246. c.tanTU1X = tanTU1X;
  98247. c.tanTU1Y = tanTU1Y;
  98248. c.tanTU1Z = tanTU1Z;
  98249. c.binTU1X = binTU1X;
  98250. c.binTU1Y = binTU1Y;
  98251. c.binTU1Z = binTU1Z;
  98252. c.norTU2X = norTU2X;
  98253. c.norTU2Y = norTU2Y;
  98254. c.norTU2Z = norTU2Z;
  98255. c.tanTU2X = tanTU2X;
  98256. c.tanTU2Y = tanTU2Y;
  98257. c.tanTU2Z = tanTU2Z;
  98258. c.binTU2X = binTU2X;
  98259. c.binTU2Y = binTU2Y;
  98260. c.binTU2Z = binTU2Z;
  98261. tmp1X = norT1X * ii1[0] + norT1Y * ii1[1] + norT1Z * ii1[2];
  98262. tmp1Y = norT1X * ii1[3] + norT1Y * ii1[4] + norT1Z * ii1[5];
  98263. tmp1Z = norT1X * ii1[6] + norT1Y * ii1[7] + norT1Z * ii1[8];
  98264. tmp2X = tmp1Y * rp1Z - tmp1Z * rp1Y;
  98265. tmp2Y = tmp1Z * rp1X - tmp1X * rp1Z;
  98266. tmp2Z = tmp1X * rp1Y - tmp1Y * rp1X;
  98267. tmp1X = norT2X * ii2[0] + norT2Y * ii2[1] + norT2Z * ii2[2];
  98268. tmp1Y = norT2X * ii2[3] + norT2Y * ii2[4] + norT2Z * ii2[5];
  98269. tmp1Z = norT2X * ii2[6] + norT2Y * ii2[7] + norT2Z * ii2[8];
  98270. tmp2X += tmp1Y * rp2Z - tmp1Z * rp2Y;
  98271. tmp2Y += tmp1Z * rp2X - tmp1X * rp2Z;
  98272. tmp2Z += tmp1X * rp2Y - tmp1Y * rp2X;
  98273. var norDen = 1 / (m1m2 + norX * tmp2X + norY * tmp2Y + norZ * tmp2Z);
  98274. tmp1X = tanT1X * ii1[0] + tanT1Y * ii1[1] + tanT1Z * ii1[2];
  98275. tmp1Y = tanT1X * ii1[3] + tanT1Y * ii1[4] + tanT1Z * ii1[5];
  98276. tmp1Z = tanT1X * ii1[6] + tanT1Y * ii1[7] + tanT1Z * ii1[8];
  98277. tmp2X = tmp1Y * rp1Z - tmp1Z * rp1Y;
  98278. tmp2Y = tmp1Z * rp1X - tmp1X * rp1Z;
  98279. tmp2Z = tmp1X * rp1Y - tmp1Y * rp1X;
  98280. tmp1X = tanT2X * ii2[0] + tanT2Y * ii2[1] + tanT2Z * ii2[2];
  98281. tmp1Y = tanT2X * ii2[3] + tanT2Y * ii2[4] + tanT2Z * ii2[5];
  98282. tmp1Z = tanT2X * ii2[6] + tanT2Y * ii2[7] + tanT2Z * ii2[8];
  98283. tmp2X += tmp1Y * rp2Z - tmp1Z * rp2Y;
  98284. tmp2Y += tmp1Z * rp2X - tmp1X * rp2Z;
  98285. tmp2Z += tmp1X * rp2Y - tmp1Y * rp2X;
  98286. var tanDen = 1 / (m1m2 + tanX * tmp2X + tanY * tmp2Y + tanZ * tmp2Z);
  98287. tmp1X = binT1X * ii1[0] + binT1Y * ii1[1] + binT1Z * ii1[2];
  98288. tmp1Y = binT1X * ii1[3] + binT1Y * ii1[4] + binT1Z * ii1[5];
  98289. tmp1Z = binT1X * ii1[6] + binT1Y * ii1[7] + binT1Z * ii1[8];
  98290. tmp2X = tmp1Y * rp1Z - tmp1Z * rp1Y;
  98291. tmp2Y = tmp1Z * rp1X - tmp1X * rp1Z;
  98292. tmp2Z = tmp1X * rp1Y - tmp1Y * rp1X;
  98293. tmp1X = binT2X * ii2[0] + binT2Y * ii2[1] + binT2Z * ii2[2];
  98294. tmp1Y = binT2X * ii2[3] + binT2Y * ii2[4] + binT2Z * ii2[5];
  98295. tmp1Z = binT2X * ii2[6] + binT2Y * ii2[7] + binT2Z * ii2[8];
  98296. tmp2X += tmp1Y * rp2Z - tmp1Z * rp2Y;
  98297. tmp2Y += tmp1Z * rp2X - tmp1X * rp2Z;
  98298. tmp2Z += tmp1X * rp2Y - tmp1Y * rp2X;
  98299. var binDen = 1 / (m1m2 + binX * tmp2X + binY * tmp2Y + binZ * tmp2Z);
  98300. c.norDen = norDen;
  98301. c.tanDen = tanDen;
  98302. c.binDen = binDen;
  98303. if (p.warmStarted) {
  98304. var norImp = p.normalImpulse;
  98305. this.lv1.x += c.norU1X * norImp;
  98306. this.lv1.y += c.norU1Y * norImp;
  98307. this.lv1.z += c.norU1Z * norImp;
  98308. this.av1.x += norTU1X * norImp;
  98309. this.av1.y += norTU1Y * norImp;
  98310. this.av1.z += norTU1Z * norImp;
  98311. this.lv2.x -= c.norU2X * norImp;
  98312. this.lv2.y -= c.norU2Y * norImp;
  98313. this.lv2.z -= c.norU2Z * norImp;
  98314. this.av2.x -= norTU2X * norImp;
  98315. this.av2.y -= norTU2Y * norImp;
  98316. this.av2.z -= norTU2Z * norImp;
  98317. c.norImp = norImp;
  98318. c.tanImp = 0;
  98319. c.binImp = 0;
  98320. rvn = 0; // disable bouncing
  98321. } else {
  98322. c.norImp = 0;
  98323. c.tanImp = 0;
  98324. c.binImp = 0;
  98325. }
  98326. if (rvn > -1) {
  98327. rvn = 0; // disable bouncing
  98328. }
  98329. var norTar = this.restitution * -rvn;
  98330. var sepV = -(p.penetration + 0.005) * invTimeStep * 0.05; // allow 0.5cm error
  98331. if (norTar < sepV) norTar = sepV;
  98332. c.norTar = norTar;
  98333. c.last = i == this.num - 1;
  98334. c = c.next;
  98335. }
  98336. }
  98337. OIMO.ContactConstraint.prototype.solve = function () {
  98338. var lv1x = this.lv1.x;
  98339. var lv1y = this.lv1.y;
  98340. var lv1z = this.lv1.z;
  98341. var lv2x = this.lv2.x;
  98342. var lv2y = this.lv2.y;
  98343. var lv2z = this.lv2.z;
  98344. var av1x = this.av1.x;
  98345. var av1y = this.av1.y;
  98346. var av1z = this.av1.z;
  98347. var av2x = this.av2.x;
  98348. var av2y = this.av2.y;
  98349. var av2z = this.av2.z;
  98350. var c = this.cs;
  98351. while (true) {
  98352. var oldImp1;
  98353. var newImp1;
  98354. var oldImp2;
  98355. var newImp2;
  98356. var rvn;
  98357. var norImp = c.norImp;
  98358. var tanImp = c.tanImp;
  98359. var binImp = c.binImp;
  98360. var max = -norImp * this.friction;
  98361. var rvX = lv2x - lv1x;
  98362. var rvY = lv2y - lv1y;
  98363. var rvZ = lv2z - lv1z;
  98364. rvn =
  98365. rvX * c.tanX + rvY * c.tanY + rvZ * c.tanZ +
  98366. av2x * c.tanT2X + av2y * c.tanT2Y + av2z * c.tanT2Z -
  98367. av1x * c.tanT1X - av1y * c.tanT1Y - av1z * c.tanT1Z
  98368. ;
  98369. oldImp1 = tanImp;
  98370. newImp1 = rvn * c.tanDen;
  98371. tanImp += newImp1;
  98372. rvn =
  98373. rvX * c.binX + rvY * c.binY + rvZ * c.binZ +
  98374. av2x * c.binT2X + av2y * c.binT2Y + av2z * c.binT2Z -
  98375. av1x * c.binT1X - av1y * c.binT1Y - av1z * c.binT1Z
  98376. ;
  98377. oldImp2 = binImp;
  98378. newImp2 = rvn * c.binDen;
  98379. binImp += newImp2;
  98380. // cone friction clamp
  98381. var len = tanImp * tanImp + binImp * binImp;
  98382. if (len > max * max) {
  98383. len = max / OIMO.sqrt(len);
  98384. tanImp *= len;
  98385. binImp *= len;
  98386. }
  98387. newImp1 = tanImp - oldImp1;
  98388. newImp2 = binImp - oldImp2;
  98389. lv1x += c.tanU1X * newImp1 + c.binU1X * newImp2;
  98390. lv1y += c.tanU1Y * newImp1 + c.binU1Y * newImp2;
  98391. lv1z += c.tanU1Z * newImp1 + c.binU1Z * newImp2;
  98392. av1x += c.tanTU1X * newImp1 + c.binTU1X * newImp2;
  98393. av1y += c.tanTU1Y * newImp1 + c.binTU1Y * newImp2;
  98394. av1z += c.tanTU1Z * newImp1 + c.binTU1Z * newImp2;
  98395. lv2x -= c.tanU2X * newImp1 + c.binU2X * newImp2;
  98396. lv2y -= c.tanU2Y * newImp1 + c.binU2Y * newImp2;
  98397. lv2z -= c.tanU2Z * newImp1 + c.binU2Z * newImp2;
  98398. av2x -= c.tanTU2X * newImp1 + c.binTU2X * newImp2;
  98399. av2y -= c.tanTU2Y * newImp1 + c.binTU2Y * newImp2;
  98400. av2z -= c.tanTU2Z * newImp1 + c.binTU2Z * newImp2;
  98401. // restitution part
  98402. rvn =
  98403. (lv2x - lv1x) * c.norX + (lv2y - lv1y) * c.norY + (lv2z - lv1z) * c.norZ +
  98404. av2x * c.norT2X + av2y * c.norT2Y + av2z * c.norT2Z -
  98405. av1x * c.norT1X - av1y * c.norT1Y - av1z * c.norT1Z;
  98406. oldImp1 = norImp;
  98407. newImp1 = (rvn - c.norTar) * c.norDen;
  98408. norImp += newImp1;
  98409. if (norImp > 0) norImp = 0;
  98410. newImp1 = norImp - oldImp1;
  98411. lv1x += c.norU1X * newImp1;
  98412. lv1y += c.norU1Y * newImp1;
  98413. lv1z += c.norU1Z * newImp1;
  98414. av1x += c.norTU1X * newImp1;
  98415. av1y += c.norTU1Y * newImp1;
  98416. av1z += c.norTU1Z * newImp1;
  98417. lv2x -= c.norU2X * newImp1;
  98418. lv2y -= c.norU2Y * newImp1;
  98419. lv2z -= c.norU2Z * newImp1;
  98420. av2x -= c.norTU2X * newImp1;
  98421. av2y -= c.norTU2Y * newImp1;
  98422. av2z -= c.norTU2Z * newImp1;
  98423. c.norImp = norImp;
  98424. c.tanImp = tanImp;
  98425. c.binImp = binImp;
  98426. if (c.last) break;
  98427. c = c.next;
  98428. }
  98429. this.lv1.x = lv1x;
  98430. this.lv1.y = lv1y;
  98431. this.lv1.z = lv1z;
  98432. this.lv2.x = lv2x;
  98433. this.lv2.y = lv2y;
  98434. this.lv2.z = lv2z;
  98435. this.av1.x = av1x;
  98436. this.av1.y = av1y;
  98437. this.av1.z = av1z;
  98438. this.av2.x = av2x;
  98439. this.av2.y = av2y;
  98440. this.av2.z = av2z;
  98441. }
  98442. OIMO.ContactConstraint.prototype.postSolve = function () {
  98443. var c = this.cs;
  98444. var i = this.num;
  98445. while (i--) {
  98446. //for(var i=0;i<this.num;i++){
  98447. var p = this.ps[i];
  98448. p.normal.x = c.norX;
  98449. p.normal.y = c.norY;
  98450. p.normal.z = c.norZ;
  98451. p.tangent.x = c.tanX;
  98452. p.tangent.y = c.tanY;
  98453. p.tangent.z = c.tanZ;
  98454. p.binormal.x = c.binX;
  98455. p.binormal.y = c.binY;
  98456. p.binormal.z = c.binZ;
  98457. p.normalImpulse = c.norImp;
  98458. p.tangentImpulse = c.tanImp;
  98459. p.binormalImpulse = c.binImp;
  98460. p.normalDenominator = c.norDen;
  98461. p.tangentDenominator = c.tanDen;
  98462. p.binormalDenominator = c.binDen;
  98463. c = c.next;
  98464. }
  98465. }
  98466. /**
  98467. * A link list of contacts.
  98468. * @author saharan
  98469. */
  98470. OIMO.ContactLink = function (contact) {
  98471. // The previous contact link.
  98472. this.prev = null;
  98473. // The next contact link.
  98474. this.next = null;
  98475. // The shape of the contact.
  98476. this.shape = null;
  98477. // The other rigid body.
  98478. this.body = null;
  98479. // The contact of the link.
  98480. this.contact = contact;
  98481. }
  98482. /**
  98483. * A contact manifold between two shapes.
  98484. * @author saharan
  98485. */
  98486. OIMO.ContactManifold = function () {
  98487. // The first rigid body.
  98488. this.body1 = null;
  98489. // The second rigid body.
  98490. this.body2 = null;
  98491. // The number of manifold points.
  98492. this.numPoints = 0;
  98493. // The manifold points.
  98494. this.points = [];
  98495. this.points.length = 4;
  98496. this.points[0] = new OIMO.ManifoldPoint();
  98497. this.points[1] = new OIMO.ManifoldPoint();
  98498. this.points[2] = new OIMO.ManifoldPoint();
  98499. this.points[3] = new OIMO.ManifoldPoint();
  98500. }
  98501. OIMO.ContactManifold.prototype = {
  98502. constructor: OIMO.ContactManifold,
  98503. /**
  98504. * Reset the manifold.
  98505. * @param shape1
  98506. * @param shape2
  98507. */
  98508. reset: function (shape1, shape2) {
  98509. this.body1 = shape1.parent;
  98510. this.body2 = shape2.parent;
  98511. this.numPoints = 0;
  98512. },
  98513. /**
  98514. * Add a point into this manifold.
  98515. * @param x
  98516. * @param y
  98517. * @param z
  98518. * @param normalX
  98519. * @param normalY
  98520. * @param normalZ
  98521. * @param penetration
  98522. * @param flip
  98523. */
  98524. addPoint: function (x, y, z, normalX, normalY, normalZ, penetration, flip) {
  98525. var p = this.points[this.numPoints++];
  98526. p.position.x = x;
  98527. p.position.y = y;
  98528. p.position.z = z;
  98529. var r = this.body1.rotation;
  98530. var rx = x - this.body1.position.x;
  98531. var ry = y - this.body1.position.y;
  98532. var rz = z - this.body1.position.z;
  98533. var tr = r.elements;
  98534. p.localPoint1.x = rx * tr[0] + ry * tr[3] + rz * tr[6];
  98535. p.localPoint1.y = rx * tr[1] + ry * tr[4] + rz * tr[7];
  98536. p.localPoint1.z = rx * tr[2] + ry * tr[5] + rz * tr[8];
  98537. r = this.body2.rotation;
  98538. rx = x - this.body2.position.x;
  98539. ry = y - this.body2.position.y;
  98540. rz = z - this.body2.position.z;
  98541. p.localPoint2.x = rx * tr[0] + ry * tr[3] + rz * tr[6];
  98542. p.localPoint2.y = rx * tr[1] + ry * tr[4] + rz * tr[7];
  98543. p.localPoint2.z = rx * tr[2] + ry * tr[5] + rz * tr[8];
  98544. p.normalImpulse = 0;
  98545. if (flip) {
  98546. p.normal.x = -normalX;
  98547. p.normal.y = -normalY;
  98548. p.normal.z = -normalZ;
  98549. } else {
  98550. p.normal.x = normalX;
  98551. p.normal.y = normalY;
  98552. p.normal.z = normalZ;
  98553. }
  98554. p.penetration = penetration;
  98555. p.warmStarted = false;
  98556. }
  98557. }
  98558. OIMO.ContactPointDataBuffer = function () {
  98559. this.norX = NaN;
  98560. this.norY = NaN;
  98561. this.norZ = NaN;
  98562. this.tanX = NaN;
  98563. this.tanY = NaN;
  98564. this.tanZ = NaN;
  98565. this.binX = NaN;
  98566. this.binY = NaN;
  98567. this.binZ = NaN;
  98568. this.rp1X = NaN;
  98569. this.rp1Y = NaN;
  98570. this.rp1Z = NaN;
  98571. this.rp2X = NaN;
  98572. this.rp2Y = NaN;
  98573. this.rp2Z = NaN;
  98574. this.norU1X = NaN;
  98575. this.norU1Y = NaN;
  98576. this.norU1Z = NaN;
  98577. this.norU2X = NaN;
  98578. this.norU2Y = NaN;
  98579. this.norU2Z = NaN;
  98580. this.tanU1X = NaN;
  98581. this.tanU1Y = NaN;
  98582. this.tanU1Z = NaN;
  98583. this.tanU2X = NaN;
  98584. this.tanU2Y = NaN;
  98585. this.tanU2Z = NaN;
  98586. this.binU1X = NaN;
  98587. this.binU1Y = NaN;
  98588. this.binU1Z = NaN;
  98589. this.binU2X = NaN;
  98590. this.binU2Y = NaN;
  98591. this.binU2Z = NaN;
  98592. this.norT1X = NaN;
  98593. this.norT1Y = NaN;
  98594. this.norT1Z = NaN;
  98595. this.norT2X = NaN;
  98596. this.norT2Y = NaN;
  98597. this.norT2Z = NaN;
  98598. this.tanT1X = NaN;
  98599. this.tanT1Y = NaN;
  98600. this.tanT1Z = NaN;
  98601. this.tanT2X = NaN;
  98602. this.tanT2Y = NaN;
  98603. this.tanT2Z = NaN;
  98604. this.binT1X = NaN;
  98605. this.binT1Y = NaN;
  98606. this.binT1Z = NaN;
  98607. this.binT2X = NaN;
  98608. this.binT2Y = NaN;
  98609. this.binT2Z = NaN;
  98610. this.norTU1X = NaN;
  98611. this.norTU1Y = NaN;
  98612. this.norTU1Z = NaN;
  98613. this.norTU2X = NaN;
  98614. this.norTU2Y = NaN;
  98615. this.norTU2Z = NaN;
  98616. this.tanTU1X = NaN;
  98617. this.tanTU1Y = NaN;
  98618. this.tanTU1Z = NaN;
  98619. this.tanTU2X = NaN;
  98620. this.tanTU2Y = NaN;
  98621. this.tanTU2Z = NaN;
  98622. this.binTU1X = NaN;
  98623. this.binTU1Y = NaN;
  98624. this.binTU1Z = NaN;
  98625. this.binTU2X = NaN;
  98626. this.binTU2Y = NaN;
  98627. this.binTU2Z = NaN;
  98628. this.norImp = NaN;
  98629. this.tanImp = NaN;
  98630. this.binImp = NaN;
  98631. this.norDen = NaN;
  98632. this.tanDen = NaN;
  98633. this.binDen = NaN;
  98634. this.norTar = NaN;
  98635. this.next = null;
  98636. this.last = false;
  98637. }
  98638. OIMO.ImpulseDataBuffer = function () {
  98639. this.lp1X = NaN;
  98640. this.lp1Y = NaN;
  98641. this.lp1Z = NaN;
  98642. this.lp2X = NaN;
  98643. this.lp2Y = NaN;
  98644. this.lp2Z = NaN;
  98645. this.impulse = NaN;
  98646. }
  98647. /**
  98648. * The class holds details of the contact point.
  98649. * @author saharan
  98650. */
  98651. OIMO.ManifoldPoint = function () {
  98652. // Whether this manifold point is persisting or not.
  98653. this.warmStarted = false;
  98654. // The position of this manifold point.
  98655. this.position = new OIMO.Vec3();
  98656. // The position in the first shape's coordinate.
  98657. this.localPoint1 = new OIMO.Vec3();
  98658. // The position in the second shape's coordinate.
  98659. this.localPoint2 = new OIMO.Vec3();
  98660. // The normal vector of this manifold point.
  98661. this.normal = new OIMO.Vec3();
  98662. // The tangent vector of this manifold point.
  98663. this.tangent = new OIMO.Vec3();
  98664. // The binormal vector of this manifold point.
  98665. this.binormal = new OIMO.Vec3();
  98666. // The impulse in normal direction.
  98667. this.normalImpulse = 0;
  98668. // The impulse in tangent direction.
  98669. this.tangentImpulse = 0;
  98670. // The impulse in binormal direction.
  98671. this.binormalImpulse = 0;
  98672. // The denominator in normal direction.
  98673. this.normalDenominator = 0;
  98674. // The denominator in tangent direction.
  98675. this.tangentDenominator = 0;
  98676. // The denominator in binormal direction.
  98677. this.binormalDenominator = 0;
  98678. // The depth of penetration.
  98679. this.penetration = 0;
  98680. }
  98681. /**
  98682. * This class holds mass information of a shape.
  98683. * @author saharan
  98684. */
  98685. OIMO.MassInfo = function () {
  98686. // Mass of the shape.
  98687. this.mass = 0;
  98688. // The moment inertia of the shape.
  98689. this.inertia = new OIMO.Mat33();
  98690. };
  98691. /**
  98692. * A shape is used to detect collisions of rigid bodies.
  98693. * @author saharan
  98694. * @author lo-th
  98695. */
  98696. OIMO.Shape = function (config) {
  98697. this.type = OIMO.SHAPE_NULL;
  98698. // The global identification of the shape should be unique to the shape.
  98699. this.id = OIMO.nextID++;
  98700. // The previous shape in parent rigid body.
  98701. this.prev = null;
  98702. // The next shape in parent rigid body.
  98703. this.next = null;
  98704. // The proxy of the shape used for broad-phase collision detection.
  98705. this.proxy = null;
  98706. // The parent rigid body of the shape.
  98707. this.parent = null;
  98708. // The linked list of the contacts with the shape.
  98709. this.contactLink = null;
  98710. // The number of the contacts with the shape.
  98711. this.numContacts = 0;
  98712. // The center of gravity of the shape in world coordinate system.
  98713. this.position = new OIMO.Vec3();
  98714. // The rotation matrix of the shape in world coordinate system
  98715. this.rotation = new OIMO.Mat33();
  98716. // The position of the shape in parent's coordinate system.
  98717. this.relativePosition = new OIMO.Vec3().copy(config.relativePosition);
  98718. // The rotation matrix of the shape in parent's coordinate system.
  98719. this.relativeRotation = new OIMO.Mat33().copy(config.relativeRotation);
  98720. // The axis-aligned bounding box of the shape.
  98721. this.aabb = new OIMO.AABB();
  98722. // The density of the shape.
  98723. this.density = config.density;
  98724. // The coefficient of friction of the shape.
  98725. this.friction = config.friction;
  98726. // The coefficient of restitution of the shape.
  98727. this.restitution = config.restitution;
  98728. // The bits of the collision groups to which the shape belongs.
  98729. this.belongsTo = config.belongsTo;
  98730. // The bits of the collision groups with which the shape collides.
  98731. this.collidesWith = config.collidesWith;
  98732. };
  98733. OIMO.Shape.prototype = {
  98734. constructor: OIMO.Shape,
  98735. // Calculate the mass information of the shape.
  98736. calculateMassInfo: function (out) {
  98737. OIMO.Error("Shape", "Inheritance error.");
  98738. },
  98739. // Update the proxy of the shape.
  98740. updateProxy: function () {
  98741. OIMO.Error("Shape", "Inheritance error.");
  98742. }
  98743. };
  98744. /**
  98745. * A shape configuration holds common configuration data for constructing a shape.
  98746. * Shape configurations can be reused safely.
  98747. * @author saharan
  98748. */
  98749. OIMO.ShapeConfig = function () {
  98750. // The position of the shape in parent's coordinate system.
  98751. this.relativePosition = new OIMO.Vec3();
  98752. // The rotation matrix of the shape in parent's coordinate system.
  98753. this.relativeRotation = new OIMO.Mat33();
  98754. // The coefficient of friction of the shape.
  98755. this.friction = 0.4;
  98756. // The coefficient of restitution of the shape.
  98757. this.restitution = 0.2;
  98758. // The density of the shape.
  98759. this.density = 1;
  98760. // The bits of the collision groups to which the shape belongs.
  98761. this.belongsTo = 1;
  98762. // The bits of the collision groups with which the shape collides.
  98763. this.collidesWith = 0xffffffff;
  98764. };
  98765. /**
  98766. * A box shape.
  98767. * @author saharan
  98768. * @author lo-th
  98769. */
  98770. OIMO.BoxShape = function (config, Width, Height, Depth) {
  98771. OIMO.Shape.call(this, config);
  98772. this.type = OIMO.SHAPE_BOX;
  98773. // The width of the box.
  98774. this.width = Width;
  98775. // The height of the box.
  98776. this.height = Height;
  98777. // The depth of the box.
  98778. this.depth = Depth;
  98779. // The half-width of the box.
  98780. this.halfWidth = Width * 0.5;
  98781. // The half-height of the box.
  98782. this.halfHeight = Height * 0.5;
  98783. // The half-depth of the box.
  98784. this.halfDepth = Depth * 0.5;
  98785. this.dimentions = new OIMO_ARRAY_TYPE(18);
  98786. this.elements = new OIMO_ARRAY_TYPE(24);
  98787. };
  98788. OIMO.BoxShape.prototype = Object.create(OIMO.Shape.prototype);
  98789. OIMO.BoxShape.prototype.constructor = OIMO.BoxShape;
  98790. OIMO.BoxShape.prototype.calculateMassInfo = function (out) {
  98791. var mass = this.width * this.height * this.depth * this.density;
  98792. var divid = 1 / 12;
  98793. out.mass = mass;
  98794. out.inertia.set(
  98795. mass * (this.height * this.height + this.depth * this.depth) * divid, 0, 0,
  98796. 0, mass * (this.width * this.width + this.depth * this.depth) * divid, 0,
  98797. 0, 0, mass * (this.width * this.width + this.height * this.height) * divid
  98798. );
  98799. };
  98800. OIMO.BoxShape.prototype.updateProxy = function () {
  98801. var te = this.rotation.elements;
  98802. var di = this.dimentions;
  98803. // Width
  98804. di[0] = te[0];
  98805. di[1] = te[3];
  98806. di[2] = te[6];
  98807. // Height
  98808. di[3] = te[1];
  98809. di[4] = te[4];
  98810. di[5] = te[7];
  98811. // Depth
  98812. di[6] = te[2];
  98813. di[7] = te[5];
  98814. di[8] = te[8];
  98815. // halp Width
  98816. di[9] = te[0] * this.halfWidth;
  98817. di[10] = te[3] * this.halfWidth;
  98818. di[11] = te[6] * this.halfWidth;
  98819. // halp Height
  98820. di[12] = te[1] * this.halfHeight;
  98821. di[13] = te[4] * this.halfHeight;
  98822. di[14] = te[7] * this.halfHeight;
  98823. // halp Depth
  98824. di[15] = te[2] * this.halfDepth;
  98825. di[16] = te[5] * this.halfDepth;
  98826. di[17] = te[8] * this.halfDepth;
  98827. var wx = di[9];
  98828. var wy = di[10];
  98829. var wz = di[11];
  98830. var hx = di[12];
  98831. var hy = di[13];
  98832. var hz = di[14];
  98833. var dx = di[15];
  98834. var dy = di[16];
  98835. var dz = di[17];
  98836. var x = this.position.x;
  98837. var y = this.position.y;
  98838. var z = this.position.z;
  98839. var v = this.elements;
  98840. //v1
  98841. v[0] = x + wx + hx + dx;
  98842. v[1] = y + wy + hy + dy;
  98843. v[2] = z + wz + hz + dz;
  98844. //v2
  98845. v[3] = x + wx + hx - dx;
  98846. v[4] = y + wy + hy - dy;
  98847. v[5] = z + wz + hz - dz;
  98848. //v3
  98849. v[6] = x + wx - hx + dx;
  98850. v[7] = y + wy - hy + dy;
  98851. v[8] = z + wz - hz + dz;
  98852. //v4
  98853. v[9] = x + wx - hx - dx;
  98854. v[10] = y + wy - hy - dy;
  98855. v[11] = z + wz - hz - dz;
  98856. //v5
  98857. v[12] = x - wx + hx + dx;
  98858. v[13] = y - wy + hy + dy;
  98859. v[14] = z - wz + hz + dz;
  98860. //v6
  98861. v[15] = x - wx + hx - dx;
  98862. v[16] = y - wy + hy - dy;
  98863. v[17] = z - wz + hz - dz;
  98864. //v7
  98865. v[18] = x - wx - hx + dx;
  98866. v[19] = y - wy - hy + dy;
  98867. v[20] = z - wz - hz + dz;
  98868. //v8
  98869. v[21] = x - wx - hx - dx;
  98870. v[22] = y - wy - hy - dy;
  98871. v[23] = z - wz - hz - dz;
  98872. var w = di[9] < 0 ? -di[9] : di[9];
  98873. var h = di[10] < 0 ? -di[10] : di[10];
  98874. var d = di[11] < 0 ? -di[11] : di[11];
  98875. w = di[12] < 0 ? w - di[12] : w + di[12];
  98876. h = di[13] < 0 ? h - di[13] : h + di[13];
  98877. d = di[14] < 0 ? d - di[14] : d + di[14];
  98878. w = di[15] < 0 ? w - di[15] : w + di[15];
  98879. h = di[16] < 0 ? h - di[16] : h + di[16];
  98880. d = di[17] < 0 ? d - di[17] : d + di[17];
  98881. var p = OIMO.AABB_PROX;
  98882. this.aabb.set(
  98883. this.position.x - w - p, this.position.x + w + p,
  98884. this.position.y - h - p, this.position.y + h + p,
  98885. this.position.z - d - p, this.position.z + d + p
  98886. );
  98887. if (this.proxy != null) this.proxy.update();
  98888. };
  98889. /**
  98890. * A sphere shape.
  98891. * @author saharan
  98892. * @author lo-th
  98893. */
  98894. OIMO.SphereShape = function (config, radius) {
  98895. OIMO.Shape.call(this, config);
  98896. this.type = OIMO.SHAPE_SPHERE;
  98897. // The radius of the shape.
  98898. this.radius = radius;
  98899. };
  98900. OIMO.SphereShape.prototype = Object.create(OIMO.Shape.prototype);
  98901. OIMO.SphereShape.prototype.constructor = OIMO.SphereShape;
  98902. OIMO.SphereShape.prototype.calculateMassInfo = function (out) {
  98903. var mass = 1.333 * OIMO.PI * this.radius * this.radius * this.radius * this.density;
  98904. out.mass = mass;
  98905. var inertia = mass * this.radius * this.radius * 0.4;
  98906. out.inertia.set(inertia, 0, 0, 0, inertia, 0, 0, 0, inertia);
  98907. };
  98908. OIMO.SphereShape.prototype.updateProxy = function () {
  98909. var p = OIMO.AABB_PROX;
  98910. this.aabb.set(
  98911. this.position.x - this.radius - p, this.position.x + this.radius + p,
  98912. this.position.y - this.radius - p, this.position.y + this.radius + p,
  98913. this.position.z - this.radius - p, this.position.z + this.radius + p
  98914. );
  98915. if (this.proxy != null) this.proxy.update();
  98916. };
  98917. /**
  98918. * A cylinder shap.
  98919. * @author saharan
  98920. * @author lo-th
  98921. */
  98922. OIMO.CylinderShape = function (config, radius, height) {
  98923. OIMO.Shape.call(this, config);
  98924. this.type = OIMO.SHAPE_CYLINDER;
  98925. this.radius = radius;
  98926. this.height = height;
  98927. this.halfHeight = height * 0.5;
  98928. this.normalDirection = new OIMO.Vec3();
  98929. this.halfDirection = new OIMO.Vec3();
  98930. };
  98931. OIMO.CylinderShape.prototype = Object.create(OIMO.Shape.prototype);
  98932. OIMO.CylinderShape.prototype.constructor = OIMO.CylinderShape;
  98933. OIMO.CylinderShape.prototype.calculateMassInfo = function (out) {
  98934. var rsq = this.radius * this.radius;
  98935. var mass = OIMO.PI * rsq * this.height * this.density;
  98936. var inertiaXZ = ((0.25 * rsq) + (0.0833 * this.height * this.height)) * mass;
  98937. var inertiaY = 0.5 * rsq;
  98938. out.mass = mass;
  98939. out.inertia.set(inertiaXZ, 0, 0, 0, inertiaY, 0, 0, 0, inertiaXZ);
  98940. };
  98941. OIMO.CylinderShape.prototype.updateProxy = function () {
  98942. var te = this.rotation.elements;
  98943. var len, wx, hy, dz, xx, yy, zz, w, h, d, p;
  98944. xx = te[1] * te[1];
  98945. yy = te[4] * te[4];
  98946. zz = te[7] * te[7];
  98947. this.normalDirection.set(te[1], te[4], te[7]);
  98948. this.halfDirection.scale(this.normalDirection, this.halfHeight);
  98949. wx = 1 - xx;
  98950. len = OIMO.sqrt(wx * wx + xx * yy + xx * zz);
  98951. if (len > 0) len = this.radius / len;
  98952. wx *= len;
  98953. hy = 1 - yy;
  98954. len = OIMO.sqrt(yy * xx + hy * hy + yy * zz);
  98955. if (len > 0) len = this.radius / len;
  98956. hy *= len;
  98957. dz = 1 - zz;
  98958. len = OIMO.sqrt(zz * xx + zz * yy + dz * dz);
  98959. if (len > 0) len = this.radius / len;
  98960. dz *= len;
  98961. w = this.halfDirection.x < 0 ? -this.halfDirection.x : this.halfDirection.x;
  98962. h = this.halfDirection.y < 0 ? -this.halfDirection.y : this.halfDirection.y;
  98963. d = this.halfDirection.z < 0 ? -this.halfDirection.z : this.halfDirection.z;
  98964. w = wx < 0 ? w - wx : w + wx;
  98965. h = hy < 0 ? h - hy : h + hy;
  98966. d = dz < 0 ? d - dz : d + dz;
  98967. p = OIMO.AABB_PROX;
  98968. this.aabb.set(
  98969. this.position.x - w - p, this.position.x + w + p,
  98970. this.position.y - h - p, this.position.y + h + p,
  98971. this.position.z - d - p, this.position.z + d + p
  98972. );
  98973. if (this.proxy != null) this.proxy.update();
  98974. };
  98975. /**
  98976. * A tetra shape.
  98977. * @author xprogram
  98978. */
  98979. OIMO.TetraShape = function (config, p1, p2, p3, p4) {
  98980. OIMO.Shape.call(this, config);
  98981. this.type = OIMO.SHAPE_TETRA;
  98982. // Vertices and faces of tetra
  98983. this.verts = [p1, p2, p3, p4];
  98984. this.faces = [
  98985. mtri(0, 1, 2),
  98986. mtri(1, 2, 3),
  98987. mtri(2, 3, 4),
  98988. mtri(4, 0, 1),
  98989. ];
  98990. };
  98991. OIMO.TetraShape.prototype = Object.create(OIMO.Shape.prototype);
  98992. OIMO.TetraShape.prototype.constructor = OIMO.TetraShape;
  98993. OIMO.TetraShape.prototype.calculateMassInfo = function () {
  98994. // I guess you could calculate box mass and split it
  98995. // in half for the tetra...
  98996. };
  98997. OIMO.TetraShape.prototype.updateProxy = function () {
  98998. this.aabb.setFromPoints(this.verts);
  98999. if (this.proxy !== null)
  99000. this.proxy.update();
  99001. };
  99002. function mtri(a, b, c) {
  99003. return { a: a, b: b, c: c };
  99004. }
  99005. OIMO.CollisionDetector = function () {
  99006. this.flip = false;
  99007. };
  99008. OIMO.CollisionDetector.prototype = {
  99009. constructor: OIMO.CollisionDetector,
  99010. detectCollision: function (shape1, shape2, manifold) {
  99011. OIMO.Error("CollisionDetector", "Inheritance error.");
  99012. }
  99013. };
  99014. /**
  99015. * A collision detector which detects collisions between two boxes.
  99016. * @author saharan
  99017. */
  99018. OIMO.BoxBoxCollisionDetector = function () {
  99019. OIMO.CollisionDetector.call(this);
  99020. this.clipVertices1 = new OIMO_ARRAY_TYPE(24); // 8 vertices x,y,z
  99021. this.clipVertices2 = new OIMO_ARRAY_TYPE(24);
  99022. this.used = new OIMO_ARRAY_TYPE(8);
  99023. this.INF = 1 / 0;
  99024. };
  99025. OIMO.BoxBoxCollisionDetector.prototype = Object.create(OIMO.CollisionDetector.prototype);
  99026. OIMO.BoxBoxCollisionDetector.prototype.constructor = OIMO.BoxBoxCollisionDetector;
  99027. OIMO.BoxBoxCollisionDetector.prototype.detectCollision = function (shape1, shape2, manifold) {
  99028. // What you are doing
  99029. // · I to prepare a separate axis of the fifteen
  99030. //-Six in each of three normal vectors of the xyz direction of the box both
  99031. // · Remaining nine 3x3 a vector perpendicular to the side of the box 2 and the side of the box 1
  99032. // · Calculate the depth to the separation axis
  99033. // Calculates the distance using the inner product and put the amount of embedment
  99034. // · However a vertical separation axis and side to weight a little to avoid vibration
  99035. // And end when there is a separate axis that is remote even one
  99036. // · I look for separation axis with little to dent most
  99037. // Men and if separation axis of the first six - end collision
  99038. // Heng If it separate axis of nine other - side collision
  99039. // Heng - case of a side collision
  99040. // · Find points of two sides on which you made ​​the separation axis
  99041. // Calculates the point of closest approach of a straight line consisting of separate axis points obtained, and the collision point
  99042. //-Surface - the case of the plane crash
  99043. //-Box A, box B and the other a box of better made ​​a separate axis
  99044. // • 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
  99045. // When viewed from the front surface A, and the cut part exceeding the area of the surface A is a surface B
  99046. //-Plane B becomes the 3-8 triangle, I a candidate for the collision point the vertex of surface B
  99047. // • If more than one candidate 5 exists, scraping up to four
  99048. // For potential collision points of all, to examine the distance between the surface A
  99049. // • If you were on the inside surface of A, and the collision point
  99050. var b1;
  99051. var b2;
  99052. if (shape1.id < shape2.id) {
  99053. b1 = (shape1);
  99054. b2 = (shape2);
  99055. } else {
  99056. b1 = (shape2);
  99057. b2 = (shape1);
  99058. }
  99059. var V1 = b1.elements;
  99060. var V2 = b2.elements;
  99061. var D1 = b1.dimentions;
  99062. var D2 = b2.dimentions;
  99063. var p1 = b1.position;
  99064. var p2 = b2.position;
  99065. var p1x = p1.x;
  99066. var p1y = p1.y;
  99067. var p1z = p1.z;
  99068. var p2x = p2.x;
  99069. var p2y = p2.y;
  99070. var p2z = p2.z;
  99071. // diff
  99072. var dx = p2x - p1x;
  99073. var dy = p2y - p1y;
  99074. var dz = p2z - p1z;
  99075. // distance
  99076. var w1 = b1.halfWidth;
  99077. var h1 = b1.halfHeight;
  99078. var d1 = b1.halfDepth;
  99079. var w2 = b2.halfWidth;
  99080. var h2 = b2.halfHeight;
  99081. var d2 = b2.halfDepth;
  99082. // direction
  99083. // ----------------------------
  99084. // 15 separating axes
  99085. // 1~6: face
  99086. // 7~f: edge
  99087. // http://marupeke296.com/COL_3D_No13_OBBvsOBB.html
  99088. // ----------------------------
  99089. var a1x = D1[0];
  99090. var a1y = D1[1];
  99091. var a1z = D1[2];
  99092. var a2x = D1[3];
  99093. var a2y = D1[4];
  99094. var a2z = D1[5];
  99095. var a3x = D1[6];
  99096. var a3y = D1[7];
  99097. var a3z = D1[8];
  99098. var d1x = D1[9];
  99099. var d1y = D1[10];
  99100. var d1z = D1[11];
  99101. var d2x = D1[12];
  99102. var d2y = D1[13];
  99103. var d2z = D1[14];
  99104. var d3x = D1[15];
  99105. var d3y = D1[16];
  99106. var d3z = D1[17];
  99107. var a4x = D2[0];
  99108. var a4y = D2[1];
  99109. var a4z = D2[2];
  99110. var a5x = D2[3];
  99111. var a5y = D2[4];
  99112. var a5z = D2[5];
  99113. var a6x = D2[6];
  99114. var a6y = D2[7];
  99115. var a6z = D2[8];
  99116. var d4x = D2[9];
  99117. var d4y = D2[10];
  99118. var d4z = D2[11];
  99119. var d5x = D2[12];
  99120. var d5y = D2[13];
  99121. var d5z = D2[14];
  99122. var d6x = D2[15];
  99123. var d6y = D2[16];
  99124. var d6z = D2[17];
  99125. var a7x = a1y * a4z - a1z * a4y;
  99126. var a7y = a1z * a4x - a1x * a4z;
  99127. var a7z = a1x * a4y - a1y * a4x;
  99128. var a8x = a1y * a5z - a1z * a5y;
  99129. var a8y = a1z * a5x - a1x * a5z;
  99130. var a8z = a1x * a5y - a1y * a5x;
  99131. var a9x = a1y * a6z - a1z * a6y;
  99132. var a9y = a1z * a6x - a1x * a6z;
  99133. var a9z = a1x * a6y - a1y * a6x;
  99134. var aax = a2y * a4z - a2z * a4y;
  99135. var aay = a2z * a4x - a2x * a4z;
  99136. var aaz = a2x * a4y - a2y * a4x;
  99137. var abx = a2y * a5z - a2z * a5y;
  99138. var aby = a2z * a5x - a2x * a5z;
  99139. var abz = a2x * a5y - a2y * a5x;
  99140. var acx = a2y * a6z - a2z * a6y;
  99141. var acy = a2z * a6x - a2x * a6z;
  99142. var acz = a2x * a6y - a2y * a6x;
  99143. var adx = a3y * a4z - a3z * a4y;
  99144. var ady = a3z * a4x - a3x * a4z;
  99145. var adz = a3x * a4y - a3y * a4x;
  99146. var aex = a3y * a5z - a3z * a5y;
  99147. var aey = a3z * a5x - a3x * a5z;
  99148. var aez = a3x * a5y - a3y * a5x;
  99149. var afx = a3y * a6z - a3z * a6y;
  99150. var afy = a3z * a6x - a3x * a6z;
  99151. var afz = a3x * a6y - a3y * a6x;
  99152. // right or left flags
  99153. var right1;
  99154. var right2;
  99155. var right3;
  99156. var right4;
  99157. var right5;
  99158. var right6;
  99159. var right7;
  99160. var right8;
  99161. var right9;
  99162. var righta;
  99163. var rightb;
  99164. var rightc;
  99165. var rightd;
  99166. var righte;
  99167. var rightf;
  99168. // overlapping distances
  99169. var overlap1;
  99170. var overlap2;
  99171. var overlap3;
  99172. var overlap4;
  99173. var overlap5;
  99174. var overlap6;
  99175. var overlap7;
  99176. var overlap8;
  99177. var overlap9;
  99178. var overlapa;
  99179. var overlapb;
  99180. var overlapc;
  99181. var overlapd;
  99182. var overlape;
  99183. var overlapf;
  99184. // invalid flags
  99185. var invalid7 = false;
  99186. var invalid8 = false;
  99187. var invalid9 = false;
  99188. var invalida = false;
  99189. var invalidb = false;
  99190. var invalidc = false;
  99191. var invalidd = false;
  99192. var invalide = false;
  99193. var invalidf = false;
  99194. // temporary variables
  99195. var len;
  99196. var len1;
  99197. var len2;
  99198. var dot1;
  99199. var dot2;
  99200. var dot3;
  99201. // try axis 1
  99202. len = a1x * dx + a1y * dy + a1z * dz;
  99203. right1 = len > 0;
  99204. if (!right1) len = -len;
  99205. len1 = w1;
  99206. dot1 = a1x * a4x + a1y * a4y + a1z * a4z;
  99207. dot2 = a1x * a5x + a1y * a5y + a1z * a5z;
  99208. dot3 = a1x * a6x + a1y * a6y + a1z * a6z;
  99209. if (dot1 < 0) dot1 = -dot1;
  99210. if (dot2 < 0) dot2 = -dot2;
  99211. if (dot3 < 0) dot3 = -dot3;
  99212. len2 = dot1 * w2 + dot2 * h2 + dot3 * d2;
  99213. overlap1 = len - len1 - len2;
  99214. if (overlap1 > 0) return;
  99215. // try axis 2
  99216. len = a2x * dx + a2y * dy + a2z * dz;
  99217. right2 = len > 0;
  99218. if (!right2) len = -len;
  99219. len1 = h1;
  99220. dot1 = a2x * a4x + a2y * a4y + a2z * a4z;
  99221. dot2 = a2x * a5x + a2y * a5y + a2z * a5z;
  99222. dot3 = a2x * a6x + a2y * a6y + a2z * a6z;
  99223. if (dot1 < 0) dot1 = -dot1;
  99224. if (dot2 < 0) dot2 = -dot2;
  99225. if (dot3 < 0) dot3 = -dot3;
  99226. len2 = dot1 * w2 + dot2 * h2 + dot3 * d2;
  99227. overlap2 = len - len1 - len2;
  99228. if (overlap2 > 0) return;
  99229. // try axis 3
  99230. len = a3x * dx + a3y * dy + a3z * dz;
  99231. right3 = len > 0;
  99232. if (!right3) len = -len;
  99233. len1 = d1;
  99234. dot1 = a3x * a4x + a3y * a4y + a3z * a4z;
  99235. dot2 = a3x * a5x + a3y * a5y + a3z * a5z;
  99236. dot3 = a3x * a6x + a3y * a6y + a3z * a6z;
  99237. if (dot1 < 0) dot1 = -dot1;
  99238. if (dot2 < 0) dot2 = -dot2;
  99239. if (dot3 < 0) dot3 = -dot3;
  99240. len2 = dot1 * w2 + dot2 * h2 + dot3 * d2;
  99241. overlap3 = len - len1 - len2;
  99242. if (overlap3 > 0) return;
  99243. // try axis 4
  99244. len = a4x * dx + a4y * dy + a4z * dz;
  99245. right4 = len > 0;
  99246. if (!right4) len = -len;
  99247. dot1 = a4x * a1x + a4y * a1y + a4z * a1z;
  99248. dot2 = a4x * a2x + a4y * a2y + a4z * a2z;
  99249. dot3 = a4x * a3x + a4y * a3y + a4z * a3z;
  99250. if (dot1 < 0) dot1 = -dot1;
  99251. if (dot2 < 0) dot2 = -dot2;
  99252. if (dot3 < 0) dot3 = -dot3;
  99253. len1 = dot1 * w1 + dot2 * h1 + dot3 * d1;
  99254. len2 = w2;
  99255. overlap4 = (len - len1 - len2) * 1.0;
  99256. if (overlap4 > 0) return;
  99257. // try axis 5
  99258. len = a5x * dx + a5y * dy + a5z * dz;
  99259. right5 = len > 0;
  99260. if (!right5) len = -len;
  99261. dot1 = a5x * a1x + a5y * a1y + a5z * a1z;
  99262. dot2 = a5x * a2x + a5y * a2y + a5z * a2z;
  99263. dot3 = a5x * a3x + a5y * a3y + a5z * a3z;
  99264. if (dot1 < 0) dot1 = -dot1;
  99265. if (dot2 < 0) dot2 = -dot2;
  99266. if (dot3 < 0) dot3 = -dot3;
  99267. len1 = dot1 * w1 + dot2 * h1 + dot3 * d1;
  99268. len2 = h2;
  99269. overlap5 = (len - len1 - len2) * 1.0;
  99270. if (overlap5 > 0) return;
  99271. // try axis 6
  99272. len = a6x * dx + a6y * dy + a6z * dz;
  99273. right6 = len > 0;
  99274. if (!right6) len = -len;
  99275. dot1 = a6x * a1x + a6y * a1y + a6z * a1z;
  99276. dot2 = a6x * a2x + a6y * a2y + a6z * a2z;
  99277. dot3 = a6x * a3x + a6y * a3y + a6z * a3z;
  99278. if (dot1 < 0) dot1 = -dot1;
  99279. if (dot2 < 0) dot2 = -dot2;
  99280. if (dot3 < 0) dot3 = -dot3;
  99281. len1 = dot1 * w1 + dot2 * h1 + dot3 * d1;
  99282. len2 = d2;
  99283. overlap6 = (len - len1 - len2) * 1.0;
  99284. if (overlap6 > 0) return;
  99285. // try axis 7
  99286. len = a7x * a7x + a7y * a7y + a7z * a7z;
  99287. if (len > 1e-5) {
  99288. len = 1 / OIMO.sqrt(len);
  99289. a7x *= len;
  99290. a7y *= len;
  99291. a7z *= len;
  99292. len = a7x * dx + a7y * dy + a7z * dz;
  99293. right7 = len > 0;
  99294. if (!right7) len = -len;
  99295. dot1 = a7x * a2x + a7y * a2y + a7z * a2z;
  99296. dot2 = a7x * a3x + a7y * a3y + a7z * a3z;
  99297. if (dot1 < 0) dot1 = -dot1;
  99298. if (dot2 < 0) dot2 = -dot2;
  99299. len1 = dot1 * h1 + dot2 * d1;
  99300. dot1 = a7x * a5x + a7y * a5y + a7z * a5z;
  99301. dot2 = a7x * a6x + a7y * a6y + a7z * a6z;
  99302. if (dot1 < 0) dot1 = -dot1;
  99303. if (dot2 < 0) dot2 = -dot2;
  99304. len2 = dot1 * h2 + dot2 * d2;
  99305. overlap7 = len - len1 - len2;
  99306. if (overlap7 > 0) return;
  99307. } else {
  99308. right7 = false;
  99309. overlap7 = 0;
  99310. invalid7 = true;
  99311. }
  99312. // try axis 8
  99313. len = a8x * a8x + a8y * a8y + a8z * a8z;
  99314. if (len > 1e-5) {
  99315. len = 1 / OIMO.sqrt(len);
  99316. a8x *= len;
  99317. a8y *= len;
  99318. a8z *= len;
  99319. len = a8x * dx + a8y * dy + a8z * dz;
  99320. right8 = len > 0;
  99321. if (!right8) len = -len;
  99322. dot1 = a8x * a2x + a8y * a2y + a8z * a2z;
  99323. dot2 = a8x * a3x + a8y * a3y + a8z * a3z;
  99324. if (dot1 < 0) dot1 = -dot1;
  99325. if (dot2 < 0) dot2 = -dot2;
  99326. len1 = dot1 * h1 + dot2 * d1;
  99327. dot1 = a8x * a4x + a8y * a4y + a8z * a4z;
  99328. dot2 = a8x * a6x + a8y * a6y + a8z * a6z;
  99329. if (dot1 < 0) dot1 = -dot1;
  99330. if (dot2 < 0) dot2 = -dot2;
  99331. len2 = dot1 * w2 + dot2 * d2;
  99332. overlap8 = len - len1 - len2;
  99333. if (overlap8 > 0) return;
  99334. } else {
  99335. right8 = false;
  99336. overlap8 = 0;
  99337. invalid8 = true;
  99338. }
  99339. // try axis 9
  99340. len = a9x * a9x + a9y * a9y + a9z * a9z;
  99341. if (len > 1e-5) {
  99342. len = 1 / OIMO.sqrt(len);
  99343. a9x *= len;
  99344. a9y *= len;
  99345. a9z *= len;
  99346. len = a9x * dx + a9y * dy + a9z * dz;
  99347. right9 = len > 0;
  99348. if (!right9) len = -len;
  99349. dot1 = a9x * a2x + a9y * a2y + a9z * a2z;
  99350. dot2 = a9x * a3x + a9y * a3y + a9z * a3z;
  99351. if (dot1 < 0) dot1 = -dot1;
  99352. if (dot2 < 0) dot2 = -dot2;
  99353. len1 = dot1 * h1 + dot2 * d1;
  99354. dot1 = a9x * a4x + a9y * a4y + a9z * a4z;
  99355. dot2 = a9x * a5x + a9y * a5y + a9z * a5z;
  99356. if (dot1 < 0) dot1 = -dot1;
  99357. if (dot2 < 0) dot2 = -dot2;
  99358. len2 = dot1 * w2 + dot2 * h2;
  99359. overlap9 = len - len1 - len2;
  99360. if (overlap9 > 0) return;
  99361. } else {
  99362. right9 = false;
  99363. overlap9 = 0;
  99364. invalid9 = true;
  99365. }
  99366. // try axis 10
  99367. len = aax * aax + aay * aay + aaz * aaz;
  99368. if (len > 1e-5) {
  99369. len = 1 / OIMO.sqrt(len);
  99370. aax *= len;
  99371. aay *= len;
  99372. aaz *= len;
  99373. len = aax * dx + aay * dy + aaz * dz;
  99374. righta = len > 0;
  99375. if (!righta) len = -len;
  99376. dot1 = aax * a1x + aay * a1y + aaz * a1z;
  99377. dot2 = aax * a3x + aay * a3y + aaz * a3z;
  99378. if (dot1 < 0) dot1 = -dot1;
  99379. if (dot2 < 0) dot2 = -dot2;
  99380. len1 = dot1 * w1 + dot2 * d1;
  99381. dot1 = aax * a5x + aay * a5y + aaz * a5z;
  99382. dot2 = aax * a6x + aay * a6y + aaz * a6z;
  99383. if (dot1 < 0) dot1 = -dot1;
  99384. if (dot2 < 0) dot2 = -dot2;
  99385. len2 = dot1 * h2 + dot2 * d2;
  99386. overlapa = len - len1 - len2;
  99387. if (overlapa > 0) return;
  99388. } else {
  99389. righta = false;
  99390. overlapa = 0;
  99391. invalida = true;
  99392. }
  99393. // try axis 11
  99394. len = abx * abx + aby * aby + abz * abz;
  99395. if (len > 1e-5) {
  99396. len = 1 / OIMO.sqrt(len);
  99397. abx *= len;
  99398. aby *= len;
  99399. abz *= len;
  99400. len = abx * dx + aby * dy + abz * dz;
  99401. rightb = len > 0;
  99402. if (!rightb) len = -len;
  99403. dot1 = abx * a1x + aby * a1y + abz * a1z;
  99404. dot2 = abx * a3x + aby * a3y + abz * a3z;
  99405. if (dot1 < 0) dot1 = -dot1;
  99406. if (dot2 < 0) dot2 = -dot2;
  99407. len1 = dot1 * w1 + dot2 * d1;
  99408. dot1 = abx * a4x + aby * a4y + abz * a4z;
  99409. dot2 = abx * a6x + aby * a6y + abz * a6z;
  99410. if (dot1 < 0) dot1 = -dot1;
  99411. if (dot2 < 0) dot2 = -dot2;
  99412. len2 = dot1 * w2 + dot2 * d2;
  99413. overlapb = len - len1 - len2;
  99414. if (overlapb > 0) return;
  99415. } else {
  99416. rightb = false;
  99417. overlapb = 0;
  99418. invalidb = true;
  99419. }
  99420. // try axis 12
  99421. len = acx * acx + acy * acy + acz * acz;
  99422. if (len > 1e-5) {
  99423. len = 1 / OIMO.sqrt(len);
  99424. acx *= len;
  99425. acy *= len;
  99426. acz *= len;
  99427. len = acx * dx + acy * dy + acz * dz;
  99428. rightc = len > 0;
  99429. if (!rightc) len = -len;
  99430. dot1 = acx * a1x + acy * a1y + acz * a1z;
  99431. dot2 = acx * a3x + acy * a3y + acz * a3z;
  99432. if (dot1 < 0) dot1 = -dot1;
  99433. if (dot2 < 0) dot2 = -dot2;
  99434. len1 = dot1 * w1 + dot2 * d1;
  99435. dot1 = acx * a4x + acy * a4y + acz * a4z;
  99436. dot2 = acx * a5x + acy * a5y + acz * a5z;
  99437. if (dot1 < 0) dot1 = -dot1;
  99438. if (dot2 < 0) dot2 = -dot2;
  99439. len2 = dot1 * w2 + dot2 * h2;
  99440. overlapc = len - len1 - len2;
  99441. if (overlapc > 0) return;
  99442. } else {
  99443. rightc = false;
  99444. overlapc = 0;
  99445. invalidc = true;
  99446. }
  99447. // try axis 13
  99448. len = adx * adx + ady * ady + adz * adz;
  99449. if (len > 1e-5) {
  99450. len = 1 / OIMO.sqrt(len);
  99451. adx *= len;
  99452. ady *= len;
  99453. adz *= len;
  99454. len = adx * dx + ady * dy + adz * dz;
  99455. rightd = len > 0;
  99456. if (!rightd) len = -len;
  99457. dot1 = adx * a1x + ady * a1y + adz * a1z;
  99458. dot2 = adx * a2x + ady * a2y + adz * a2z;
  99459. if (dot1 < 0) dot1 = -dot1;
  99460. if (dot2 < 0) dot2 = -dot2;
  99461. len1 = dot1 * w1 + dot2 * h1;
  99462. dot1 = adx * a5x + ady * a5y + adz * a5z;
  99463. dot2 = adx * a6x + ady * a6y + adz * a6z;
  99464. if (dot1 < 0) dot1 = -dot1;
  99465. if (dot2 < 0) dot2 = -dot2;
  99466. len2 = dot1 * h2 + dot2 * d2;
  99467. overlapd = len - len1 - len2;
  99468. if (overlapd > 0) return;
  99469. } else {
  99470. rightd = false;
  99471. overlapd = 0;
  99472. invalidd = true;
  99473. }
  99474. // try axis 14
  99475. len = aex * aex + aey * aey + aez * aez;
  99476. if (len > 1e-5) {
  99477. len = 1 / OIMO.sqrt(len);
  99478. aex *= len;
  99479. aey *= len;
  99480. aez *= len;
  99481. len = aex * dx + aey * dy + aez * dz;
  99482. righte = len > 0;
  99483. if (!righte) len = -len;
  99484. dot1 = aex * a1x + aey * a1y + aez * a1z;
  99485. dot2 = aex * a2x + aey * a2y + aez * a2z;
  99486. if (dot1 < 0) dot1 = -dot1;
  99487. if (dot2 < 0) dot2 = -dot2;
  99488. len1 = dot1 * w1 + dot2 * h1;
  99489. dot1 = aex * a4x + aey * a4y + aez * a4z;
  99490. dot2 = aex * a6x + aey * a6y + aez * a6z;
  99491. if (dot1 < 0) dot1 = -dot1;
  99492. if (dot2 < 0) dot2 = -dot2;
  99493. len2 = dot1 * w2 + dot2 * d2;
  99494. overlape = len - len1 - len2;
  99495. if (overlape > 0) return;
  99496. } else {
  99497. righte = false;
  99498. overlape = 0;
  99499. invalide = true;
  99500. }
  99501. // try axis 15
  99502. len = afx * afx + afy * afy + afz * afz;
  99503. if (len > 1e-5) {
  99504. len = 1 / OIMO.sqrt(len);
  99505. afx *= len;
  99506. afy *= len;
  99507. afz *= len;
  99508. len = afx * dx + afy * dy + afz * dz;
  99509. rightf = len > 0;
  99510. if (!rightf) len = -len;
  99511. dot1 = afx * a1x + afy * a1y + afz * a1z;
  99512. dot2 = afx * a2x + afy * a2y + afz * a2z;
  99513. if (dot1 < 0) dot1 = -dot1;
  99514. if (dot2 < 0) dot2 = -dot2;
  99515. len1 = dot1 * w1 + dot2 * h1;
  99516. dot1 = afx * a4x + afy * a4y + afz * a4z;
  99517. dot2 = afx * a5x + afy * a5y + afz * a5z;
  99518. if (dot1 < 0) dot1 = -dot1;
  99519. if (dot2 < 0) dot2 = -dot2;
  99520. len2 = dot1 * w2 + dot2 * h2;
  99521. overlapf = len - len1 - len2;
  99522. if (overlapf > 0) return;
  99523. } else {
  99524. rightf = false;
  99525. overlapf = 0;
  99526. invalidf = true;
  99527. }
  99528. // boxes are overlapping
  99529. var depth = overlap1;
  99530. var depth2 = overlap1;
  99531. var minIndex = 0;
  99532. var right = right1;
  99533. if (overlap2 > depth2) {
  99534. depth = overlap2;
  99535. depth2 = overlap2;
  99536. minIndex = 1;
  99537. right = right2;
  99538. }
  99539. if (overlap3 > depth2) {
  99540. depth = overlap3;
  99541. depth2 = overlap3;
  99542. minIndex = 2;
  99543. right = right3;
  99544. }
  99545. if (overlap4 > depth2) {
  99546. depth = overlap4;
  99547. depth2 = overlap4;
  99548. minIndex = 3;
  99549. right = right4;
  99550. }
  99551. if (overlap5 > depth2) {
  99552. depth = overlap5;
  99553. depth2 = overlap5;
  99554. minIndex = 4;
  99555. right = right5;
  99556. }
  99557. if (overlap6 > depth2) {
  99558. depth = overlap6;
  99559. depth2 = overlap6;
  99560. minIndex = 5;
  99561. right = right6;
  99562. }
  99563. if (overlap7 - 0.01 > depth2 && !invalid7) {
  99564. depth = overlap7;
  99565. depth2 = overlap7 - 0.01;
  99566. minIndex = 6;
  99567. right = right7;
  99568. }
  99569. if (overlap8 - 0.01 > depth2 && !invalid8) {
  99570. depth = overlap8;
  99571. depth2 = overlap8 - 0.01;
  99572. minIndex = 7;
  99573. right = right8;
  99574. }
  99575. if (overlap9 - 0.01 > depth2 && !invalid9) {
  99576. depth = overlap9;
  99577. depth2 = overlap9 - 0.01;
  99578. minIndex = 8;
  99579. right = right9;
  99580. }
  99581. if (overlapa - 0.01 > depth2 && !invalida) {
  99582. depth = overlapa;
  99583. depth2 = overlapa - 0.01;
  99584. minIndex = 9;
  99585. right = righta;
  99586. }
  99587. if (overlapb - 0.01 > depth2 && !invalidb) {
  99588. depth = overlapb;
  99589. depth2 = overlapb - 0.01;
  99590. minIndex = 10;
  99591. right = rightb;
  99592. }
  99593. if (overlapc - 0.01 > depth2 && !invalidc) {
  99594. depth = overlapc;
  99595. depth2 = overlapc - 0.01;
  99596. minIndex = 11;
  99597. right = rightc;
  99598. }
  99599. if (overlapd - 0.01 > depth2 && !invalidd) {
  99600. depth = overlapd;
  99601. depth2 = overlapd - 0.01;
  99602. minIndex = 12;
  99603. right = rightd;
  99604. }
  99605. if (overlape - 0.01 > depth2 && !invalide) {
  99606. depth = overlape;
  99607. depth2 = overlape - 0.01;
  99608. minIndex = 13;
  99609. right = righte;
  99610. }
  99611. if (overlapf - 0.01 > depth2 && !invalidf) {
  99612. depth = overlapf;
  99613. minIndex = 14;
  99614. right = rightf;
  99615. }
  99616. // normal
  99617. var nx = 0;
  99618. var ny = 0;
  99619. var nz = 0;
  99620. // edge line or face side normal
  99621. var n1x = 0;
  99622. var n1y = 0;
  99623. var n1z = 0;
  99624. var n2x = 0;
  99625. var n2y = 0;
  99626. var n2z = 0;
  99627. // center of current face
  99628. var cx = 0;
  99629. var cy = 0;
  99630. var cz = 0;
  99631. // face side
  99632. var s1x = 0;
  99633. var s1y = 0;
  99634. var s1z = 0;
  99635. var s2x = 0;
  99636. var s2y = 0;
  99637. var s2z = 0;
  99638. // swap b1 b2
  99639. var swap = false;
  99640. //_______________________________________
  99641. if (minIndex == 0) {// b1.x * b2
  99642. if (right) {
  99643. cx = p1x + d1x; cy = p1y + d1y; cz = p1z + d1z;
  99644. nx = a1x; ny = a1y; nz = a1z;
  99645. } else {
  99646. cx = p1x - d1x; cy = p1y - d1y; cz = p1z - d1z;
  99647. nx = -a1x; ny = -a1y; nz = -a1z;
  99648. }
  99649. s1x = d2x; s1y = d2y; s1z = d2z;
  99650. n1x = -a2x; n1y = -a2y; n1z = -a2z;
  99651. s2x = d3x; s2y = d3y; s2z = d3z;
  99652. n2x = -a3x; n2y = -a3y; n2z = -a3z;
  99653. }
  99654. else if (minIndex == 1) {// b1.y * b2
  99655. if (right) {
  99656. cx = p1x + d2x; cy = p1y + d2y; cz = p1z + d2z;
  99657. nx = a2x; ny = a2y; nz = a2z;
  99658. } else {
  99659. cx = p1x - d2x; cy = p1y - d2y; cz = p1z - d2z;
  99660. nx = -a2x; ny = -a2y; nz = -a2z;
  99661. }
  99662. s1x = d1x; s1y = d1y; s1z = d1z;
  99663. n1x = -a1x; n1y = -a1y; n1z = -a1z;
  99664. s2x = d3x; s2y = d3y; s2z = d3z;
  99665. n2x = -a3x; n2y = -a3y; n2z = -a3z;
  99666. }
  99667. else if (minIndex == 2) {// b1.z * b2
  99668. if (right) {
  99669. cx = p1x + d3x; cy = p1y + d3y; cz = p1z + d3z;
  99670. nx = a3x; ny = a3y; nz = a3z;
  99671. } else {
  99672. cx = p1x - d3x; cy = p1y - d3y; cz = p1z - d3z;
  99673. nx = -a3x; ny = -a3y; nz = -a3z;
  99674. }
  99675. s1x = d1x; s1y = d1y; s1z = d1z;
  99676. n1x = -a1x; n1y = -a1y; n1z = -a1z;
  99677. s2x = d2x; s2y = d2y; s2z = d2z;
  99678. n2x = -a2x; n2y = -a2y; n2z = -a2z;
  99679. }
  99680. else if (minIndex == 3) {// b2.x * b1
  99681. swap = true;
  99682. if (!right) {
  99683. cx = p2x + d4x; cy = p2y + d4y; cz = p2z + d4z;
  99684. nx = a4x; ny = a4y; nz = a4z;
  99685. } else {
  99686. cx = p2x - d4x; cy = p2y - d4y; cz = p2z - d4z;
  99687. nx = -a4x; ny = -a4y; nz = -a4z;
  99688. }
  99689. s1x = d5x; s1y = d5y; s1z = d5z;
  99690. n1x = -a5x; n1y = -a5y; n1z = -a5z;
  99691. s2x = d6x; s2y = d6y; s2z = d6z;
  99692. n2x = -a6x; n2y = -a6y; n2z = -a6z;
  99693. }
  99694. else if (minIndex == 4) {// b2.y * b1
  99695. swap = true;
  99696. if (!right) {
  99697. cx = p2x + d5x; cy = p2y + d5y; cz = p2z + d5z;
  99698. nx = a5x; ny = a5y; nz = a5z;
  99699. } else {
  99700. cx = p2x - d5x; cy = p2y - d5y; cz = p2z - d5z;
  99701. nx = -a5x; ny = -a5y; nz = -a5z;
  99702. }
  99703. s1x = d4x; s1y = d4y; s1z = d4z;
  99704. n1x = -a4x; n1y = -a4y; n1z = -a4z;
  99705. s2x = d6x; s2y = d6y; s2z = d6z;
  99706. n2x = -a6x; n2y = -a6y; n2z = -a6z;
  99707. }
  99708. else if (minIndex == 5) {// b2.z * b1
  99709. swap = true;
  99710. if (!right) {
  99711. cx = p2x + d6x; cy = p2y + d6y; cz = p2z + d6z;
  99712. nx = a6x; ny = a6y; nz = a6z;
  99713. } else {
  99714. cx = p2x - d6x; cy = p2y - d6y; cz = p2z - d6z;
  99715. nx = -a6x; ny = -a6y; nz = -a6z;
  99716. }
  99717. s1x = d4x; s1y = d4y; s1z = d4z;
  99718. n1x = -a4x; n1y = -a4y; n1z = -a4z;
  99719. s2x = d5x; s2y = d5y; s2z = d5z;
  99720. n2x = -a5x; n2y = -a5y; n2z = -a5z;
  99721. }
  99722. else if (minIndex == 6) {// b1.x * b2.x
  99723. nx = a7x; ny = a7y; nz = a7z;
  99724. n1x = a1x; n1y = a1y; n1z = a1z;
  99725. n2x = a4x; n2y = a4y; n2z = a4z;
  99726. }
  99727. else if (minIndex == 7) {// b1.x * b2.y
  99728. nx = a8x; ny = a8y; nz = a8z;
  99729. n1x = a1x; n1y = a1y; n1z = a1z;
  99730. n2x = a5x; n2y = a5y; n2z = a5z;
  99731. }
  99732. else if (minIndex == 8) {// b1.x * b2.z
  99733. nx = a9x; ny = a9y; nz = a9z;
  99734. n1x = a1x; n1y = a1y; n1z = a1z;
  99735. n2x = a6x; n2y = a6y; n2z = a6z;
  99736. }
  99737. else if (minIndex == 9) {// b1.y * b2.x
  99738. nx = aax; ny = aay; nz = aaz;
  99739. n1x = a2x; n1y = a2y; n1z = a2z;
  99740. n2x = a4x; n2y = a4y; n2z = a4z
  99741. }
  99742. else if (minIndex == 10) {// b1.y * b2.y
  99743. nx = abx; ny = aby; nz = abz;
  99744. n1x = a2x; n1y = a2y; n1z = a2z;
  99745. n2x = a5x; n2y = a5y; n2z = a5z;
  99746. }
  99747. else if (minIndex == 11) {// b1.y * b2.z
  99748. nx = acx; ny = acy; nz = acz;
  99749. n1x = a2x; n1y = a2y; n1z = a2z;
  99750. n2x = a6x; n2y = a6y; n2z = a6z;
  99751. }
  99752. else if (minIndex == 12) {// b1.z * b2.x
  99753. nx = adx; ny = ady; nz = adz;
  99754. n1x = a3x; n1y = a3y; n1z = a3z;
  99755. n2x = a4x; n2y = a4y; n2z = a4z;
  99756. }
  99757. else if (minIndex == 13) {// b1.z * b2.y
  99758. nx = aex; ny = aey; nz = aez;
  99759. n1x = a3x; n1y = a3y; n1z = a3z;
  99760. n2x = a5x; n2y = a5y; n2z = a5z;
  99761. }
  99762. else if (minIndex == 14) {// b1.z * b2.z
  99763. nx = afx; ny = afy; nz = afz;
  99764. n1x = a3x; n1y = a3y; n1z = a3z;
  99765. n2x = a6x; n2y = a6y; n2z = a6z;
  99766. }
  99767. //__________________________________________
  99768. var v;
  99769. if (minIndex > 5) {
  99770. if (!right) {
  99771. nx = -nx; ny = -ny; nz = -nz;
  99772. }
  99773. var distance;
  99774. var maxDistance;
  99775. var vx;
  99776. var vy;
  99777. var vz;
  99778. var v1x;
  99779. var v1y;
  99780. var v1z;
  99781. var v2x;
  99782. var v2y;
  99783. var v2z;
  99784. //vertex1;
  99785. v1x = V1[0]; v1y = V1[1]; v1z = V1[2];
  99786. maxDistance = nx * v1x + ny * v1y + nz * v1z;
  99787. //vertex2;
  99788. vx = V1[3]; vy = V1[4]; vz = V1[5];
  99789. distance = nx * vx + ny * vy + nz * vz;
  99790. if (distance > maxDistance) {
  99791. maxDistance = distance;
  99792. v1x = vx; v1y = vy; v1z = vz;
  99793. }
  99794. //vertex3;
  99795. vx = V1[6]; vy = V1[7]; vz = V1[8];
  99796. distance = nx * vx + ny * vy + nz * vz;
  99797. if (distance > maxDistance) {
  99798. maxDistance = distance;
  99799. v1x = vx; v1y = vy; v1z = vz;
  99800. }
  99801. //vertex4;
  99802. vx = V1[9]; vy = V1[10]; vz = V1[11];
  99803. distance = nx * vx + ny * vy + nz * vz;
  99804. if (distance > maxDistance) {
  99805. maxDistance = distance;
  99806. v1x = vx; v1y = vy; v1z = vz;
  99807. }
  99808. //vertex5;
  99809. vx = V1[12]; vy = V1[13]; vz = V1[14];
  99810. distance = nx * vx + ny * vy + nz * vz;
  99811. if (distance > maxDistance) {
  99812. maxDistance = distance;
  99813. v1x = vx; v1y = vy; v1z = vz;
  99814. }
  99815. //vertex6;
  99816. vx = V1[15]; vy = V1[16]; vz = V1[17];
  99817. distance = nx * vx + ny * vy + nz * vz;
  99818. if (distance > maxDistance) {
  99819. maxDistance = distance;
  99820. v1x = vx; v1y = vy; v1z = vz;
  99821. }
  99822. //vertex7;
  99823. vx = V1[18]; vy = V1[19]; vz = V1[20];
  99824. distance = nx * vx + ny * vy + nz * vz;
  99825. if (distance > maxDistance) {
  99826. maxDistance = distance;
  99827. v1x = vx; v1y = vy; v1z = vz;
  99828. }
  99829. //vertex8;
  99830. vx = V1[21]; vy = V1[22]; vz = V1[23];
  99831. distance = nx * vx + ny * vy + nz * vz;
  99832. if (distance > maxDistance) {
  99833. maxDistance = distance;
  99834. v1x = vx; v1y = vy; v1z = vz;
  99835. }
  99836. //vertex1;
  99837. v2x = V2[0]; v2y = V2[1]; v2z = V2[2];
  99838. maxDistance = nx * v2x + ny * v2y + nz * v2z;
  99839. //vertex2;
  99840. vx = V2[3]; vy = V2[4]; vz = V2[5];
  99841. distance = nx * vx + ny * vy + nz * vz;
  99842. if (distance < maxDistance) {
  99843. maxDistance = distance;
  99844. v2x = vx; v2y = vy; v2z = vz;
  99845. }
  99846. //vertex3;
  99847. vx = V2[6]; vy = V2[7]; vz = V2[8];
  99848. distance = nx * vx + ny * vy + nz * vz;
  99849. if (distance < maxDistance) {
  99850. maxDistance = distance;
  99851. v2x = vx; v2y = vy; v2z = vz;
  99852. }
  99853. //vertex4;
  99854. vx = V2[9]; vy = V2[10]; vz = V2[11];
  99855. distance = nx * vx + ny * vy + nz * vz;
  99856. if (distance < maxDistance) {
  99857. maxDistance = distance;
  99858. v2x = vx; v2y = vy; v2z = vz;
  99859. }
  99860. //vertex5;
  99861. vx = V2[12]; vy = V2[13]; vz = V2[14];
  99862. distance = nx * vx + ny * vy + nz * vz;
  99863. if (distance < maxDistance) {
  99864. maxDistance = distance;
  99865. v2x = vx; v2y = vy; v2z = vz;
  99866. }
  99867. //vertex6;
  99868. vx = V2[15]; vy = V2[16]; vz = V2[17];
  99869. distance = nx * vx + ny * vy + nz * vz;
  99870. if (distance < maxDistance) {
  99871. maxDistance = distance;
  99872. v2x = vx; v2y = vy; v2z = vz;
  99873. }
  99874. //vertex7;
  99875. vx = V2[18]; vy = V2[19]; vz = V2[20];
  99876. distance = nx * vx + ny * vy + nz * vz;
  99877. if (distance < maxDistance) {
  99878. maxDistance = distance;
  99879. v2x = vx; v2y = vy; v2z = vz;
  99880. }
  99881. //vertex8;
  99882. vx = V2[21]; vy = V2[22]; vz = V2[23];
  99883. distance = nx * vx + ny * vy + nz * vz;
  99884. if (distance < maxDistance) {
  99885. maxDistance = distance;
  99886. v2x = vx; v2y = vy; v2z = vz;
  99887. }
  99888. vx = v2x - v1x; vy = v2y - v1y; vz = v2z - v1z;
  99889. dot1 = n1x * n2x + n1y * n2y + n1z * n2z;
  99890. var t = (vx * (n1x - n2x * dot1) + vy * (n1y - n2y * dot1) + vz * (n1z - n2z * dot1)) / (1 - dot1 * dot1);
  99891. 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);
  99892. return;
  99893. }
  99894. // now detect face-face collision...
  99895. // target quad
  99896. var q1x;
  99897. var q1y;
  99898. var q1z;
  99899. var q2x;
  99900. var q2y;
  99901. var q2z;
  99902. var q3x;
  99903. var q3y;
  99904. var q3z;
  99905. var q4x;
  99906. var q4y;
  99907. var q4z;
  99908. // search support face and vertex
  99909. var minDot = 1;
  99910. var dot = 0;
  99911. var minDotIndex = 0;
  99912. if (swap) {
  99913. dot = a1x * nx + a1y * ny + a1z * nz;
  99914. if (dot < minDot) {
  99915. minDot = dot;
  99916. minDotIndex = 0;
  99917. }
  99918. if (-dot < minDot) {
  99919. minDot = -dot;
  99920. minDotIndex = 1;
  99921. }
  99922. dot = a2x * nx + a2y * ny + a2z * nz;
  99923. if (dot < minDot) {
  99924. minDot = dot;
  99925. minDotIndex = 2;
  99926. }
  99927. if (-dot < minDot) {
  99928. minDot = -dot;
  99929. minDotIndex = 3;
  99930. }
  99931. dot = a3x * nx + a3y * ny + a3z * nz;
  99932. if (dot < minDot) {
  99933. minDot = dot;
  99934. minDotIndex = 4;
  99935. }
  99936. if (-dot < minDot) {
  99937. minDot = -dot;
  99938. minDotIndex = 5;
  99939. }
  99940. if (minDotIndex == 0) {// x+ face
  99941. q1x = V1[0]; q1y = V1[1]; q1z = V1[2];//vertex1
  99942. q2x = V1[6]; q2y = V1[7]; q2z = V1[8];//vertex3
  99943. q3x = V1[9]; q3y = V1[10]; q3z = V1[11];//vertex4
  99944. q4x = V1[3]; q4y = V1[4]; q4z = V1[5];//vertex2
  99945. }
  99946. else if (minDotIndex == 1) {// x- face
  99947. q1x = V1[15]; q1y = V1[16]; q1z = V1[17];//vertex6
  99948. q2x = V1[21]; q2y = V1[22]; q2z = V1[23];//vertex8
  99949. q3x = V1[18]; q3y = V1[19]; q3z = V1[20];//vertex7
  99950. q4x = V1[12]; q4y = V1[13]; q4z = V1[14];//vertex5
  99951. }
  99952. else if (minDotIndex == 2) {// y+ face
  99953. q1x = V1[12]; q1y = V1[13]; q1z = V1[14];//vertex5
  99954. q2x = V1[0]; q2y = V1[1]; q2z = V1[2];//vertex1
  99955. q3x = V1[3]; q3y = V1[4]; q3z = V1[5];//vertex2
  99956. q4x = V1[15]; q4y = V1[16]; q4z = V1[17];//vertex6
  99957. }
  99958. else if (minDotIndex == 3) {// y- face
  99959. q1x = V1[21]; q1y = V1[22]; q1z = V1[23];//vertex8
  99960. q2x = V1[9]; q2y = V1[10]; q2z = V1[11];//vertex4
  99961. q3x = V1[6]; q3y = V1[7]; q3z = V1[8];//vertex3
  99962. q4x = V1[18]; q4y = V1[19]; q4z = V1[20];//vertex7
  99963. }
  99964. else if (minDotIndex == 4) {// z+ face
  99965. q1x = V1[12]; q1y = V1[13]; q1z = V1[14];//vertex5
  99966. q2x = V1[18]; q2y = V1[19]; q2z = V1[20];//vertex7
  99967. q3x = V1[6]; q3y = V1[7]; q3z = V1[8];//vertex3
  99968. q4x = V1[0]; q4y = V1[1]; q4z = V1[2];//vertex1
  99969. }
  99970. else if (minDotIndex == 5) {// z- face
  99971. q1x = V1[3]; q1y = V1[4]; q1z = V1[5];//vertex2
  99972. q2x = V1[6]; q2y = V1[7]; q2z = V1[8];//vertex4
  99973. q3x = V1[21]; q3y = V1[22]; q3z = V1[23];//vertex8
  99974. q4x = V1[15]; q4y = V1[16]; q4z = V1[17];//vertex6
  99975. }
  99976. } else {
  99977. dot = a4x * nx + a4y * ny + a4z * nz;
  99978. if (dot < minDot) {
  99979. minDot = dot;
  99980. minDotIndex = 0;
  99981. }
  99982. if (-dot < minDot) {
  99983. minDot = -dot;
  99984. minDotIndex = 1;
  99985. }
  99986. dot = a5x * nx + a5y * ny + a5z * nz;
  99987. if (dot < minDot) {
  99988. minDot = dot;
  99989. minDotIndex = 2;
  99990. }
  99991. if (-dot < minDot) {
  99992. minDot = -dot;
  99993. minDotIndex = 3;
  99994. }
  99995. dot = a6x * nx + a6y * ny + a6z * nz;
  99996. if (dot < minDot) {
  99997. minDot = dot;
  99998. minDotIndex = 4;
  99999. }
  100000. if (-dot < minDot) {
  100001. minDot = -dot;
  100002. minDotIndex = 5;
  100003. }
  100004. //______________________________________________________
  100005. if (minDotIndex == 0) {// x+ face
  100006. q1x = V2[0]; q1y = V2[1]; q1z = V2[2];//vertex1
  100007. q2x = V2[6]; q2y = V2[7]; q2z = V2[8];//vertex3
  100008. q3x = V2[9]; q3y = V2[10]; q3z = V2[11];//vertex4
  100009. q4x = V2[3]; q4y = V2[4]; q4z = V2[5];//vertex2
  100010. }
  100011. else if (minDotIndex == 1) {// x- face
  100012. q1x = V2[15]; q1y = V2[16]; q1z = V2[17];//vertex6
  100013. q2x = V2[21]; q2y = V2[22]; q2z = V2[23]; //vertex8
  100014. q3x = V2[18]; q3y = V2[19]; q3z = V2[20];//vertex7
  100015. q4x = V2[12]; q4y = V2[13]; q4z = V2[14];//vertex5
  100016. }
  100017. else if (minDotIndex == 2) {// y+ face
  100018. q1x = V2[12]; q1y = V2[13]; q1z = V2[14];//vertex5
  100019. q2x = V2[0]; q2y = V2[1]; q2z = V2[2];//vertex1
  100020. q3x = V2[3]; q3y = V2[4]; q3z = V2[5];//vertex2
  100021. q4x = V2[15]; q4y = V2[16]; q4z = V2[17];//vertex6
  100022. }
  100023. else if (minDotIndex == 3) {// y- face
  100024. q1x = V2[21]; q1y = V2[22]; q1z = V2[23];//vertex8
  100025. q2x = V2[9]; q2y = V2[10]; q2z = V2[11];//vertex4
  100026. q3x = V2[6]; q3y = V2[7]; q3z = V2[8];//vertex3
  100027. q4x = V2[18]; q4y = V2[19]; q4z = V2[20];//vertex7
  100028. }
  100029. else if (minDotIndex == 4) {// z+ face
  100030. q1x = V2[12]; q1y = V2[13]; q1z = V2[14];//vertex5
  100031. q2x = V2[18]; q2y = V2[19]; q2z = V2[20];//vertex7
  100032. q3x = V2[6]; q3y = V2[7]; q3z = V2[8];//vertex3
  100033. q4x = V2[0]; q4y = V2[1]; q4z = V2[2];//vertex1
  100034. }
  100035. else if (minDotIndex == 5) {// z- face
  100036. q1x = V2[3]; q1y = V2[4]; q1z = V2[5];//vertex2
  100037. q2x = V2[9]; q2y = V2[10]; q2z = V2[11];//vertex4
  100038. q3x = V2[21]; q3y = V2[22]; q3z = V2[23];//vertex8
  100039. q4x = V2[15]; q4y = V2[16]; q4z = V2[17];//vertex6
  100040. }
  100041. }
  100042. // clip vertices
  100043. var numClipVertices;
  100044. var numAddedClipVertices;
  100045. var index;
  100046. var x1;
  100047. var y1;
  100048. var z1;
  100049. var x2;
  100050. var y2;
  100051. var z2;
  100052. this.clipVertices1[0] = q1x;
  100053. this.clipVertices1[1] = q1y;
  100054. this.clipVertices1[2] = q1z;
  100055. this.clipVertices1[3] = q2x;
  100056. this.clipVertices1[4] = q2y;
  100057. this.clipVertices1[5] = q2z;
  100058. this.clipVertices1[6] = q3x;
  100059. this.clipVertices1[7] = q3y;
  100060. this.clipVertices1[8] = q3z;
  100061. this.clipVertices1[9] = q4x;
  100062. this.clipVertices1[10] = q4y;
  100063. this.clipVertices1[11] = q4z;
  100064. numAddedClipVertices = 0;
  100065. x1 = this.clipVertices1[9];
  100066. y1 = this.clipVertices1[10];
  100067. z1 = this.clipVertices1[11];
  100068. dot1 = (x1 - cx - s1x) * n1x + (y1 - cy - s1y) * n1y + (z1 - cz - s1z) * n1z;
  100069. //var i = 4;
  100070. //while(i--){
  100071. for (var i = 0; i < 4; i++) {
  100072. index = i * 3;
  100073. x2 = this.clipVertices1[index];
  100074. y2 = this.clipVertices1[index + 1];
  100075. z2 = this.clipVertices1[index + 2];
  100076. dot2 = (x2 - cx - s1x) * n1x + (y2 - cy - s1y) * n1y + (z2 - cz - s1z) * n1z;
  100077. if (dot1 > 0) {
  100078. if (dot2 > 0) {
  100079. index = numAddedClipVertices * 3;
  100080. numAddedClipVertices++;
  100081. this.clipVertices2[index] = x2;
  100082. this.clipVertices2[index + 1] = y2;
  100083. this.clipVertices2[index + 2] = z2;
  100084. } else {
  100085. index = numAddedClipVertices * 3;
  100086. numAddedClipVertices++;
  100087. t = dot1 / (dot1 - dot2);
  100088. this.clipVertices2[index] = x1 + (x2 - x1) * t;
  100089. this.clipVertices2[index + 1] = y1 + (y2 - y1) * t;
  100090. this.clipVertices2[index + 2] = z1 + (z2 - z1) * t;
  100091. }
  100092. } else {
  100093. if (dot2 > 0) {
  100094. index = numAddedClipVertices * 3;
  100095. numAddedClipVertices++;
  100096. t = dot1 / (dot1 - dot2);
  100097. this.clipVertices2[index] = x1 + (x2 - x1) * t;
  100098. this.clipVertices2[index + 1] = y1 + (y2 - y1) * t;
  100099. this.clipVertices2[index + 2] = z1 + (z2 - z1) * t;
  100100. index = numAddedClipVertices * 3;
  100101. numAddedClipVertices++;
  100102. this.clipVertices2[index] = x2;
  100103. this.clipVertices2[index + 1] = y2;
  100104. this.clipVertices2[index + 2] = z2;
  100105. }
  100106. }
  100107. x1 = x2;
  100108. y1 = y2;
  100109. z1 = z2;
  100110. dot1 = dot2;
  100111. }
  100112. numClipVertices = numAddedClipVertices;
  100113. if (numClipVertices == 0) return;
  100114. numAddedClipVertices = 0;
  100115. index = (numClipVertices - 1) * 3;
  100116. x1 = this.clipVertices2[index];
  100117. y1 = this.clipVertices2[index + 1];
  100118. z1 = this.clipVertices2[index + 2];
  100119. dot1 = (x1 - cx - s2x) * n2x + (y1 - cy - s2y) * n2y + (z1 - cz - s2z) * n2z;
  100120. //i = numClipVertices;
  100121. //while(i--){
  100122. for (i = 0; i < numClipVertices; i++) {
  100123. index = i * 3;
  100124. x2 = this.clipVertices2[index];
  100125. y2 = this.clipVertices2[index + 1];
  100126. z2 = this.clipVertices2[index + 2];
  100127. dot2 = (x2 - cx - s2x) * n2x + (y2 - cy - s2y) * n2y + (z2 - cz - s2z) * n2z;
  100128. if (dot1 > 0) {
  100129. if (dot2 > 0) {
  100130. index = numAddedClipVertices * 3;
  100131. numAddedClipVertices++;
  100132. this.clipVertices1[index] = x2;
  100133. this.clipVertices1[index + 1] = y2;
  100134. this.clipVertices1[index + 2] = z2;
  100135. } else {
  100136. index = numAddedClipVertices * 3;
  100137. numAddedClipVertices++;
  100138. t = dot1 / (dot1 - dot2);
  100139. this.clipVertices1[index] = x1 + (x2 - x1) * t;
  100140. this.clipVertices1[index + 1] = y1 + (y2 - y1) * t;
  100141. this.clipVertices1[index + 2] = z1 + (z2 - z1) * t;
  100142. }
  100143. } else {
  100144. if (dot2 > 0) {
  100145. index = numAddedClipVertices * 3;
  100146. numAddedClipVertices++;
  100147. t = dot1 / (dot1 - dot2);
  100148. this.clipVertices1[index] = x1 + (x2 - x1) * t;
  100149. this.clipVertices1[index + 1] = y1 + (y2 - y1) * t;
  100150. this.clipVertices1[index + 2] = z1 + (z2 - z1) * t;
  100151. index = numAddedClipVertices * 3;
  100152. numAddedClipVertices++;
  100153. this.clipVertices1[index] = x2;
  100154. this.clipVertices1[index + 1] = y2;
  100155. this.clipVertices1[index + 2] = z2;
  100156. }
  100157. }
  100158. x1 = x2;
  100159. y1 = y2;
  100160. z1 = z2;
  100161. dot1 = dot2;
  100162. }
  100163. numClipVertices = numAddedClipVertices;
  100164. if (numClipVertices == 0) return;
  100165. numAddedClipVertices = 0;
  100166. index = (numClipVertices - 1) * 3;
  100167. x1 = this.clipVertices1[index];
  100168. y1 = this.clipVertices1[index + 1];
  100169. z1 = this.clipVertices1[index + 2];
  100170. dot1 = (x1 - cx + s1x) * -n1x + (y1 - cy + s1y) * -n1y + (z1 - cz + s1z) * -n1z;
  100171. //i = numClipVertices;
  100172. //while(i--){
  100173. for (i = 0; i < numClipVertices; i++) {
  100174. index = i * 3;
  100175. x2 = this.clipVertices1[index];
  100176. y2 = this.clipVertices1[index + 1];
  100177. z2 = this.clipVertices1[index + 2];
  100178. dot2 = (x2 - cx + s1x) * -n1x + (y2 - cy + s1y) * -n1y + (z2 - cz + s1z) * -n1z;
  100179. if (dot1 > 0) {
  100180. if (dot2 > 0) {
  100181. index = numAddedClipVertices * 3;
  100182. numAddedClipVertices++;
  100183. this.clipVertices2[index] = x2;
  100184. this.clipVertices2[index + 1] = y2;
  100185. this.clipVertices2[index + 2] = z2;
  100186. } else {
  100187. index = numAddedClipVertices * 3;
  100188. numAddedClipVertices++;
  100189. t = dot1 / (dot1 - dot2);
  100190. this.clipVertices2[index] = x1 + (x2 - x1) * t;
  100191. this.clipVertices2[index + 1] = y1 + (y2 - y1) * t;
  100192. this.clipVertices2[index + 2] = z1 + (z2 - z1) * t;
  100193. }
  100194. } else {
  100195. if (dot2 > 0) {
  100196. index = numAddedClipVertices * 3;
  100197. numAddedClipVertices++;
  100198. t = dot1 / (dot1 - dot2);
  100199. this.clipVertices2[index] = x1 + (x2 - x1) * t;
  100200. this.clipVertices2[index + 1] = y1 + (y2 - y1) * t;
  100201. this.clipVertices2[index + 2] = z1 + (z2 - z1) * t;
  100202. index = numAddedClipVertices * 3;
  100203. numAddedClipVertices++;
  100204. this.clipVertices2[index] = x2;
  100205. this.clipVertices2[index + 1] = y2;
  100206. this.clipVertices2[index + 2] = z2;
  100207. }
  100208. }
  100209. x1 = x2;
  100210. y1 = y2;
  100211. z1 = z2;
  100212. dot1 = dot2;
  100213. }
  100214. numClipVertices = numAddedClipVertices;
  100215. if (numClipVertices == 0) return;
  100216. numAddedClipVertices = 0;
  100217. index = (numClipVertices - 1) * 3;
  100218. x1 = this.clipVertices2[index];
  100219. y1 = this.clipVertices2[index + 1];
  100220. z1 = this.clipVertices2[index + 2];
  100221. dot1 = (x1 - cx + s2x) * -n2x + (y1 - cy + s2y) * -n2y + (z1 - cz + s2z) * -n2z;
  100222. //i = numClipVertices;
  100223. //while(i--){
  100224. for (i = 0; i < numClipVertices; i++) {
  100225. index = i * 3;
  100226. x2 = this.clipVertices2[index];
  100227. y2 = this.clipVertices2[index + 1];
  100228. z2 = this.clipVertices2[index + 2];
  100229. dot2 = (x2 - cx + s2x) * -n2x + (y2 - cy + s2y) * -n2y + (z2 - cz + s2z) * -n2z;
  100230. if (dot1 > 0) {
  100231. if (dot2 > 0) {
  100232. index = numAddedClipVertices * 3;
  100233. numAddedClipVertices++;
  100234. this.clipVertices1[index] = x2;
  100235. this.clipVertices1[index + 1] = y2;
  100236. this.clipVertices1[index + 2] = z2;
  100237. } else {
  100238. index = numAddedClipVertices * 3;
  100239. numAddedClipVertices++;
  100240. t = dot1 / (dot1 - dot2);
  100241. this.clipVertices1[index] = x1 + (x2 - x1) * t;
  100242. this.clipVertices1[index + 1] = y1 + (y2 - y1) * t;
  100243. this.clipVertices1[index + 2] = z1 + (z2 - z1) * t;
  100244. }
  100245. } else {
  100246. if (dot2 > 0) {
  100247. index = numAddedClipVertices * 3;
  100248. numAddedClipVertices++;
  100249. t = dot1 / (dot1 - dot2);
  100250. this.clipVertices1[index] = x1 + (x2 - x1) * t;
  100251. this.clipVertices1[index + 1] = y1 + (y2 - y1) * t;
  100252. this.clipVertices1[index + 2] = z1 + (z2 - z1) * t;
  100253. index = numAddedClipVertices * 3;
  100254. numAddedClipVertices++;
  100255. this.clipVertices1[index] = x2;
  100256. this.clipVertices1[index + 1] = y2;
  100257. this.clipVertices1[index + 2] = z2;
  100258. }
  100259. }
  100260. x1 = x2;
  100261. y1 = y2;
  100262. z1 = z2;
  100263. dot1 = dot2;
  100264. }
  100265. numClipVertices = numAddedClipVertices;
  100266. if (swap) {
  100267. var tb = b1;
  100268. b1 = b2;
  100269. b2 = tb;
  100270. }
  100271. if (numClipVertices == 0) return;
  100272. var flipped = b1 != shape1;
  100273. if (numClipVertices > 4) {
  100274. x1 = (q1x + q2x + q3x + q4x) * 0.25;
  100275. y1 = (q1y + q2y + q3y + q4y) * 0.25;
  100276. z1 = (q1z + q2z + q3z + q4z) * 0.25;
  100277. n1x = q1x - x1;
  100278. n1y = q1y - y1;
  100279. n1z = q1z - z1;
  100280. n2x = q2x - x1;
  100281. n2y = q2y - y1;
  100282. n2z = q2z - z1;
  100283. var index1 = 0;
  100284. var index2 = 0;
  100285. var index3 = 0;
  100286. var index4 = 0;
  100287. var maxDot = -this.INF;
  100288. minDot = this.INF;
  100289. //i = numClipVertices;
  100290. //while(i--){
  100291. for (i = 0; i < numClipVertices; i++) {
  100292. this.used[i] = false;
  100293. index = i * 3;
  100294. x1 = this.clipVertices1[index];
  100295. y1 = this.clipVertices1[index + 1];
  100296. z1 = this.clipVertices1[index + 2];
  100297. dot = x1 * n1x + y1 * n1y + z1 * n1z;
  100298. if (dot < minDot) {
  100299. minDot = dot;
  100300. index1 = i;
  100301. }
  100302. if (dot > maxDot) {
  100303. maxDot = dot;
  100304. index3 = i;
  100305. }
  100306. }
  100307. this.used[index1] = true;
  100308. this.used[index3] = true;
  100309. maxDot = -this.INF;
  100310. minDot = this.INF;
  100311. //i = numClipVertices;
  100312. //while(i--){
  100313. for (i = 0; i < numClipVertices; i++) {
  100314. if (this.used[i]) continue;
  100315. index = i * 3;
  100316. x1 = this.clipVertices1[index];
  100317. y1 = this.clipVertices1[index + 1];
  100318. z1 = this.clipVertices1[index + 2];
  100319. dot = x1 * n2x + y1 * n2y + z1 * n2z;
  100320. if (dot < minDot) {
  100321. minDot = dot;
  100322. index2 = i;
  100323. }
  100324. if (dot > maxDot) {
  100325. maxDot = dot;
  100326. index4 = i;
  100327. }
  100328. }
  100329. index = index1 * 3;
  100330. x1 = this.clipVertices1[index];
  100331. y1 = this.clipVertices1[index + 1];
  100332. z1 = this.clipVertices1[index + 2];
  100333. dot = (x1 - cx) * nx + (y1 - cy) * ny + (z1 - cz) * nz;
  100334. if (dot < 0) manifold.addPoint(x1, y1, z1, nx, ny, nz, dot, flipped);
  100335. index = index2 * 3;
  100336. x1 = this.clipVertices1[index];
  100337. y1 = this.clipVertices1[index + 1];
  100338. z1 = this.clipVertices1[index + 2];
  100339. dot = (x1 - cx) * nx + (y1 - cy) * ny + (z1 - cz) * nz;
  100340. if (dot < 0) manifold.addPoint(x1, y1, z1, nx, ny, nz, dot, flipped);
  100341. index = index3 * 3;
  100342. x1 = this.clipVertices1[index];
  100343. y1 = this.clipVertices1[index + 1];
  100344. z1 = this.clipVertices1[index + 2];
  100345. dot = (x1 - cx) * nx + (y1 - cy) * ny + (z1 - cz) * nz;
  100346. if (dot < 0) manifold.addPoint(x1, y1, z1, nx, ny, nz, dot, flipped);
  100347. index = index4 * 3;
  100348. x1 = this.clipVertices1[index];
  100349. y1 = this.clipVertices1[index + 1];
  100350. z1 = this.clipVertices1[index + 2];
  100351. dot = (x1 - cx) * nx + (y1 - cy) * ny + (z1 - cz) * nz;
  100352. if (dot < 0) manifold.addPoint(x1, y1, z1, nx, ny, nz, dot, flipped);
  100353. } else {
  100354. //i = numClipVertices;
  100355. //while(i--){
  100356. for (i = 0; i < numClipVertices; i++) {
  100357. index = i * 3;
  100358. x1 = this.clipVertices1[index];
  100359. y1 = this.clipVertices1[index + 1];
  100360. z1 = this.clipVertices1[index + 2];
  100361. dot = (x1 - cx) * nx + (y1 - cy) * ny + (z1 - cz) * nz;
  100362. if (dot < 0) manifold.addPoint(x1, y1, z1, nx, ny, nz, dot, flipped);
  100363. }
  100364. }
  100365. };
  100366. /**
  100367. * A collision detector which detects collisions between sphere and box.
  100368. * @author saharan
  100369. */
  100370. OIMO.SphereBoxCollisionDetector = function (flip) {
  100371. OIMO.CollisionDetector.call(this);
  100372. this.flip = flip;
  100373. };
  100374. OIMO.SphereBoxCollisionDetector.prototype = Object.create(OIMO.CollisionDetector.prototype);
  100375. OIMO.SphereBoxCollisionDetector.prototype.constructor = OIMO.SphereBoxCollisionDetector;
  100376. OIMO.SphereBoxCollisionDetector.prototype.detectCollision = function (shape1, shape2, manifold) {
  100377. var s;
  100378. var b;
  100379. if (this.flip) {
  100380. s = (shape2);
  100381. b = (shape1);
  100382. } else {
  100383. s = (shape1);
  100384. b = (shape2);
  100385. }
  100386. var D = b.dimentions;
  100387. var ps = s.position;
  100388. var psx = ps.x;
  100389. var psy = ps.y;
  100390. var psz = ps.z;
  100391. var pb = b.position;
  100392. var pbx = pb.x;
  100393. var pby = pb.y;
  100394. var pbz = pb.z;
  100395. var rad = s.radius;
  100396. var hw = b.halfWidth;
  100397. var hh = b.halfHeight;
  100398. var hd = b.halfDepth;
  100399. var dx = psx - pbx;
  100400. var dy = psy - pby;
  100401. var dz = psz - pbz;
  100402. var sx = D[0] * dx + D[1] * dy + D[2] * dz;
  100403. var sy = D[3] * dx + D[4] * dy + D[5] * dz;
  100404. var sz = D[6] * dx + D[7] * dy + D[8] * dz;
  100405. var cx;
  100406. var cy;
  100407. var cz;
  100408. var len;
  100409. var invLen;
  100410. var overlap = 0;
  100411. if (sx > hw) {
  100412. sx = hw;
  100413. } else if (sx < -hw) {
  100414. sx = -hw;
  100415. } else {
  100416. overlap = 1;
  100417. }
  100418. if (sy > hh) {
  100419. sy = hh;
  100420. } else if (sy < -hh) {
  100421. sy = -hh;
  100422. } else {
  100423. overlap |= 2;
  100424. }
  100425. if (sz > hd) {
  100426. sz = hd;
  100427. } else if (sz < -hd) {
  100428. sz = -hd;
  100429. } else {
  100430. overlap |= 4;
  100431. }
  100432. if (overlap == 7) {
  100433. // center of sphere is in the box
  100434. if (sx < 0) {
  100435. dx = hw + sx;
  100436. } else {
  100437. dx = hw - sx;
  100438. }
  100439. if (sy < 0) {
  100440. dy = hh + sy;
  100441. } else {
  100442. dy = hh - sy;
  100443. }
  100444. if (sz < 0) {
  100445. dz = hd + sz;
  100446. } else {
  100447. dz = hd - sz;
  100448. }
  100449. if (dx < dy) {
  100450. if (dx < dz) {
  100451. len = dx - hw;
  100452. if (sx < 0) {
  100453. sx = -hw;
  100454. dx = D[0];
  100455. dy = D[1];
  100456. dz = D[2];
  100457. } else {
  100458. sx = hw;
  100459. dx = -D[0];
  100460. dy = -D[1];
  100461. dz = -D[2];
  100462. }
  100463. } else {
  100464. len = dz - hd;
  100465. if (sz < 0) {
  100466. sz = -hd;
  100467. dx = D[6];
  100468. dy = D[7];
  100469. dz = D[8];
  100470. } else {
  100471. sz = hd;
  100472. dx = -D[6];
  100473. dy = -D[7];
  100474. dz = -D[8];
  100475. }
  100476. }
  100477. } else {
  100478. if (dy < dz) {
  100479. len = dy - hh;
  100480. if (sy < 0) {
  100481. sy = -hh;
  100482. dx = D[3];
  100483. dy = D[4];
  100484. dz = D[5];
  100485. } else {
  100486. sy = hh;
  100487. dx = -D[3];
  100488. dy = -D[4];
  100489. dz = -D[5];
  100490. }
  100491. } else {
  100492. len = dz - hd;
  100493. if (sz < 0) {
  100494. sz = -hd;
  100495. dx = D[6];
  100496. dy = D[7];
  100497. dz = D[8];
  100498. } else {
  100499. sz = hd;
  100500. dx = -D[6];
  100501. dy = -D[7];
  100502. dz = -D[8];
  100503. }
  100504. }
  100505. }
  100506. cx = pbx + sx * D[0] + sy * D[3] + sz * D[6];
  100507. cy = pby + sx * D[1] + sy * D[4] + sz * D[7];
  100508. cz = pbz + sx * D[2] + sy * D[5] + sz * D[8];
  100509. manifold.addPoint(psx + rad * dx, psy + rad * dy, psz + rad * dz, dx, dy, dz, len - rad, this.flip);
  100510. } else {
  100511. cx = pbx + sx * D[0] + sy * D[3] + sz * D[6];
  100512. cy = pby + sx * D[1] + sy * D[4] + sz * D[7];
  100513. cz = pbz + sx * D[2] + sy * D[5] + sz * D[8];
  100514. dx = cx - ps.x;
  100515. dy = cy - ps.y;
  100516. dz = cz - ps.z;
  100517. len = dx * dx + dy * dy + dz * dz;
  100518. if (len > 0 && len < rad * rad) {
  100519. len = OIMO.sqrt(len);
  100520. invLen = 1 / len;
  100521. dx *= invLen;
  100522. dy *= invLen;
  100523. dz *= invLen;
  100524. manifold.addPoint(psx + rad * dx, psy + rad * dy, psz + rad * dz, dx, dy, dz, len - rad, this.flip);
  100525. }
  100526. }
  100527. };
  100528. /**
  100529. * A collision detector which detects collisions between two spheres.
  100530. * @author saharan
  100531. */
  100532. OIMO.SphereSphereCollisionDetector = function () {
  100533. OIMO.CollisionDetector.call(this);
  100534. };
  100535. OIMO.SphereSphereCollisionDetector.prototype = Object.create(OIMO.CollisionDetector.prototype);
  100536. OIMO.SphereSphereCollisionDetector.prototype.constructor = OIMO.SphereSphereCollisionDetector;
  100537. OIMO.SphereSphereCollisionDetector.prototype.detectCollision = function (shape1, shape2, manifold) {
  100538. var s1 = shape1;
  100539. var s2 = shape2;
  100540. var p1 = s1.position;
  100541. var p2 = s2.position;
  100542. var dx = p2.x - p1.x;
  100543. var dy = p2.y - p1.y;
  100544. var dz = p2.z - p1.z;
  100545. var len = dx * dx + dy * dy + dz * dz;
  100546. var r1 = s1.radius;
  100547. var r2 = s2.radius;
  100548. var rad = r1 + r2;
  100549. if (len > 0 && len < rad * rad) {
  100550. len = OIMO.sqrt(len);
  100551. var invLen = 1 / len;
  100552. dx *= invLen;
  100553. dy *= invLen;
  100554. dz *= invLen;
  100555. manifold.addPoint(p1.x + dx * r1, p1.y + dy * r1, p1.z + dz * r1, dx, dy, dz, len - rad, false);
  100556. }
  100557. };
  100558. OIMO.BoxCylinderCollisionDetector = function (flip) {
  100559. OIMO.CollisionDetector.call(this);
  100560. this.flip = flip;
  100561. };
  100562. OIMO.BoxCylinderCollisionDetector.prototype = Object.create(OIMO.CollisionDetector.prototype);
  100563. OIMO.BoxCylinderCollisionDetector.prototype.constructor = OIMO.BoxCylinderCollisionDetector;
  100564. OIMO.BoxCylinderCollisionDetector.prototype.getSep = function (c1, c2, sep, pos, dep) {
  100565. var t1x;
  100566. var t1y;
  100567. var t1z;
  100568. var t2x;
  100569. var t2y;
  100570. var t2z;
  100571. var sup = new OIMO.Vec3();
  100572. var len;
  100573. var p1x;
  100574. var p1y;
  100575. var p1z;
  100576. var p2x;
  100577. var p2y;
  100578. var p2z;
  100579. var v01x = c1.position.x;
  100580. var v01y = c1.position.y;
  100581. var v01z = c1.position.z;
  100582. var v02x = c2.position.x;
  100583. var v02y = c2.position.y;
  100584. var v02z = c2.position.z;
  100585. var v0x = v02x - v01x;
  100586. var v0y = v02y - v01y;
  100587. var v0z = v02z - v01z;
  100588. if (v0x * v0x + v0y * v0y + v0z * v0z == 0) v0y = 0.001;
  100589. var nx = -v0x;
  100590. var ny = -v0y;
  100591. var nz = -v0z;
  100592. this.supportPointB(c1, -nx, -ny, -nz, sup);
  100593. var v11x = sup.x;
  100594. var v11y = sup.y;
  100595. var v11z = sup.z;
  100596. this.supportPointC(c2, nx, ny, nz, sup);
  100597. var v12x = sup.x;
  100598. var v12y = sup.y;
  100599. var v12z = sup.z;
  100600. var v1x = v12x - v11x;
  100601. var v1y = v12y - v11y;
  100602. var v1z = v12z - v11z;
  100603. if (v1x * nx + v1y * ny + v1z * nz <= 0) {
  100604. return false;
  100605. }
  100606. nx = v1y * v0z - v1z * v0y;
  100607. ny = v1z * v0x - v1x * v0z;
  100608. nz = v1x * v0y - v1y * v0x;
  100609. if (nx * nx + ny * ny + nz * nz == 0) {
  100610. sep.init(v1x - v0x, v1y - v0y, v1z - v0z);
  100611. sep.normalize(sep);
  100612. pos.init((v11x + v12x) * 0.5, (v11y + v12y) * 0.5, (v11z + v12z) * 0.5);
  100613. return true;
  100614. }
  100615. this.supportPointB(c1, -nx, -ny, -nz, sup);
  100616. var v21x = sup.x;
  100617. var v21y = sup.y;
  100618. var v21z = sup.z;
  100619. this.supportPointC(c2, nx, ny, nz, sup);
  100620. var v22x = sup.x;
  100621. var v22y = sup.y;
  100622. var v22z = sup.z;
  100623. var v2x = v22x - v21x;
  100624. var v2y = v22y - v21y;
  100625. var v2z = v22z - v21z;
  100626. if (v2x * nx + v2y * ny + v2z * nz <= 0) {
  100627. return false;
  100628. }
  100629. t1x = v1x - v0x;
  100630. t1y = v1y - v0y;
  100631. t1z = v1z - v0z;
  100632. t2x = v2x - v0x;
  100633. t2y = v2y - v0y;
  100634. t2z = v2z - v0z;
  100635. nx = t1y * t2z - t1z * t2y;
  100636. ny = t1z * t2x - t1x * t2z;
  100637. nz = t1x * t2y - t1y * t2x;
  100638. if (nx * v0x + ny * v0y + nz * v0z > 0) {
  100639. t1x = v1x;
  100640. t1y = v1y;
  100641. t1z = v1z;
  100642. v1x = v2x;
  100643. v1y = v2y;
  100644. v1z = v2z;
  100645. v2x = t1x;
  100646. v2y = t1y;
  100647. v2z = t1z;
  100648. t1x = v11x;
  100649. t1y = v11y;
  100650. t1z = v11z;
  100651. v11x = v21x;
  100652. v11y = v21y;
  100653. v11z = v21z;
  100654. v21x = t1x;
  100655. v21y = t1y;
  100656. v21z = t1z;
  100657. t1x = v12x;
  100658. t1y = v12y;
  100659. t1z = v12z;
  100660. v12x = v22x;
  100661. v12y = v22y;
  100662. v12z = v22z;
  100663. v22x = t1x;
  100664. v22y = t1y;
  100665. v22z = t1z;
  100666. nx = -nx;
  100667. ny = -ny;
  100668. nz = -nz;
  100669. }
  100670. var iterations = 0;
  100671. while (true) {
  100672. if (++iterations > 100) {
  100673. return false;
  100674. }
  100675. this.supportPointB(c1, -nx, -ny, -nz, sup);
  100676. var v31x = sup.x;
  100677. var v31y = sup.y;
  100678. var v31z = sup.z;
  100679. this.supportPointC(c2, nx, ny, nz, sup);
  100680. var v32x = sup.x;
  100681. var v32y = sup.y;
  100682. var v32z = sup.z;
  100683. var v3x = v32x - v31x;
  100684. var v3y = v32y - v31y;
  100685. var v3z = v32z - v31z;
  100686. if (v3x * nx + v3y * ny + v3z * nz <= 0) {
  100687. return false;
  100688. }
  100689. if ((v1y * v3z - v1z * v3y) * v0x + (v1z * v3x - v1x * v3z) * v0y + (v1x * v3y - v1y * v3x) * v0z < 0) {
  100690. v2x = v3x;
  100691. v2y = v3y;
  100692. v2z = v3z;
  100693. v21x = v31x;
  100694. v21y = v31y;
  100695. v21z = v31z;
  100696. v22x = v32x;
  100697. v22y = v32y;
  100698. v22z = v32z;
  100699. t1x = v1x - v0x;
  100700. t1y = v1y - v0y;
  100701. t1z = v1z - v0z;
  100702. t2x = v3x - v0x;
  100703. t2y = v3y - v0y;
  100704. t2z = v3z - v0z;
  100705. nx = t1y * t2z - t1z * t2y;
  100706. ny = t1z * t2x - t1x * t2z;
  100707. nz = t1x * t2y - t1y * t2x;
  100708. continue;
  100709. }
  100710. if ((v3y * v2z - v3z * v2y) * v0x + (v3z * v2x - v3x * v2z) * v0y + (v3x * v2y - v3y * v2x) * v0z < 0) {
  100711. v1x = v3x;
  100712. v1y = v3y;
  100713. v1z = v3z;
  100714. v11x = v31x;
  100715. v11y = v31y;
  100716. v11z = v31z;
  100717. v12x = v32x;
  100718. v12y = v32y;
  100719. v12z = v32z;
  100720. t1x = v3x - v0x;
  100721. t1y = v3y - v0y;
  100722. t1z = v3z - v0z;
  100723. t2x = v2x - v0x;
  100724. t2y = v2y - v0y;
  100725. t2z = v2z - v0z;
  100726. nx = t1y * t2z - t1z * t2y;
  100727. ny = t1z * t2x - t1x * t2z;
  100728. nz = t1x * t2y - t1y * t2x;
  100729. continue;
  100730. }
  100731. var hit = false;
  100732. while (true) {
  100733. t1x = v2x - v1x;
  100734. t1y = v2y - v1y;
  100735. t1z = v2z - v1z;
  100736. t2x = v3x - v1x;
  100737. t2y = v3y - v1y;
  100738. t2z = v3z - v1z;
  100739. nx = t1y * t2z - t1z * t2y;
  100740. ny = t1z * t2x - t1x * t2z;
  100741. nz = t1x * t2y - t1y * t2x;
  100742. len = 1 / OIMO.sqrt(nx * nx + ny * ny + nz * nz);
  100743. nx *= len;
  100744. ny *= len;
  100745. nz *= len;
  100746. if (nx * v1x + ny * v1y + nz * v1z >= 0 && !hit) {
  100747. var b0 = (v1y * v2z - v1z * v2y) * v3x + (v1z * v2x - v1x * v2z) * v3y + (v1x * v2y - v1y * v2x) * v3z;
  100748. var b1 = (v3y * v2z - v3z * v2y) * v0x + (v3z * v2x - v3x * v2z) * v0y + (v3x * v2y - v3y * v2x) * v0z;
  100749. var b2 = (v0y * v1z - v0z * v1y) * v3x + (v0z * v1x - v0x * v1z) * v3y + (v0x * v1y - v0y * v1x) * v3z;
  100750. var b3 = (v2y * v1z - v2z * v1y) * v0x + (v2z * v1x - v2x * v1z) * v0y + (v2x * v1y - v2y * v1x) * v0z;
  100751. var sum = b0 + b1 + b2 + b3;
  100752. if (sum <= 0) {
  100753. b0 = 0;
  100754. b1 = (v2y * v3z - v2z * v3y) * nx + (v2z * v3x - v2x * v3z) * ny + (v2x * v3y - v2y * v3x) * nz;
  100755. b2 = (v3y * v2z - v3z * v2y) * nx + (v3z * v2x - v3x * v2z) * ny + (v3x * v2y - v3y * v2x) * nz;
  100756. b3 = (v1y * v2z - v1z * v2y) * nx + (v1z * v2x - v1x * v2z) * ny + (v1x * v2y - v1y * v2x) * nz;
  100757. sum = b1 + b2 + b3;
  100758. }
  100759. var inv = 1 / sum;
  100760. p1x = (v01x * b0 + v11x * b1 + v21x * b2 + v31x * b3) * inv;
  100761. p1y = (v01y * b0 + v11y * b1 + v21y * b2 + v31y * b3) * inv;
  100762. p1z = (v01z * b0 + v11z * b1 + v21z * b2 + v31z * b3) * inv;
  100763. p2x = (v02x * b0 + v12x * b1 + v22x * b2 + v32x * b3) * inv;
  100764. p2y = (v02y * b0 + v12y * b1 + v22y * b2 + v32y * b3) * inv;
  100765. p2z = (v02z * b0 + v12z * b1 + v22z * b2 + v32z * b3) * inv;
  100766. hit = true;
  100767. }
  100768. this.supportPointB(c1, -nx, -ny, -nz, sup);
  100769. var v41x = sup.x;
  100770. var v41y = sup.y;
  100771. var v41z = sup.z;
  100772. this.supportPointC(c2, nx, ny, nz, sup);
  100773. var v42x = sup.x;
  100774. var v42y = sup.y;
  100775. var v42z = sup.z;
  100776. var v4x = v42x - v41x;
  100777. var v4y = v42y - v41y;
  100778. var v4z = v42z - v41z;
  100779. var separation = -(v4x * nx + v4y * ny + v4z * nz);
  100780. if ((v4x - v3x) * nx + (v4y - v3y) * ny + (v4z - v3z) * nz <= 0.01 || separation >= 0) {
  100781. if (hit) {
  100782. sep.init(-nx, -ny, -nz);
  100783. pos.init((p1x + p2x) * 0.5, (p1y + p2y) * 0.5, (p1z + p2z) * 0.5);
  100784. dep.x = separation;
  100785. return true;
  100786. }
  100787. return false;
  100788. }
  100789. if (
  100790. (v4y * v1z - v4z * v1y) * v0x +
  100791. (v4z * v1x - v4x * v1z) * v0y +
  100792. (v4x * v1y - v4y * v1x) * v0z < 0
  100793. ) {
  100794. if (
  100795. (v4y * v2z - v4z * v2y) * v0x +
  100796. (v4z * v2x - v4x * v2z) * v0y +
  100797. (v4x * v2y - v4y * v2x) * v0z < 0
  100798. ) {
  100799. v1x = v4x;
  100800. v1y = v4y;
  100801. v1z = v4z;
  100802. v11x = v41x;
  100803. v11y = v41y;
  100804. v11z = v41z;
  100805. v12x = v42x;
  100806. v12y = v42y;
  100807. v12z = v42z;
  100808. } else {
  100809. v3x = v4x;
  100810. v3y = v4y;
  100811. v3z = v4z;
  100812. v31x = v41x;
  100813. v31y = v41y;
  100814. v31z = v41z;
  100815. v32x = v42x;
  100816. v32y = v42y;
  100817. v32z = v42z;
  100818. }
  100819. } else {
  100820. if (
  100821. (v4y * v3z - v4z * v3y) * v0x +
  100822. (v4z * v3x - v4x * v3z) * v0y +
  100823. (v4x * v3y - v4y * v3x) * v0z < 0
  100824. ) {
  100825. v2x = v4x;
  100826. v2y = v4y;
  100827. v2z = v4z;
  100828. v21x = v41x;
  100829. v21y = v41y;
  100830. v21z = v41z;
  100831. v22x = v42x;
  100832. v22y = v42y;
  100833. v22z = v42z;
  100834. } else {
  100835. v1x = v4x;
  100836. v1y = v4y;
  100837. v1z = v4z;
  100838. v11x = v41x;
  100839. v11y = v41y;
  100840. v11z = v41z;
  100841. v12x = v42x;
  100842. v12y = v42y;
  100843. v12z = v42z;
  100844. }
  100845. }
  100846. }
  100847. }
  100848. //return false;
  100849. };
  100850. OIMO.BoxCylinderCollisionDetector.prototype.supportPointB = function (c, dx, dy, dz, out) {
  100851. var rot = c.rotation.elements;
  100852. var ldx = rot[0] * dx + rot[3] * dy + rot[6] * dz;
  100853. var ldy = rot[1] * dx + rot[4] * dy + rot[7] * dz;
  100854. var ldz = rot[2] * dx + rot[5] * dy + rot[8] * dz;
  100855. var w = c.halfWidth;
  100856. var h = c.halfHeight;
  100857. var d = c.halfDepth;
  100858. var ox;
  100859. var oy;
  100860. var oz;
  100861. if (ldx < 0) ox = -w;
  100862. else ox = w;
  100863. if (ldy < 0) oy = -h;
  100864. else oy = h;
  100865. if (ldz < 0) oz = -d;
  100866. else oz = d;
  100867. ldx = rot[0] * ox + rot[1] * oy + rot[2] * oz + c.position.x;
  100868. ldy = rot[3] * ox + rot[4] * oy + rot[5] * oz + c.position.y;
  100869. ldz = rot[6] * ox + rot[7] * oy + rot[8] * oz + c.position.z;
  100870. out.init(ldx, ldy, ldz);
  100871. };
  100872. OIMO.BoxCylinderCollisionDetector.prototype.supportPointC = function (c, dx, dy, dz, out) {
  100873. var rot = c.rotation.elements;
  100874. var ldx = rot[0] * dx + rot[3] * dy + rot[6] * dz;
  100875. var ldy = rot[1] * dx + rot[4] * dy + rot[7] * dz;
  100876. var ldz = rot[2] * dx + rot[5] * dy + rot[8] * dz;
  100877. var radx = ldx;
  100878. var radz = ldz;
  100879. var len = radx * radx + radz * radz;
  100880. var rad = c.radius;
  100881. var hh = c.halfHeight;
  100882. var ox;
  100883. var oy;
  100884. var oz;
  100885. if (len == 0) {
  100886. if (ldy < 0) {
  100887. ox = rad;
  100888. oy = -hh;
  100889. oz = 0;
  100890. } else {
  100891. ox = rad;
  100892. oy = hh;
  100893. oz = 0;
  100894. }
  100895. } else {
  100896. len = c.radius / OIMO.sqrt(len);
  100897. if (ldy < 0) {
  100898. ox = radx * len;
  100899. oy = -hh;
  100900. oz = radz * len;
  100901. } else {
  100902. ox = radx * len;
  100903. oy = hh;
  100904. oz = radz * len;
  100905. }
  100906. }
  100907. ldx = rot[0] * ox + rot[1] * oy + rot[2] * oz + c.position.x;
  100908. ldy = rot[3] * ox + rot[4] * oy + rot[5] * oz + c.position.y;
  100909. ldz = rot[6] * ox + rot[7] * oy + rot[8] * oz + c.position.z;
  100910. out.init(ldx, ldy, ldz);
  100911. };
  100912. OIMO.BoxCylinderCollisionDetector.prototype.detectCollision = function (shape1, shape2, manifold) {
  100913. var b;
  100914. var c;
  100915. if (this.flip) {
  100916. b = shape2;
  100917. c = shape1;
  100918. } else {
  100919. b = shape1;
  100920. c = shape2;
  100921. }
  100922. var sep = new OIMO.Vec3();
  100923. var pos = new OIMO.Vec3();
  100924. var dep = new OIMO.Vec3();
  100925. var co;
  100926. if (!this.getSep(b, c, sep, pos, dep)) return;
  100927. var pbx = b.position.x;
  100928. var pby = b.position.y;
  100929. var pbz = b.position.z;
  100930. var pcx = c.position.x;
  100931. var pcy = c.position.y;
  100932. var pcz = c.position.z;
  100933. var bw = b.halfWidth;
  100934. var bh = b.halfHeight;
  100935. var bd = b.halfDepth;
  100936. var ch = c.halfHeight;
  100937. var r = c.radius;
  100938. var D = b.dimentions;
  100939. var nwx = D[0];//b.normalDirectionWidth.x;
  100940. var nwy = D[1];//b.normalDirectionWidth.y;
  100941. var nwz = D[2];//b.normalDirectionWidth.z;
  100942. var nhx = D[3];//b.normalDirectionHeight.x;
  100943. var nhy = D[4];//b.normalDirectionHeight.y;
  100944. var nhz = D[5];//b.normalDirectionHeight.z;
  100945. var ndx = D[6];//b.normalDirectionDepth.x;
  100946. var ndy = D[7];//b.normalDirectionDepth.y;
  100947. var ndz = D[8];//b.normalDirectionDepth.z;
  100948. var dwx = D[9];//b.halfDirectionWidth.x;
  100949. var dwy = D[10];//b.halfDirectionWidth.y;
  100950. var dwz = D[11];//b.halfDirectionWidth.z;
  100951. var dhx = D[12];//b.halfDirectionHeight.x;
  100952. var dhy = D[13];//b.halfDirectionHeight.y;
  100953. var dhz = D[14];//b.halfDirectionHeight.z;
  100954. var ddx = D[15];//b.halfDirectionDepth.x;
  100955. var ddy = D[16];//b.halfDirectionDepth.y;
  100956. var ddz = D[17];//b.halfDirectionDepth.z;
  100957. var ncx = c.normalDirection.x;
  100958. var ncy = c.normalDirection.y;
  100959. var ncz = c.normalDirection.z;
  100960. var dcx = c.halfDirection.x;
  100961. var dcy = c.halfDirection.y;
  100962. var dcz = c.halfDirection.z;
  100963. var nx = sep.x;
  100964. var ny = sep.y;
  100965. var nz = sep.z;
  100966. var dotw = nx * nwx + ny * nwy + nz * nwz;
  100967. var doth = nx * nhx + ny * nhy + nz * nhz;
  100968. var dotd = nx * ndx + ny * ndy + nz * ndz;
  100969. var dotc = nx * ncx + ny * ncy + nz * ncz;
  100970. var right1 = dotw > 0;
  100971. var right2 = doth > 0;
  100972. var right3 = dotd > 0;
  100973. var right4 = dotc > 0;
  100974. if (!right1) dotw = -dotw;
  100975. if (!right2) doth = -doth;
  100976. if (!right3) dotd = -dotd;
  100977. if (!right4) dotc = -dotc;
  100978. var state = 0;
  100979. if (dotc > 0.999) {
  100980. if (dotw > 0.999) {
  100981. if (dotw > dotc) state = 1;
  100982. else state = 4;
  100983. } else if (doth > 0.999) {
  100984. if (doth > dotc) state = 2;
  100985. else state = 4;
  100986. } else if (dotd > 0.999) {
  100987. if (dotd > dotc) state = 3;
  100988. else state = 4;
  100989. } else state = 4;
  100990. } else {
  100991. if (dotw > 0.999) state = 1;
  100992. else if (doth > 0.999) state = 2;
  100993. else if (dotd > 0.999) state = 3;
  100994. }
  100995. var cbx;
  100996. var cby;
  100997. var cbz;
  100998. var ccx;
  100999. var ccy;
  101000. var ccz;
  101001. var r00;
  101002. var r01;
  101003. var r02;
  101004. var r10;
  101005. var r11;
  101006. var r12;
  101007. var r20;
  101008. var r21;
  101009. var r22;
  101010. var px;
  101011. var py;
  101012. var pz;
  101013. var pd;
  101014. var dot;
  101015. var len;
  101016. var tx;
  101017. var ty;
  101018. var tz;
  101019. var td;
  101020. var dx;
  101021. var dy;
  101022. var dz;
  101023. var d1x;
  101024. var d1y;
  101025. var d1z;
  101026. var d2x;
  101027. var d2y;
  101028. var d2z;
  101029. var sx;
  101030. var sy;
  101031. var sz;
  101032. var sd;
  101033. var ex;
  101034. var ey;
  101035. var ez;
  101036. var ed;
  101037. var dot1;
  101038. var dot2;
  101039. var t1;
  101040. var t2;
  101041. var dir1x;
  101042. var dir1y;
  101043. var dir1z;
  101044. var dir2x;
  101045. var dir2y;
  101046. var dir2z;
  101047. var dir1l;
  101048. var dir2l;
  101049. if (state == 0) {
  101050. //manifold.addPoint(pos.x,pos.y,pos.z,nx,ny,nz,dep.x,b,c,0,0,false);
  101051. manifold.addPoint(pos.x, pos.y, pos.z, nx, ny, nz, dep.x, this.flip);
  101052. } else if (state == 4) {
  101053. if (right4) {
  101054. ccx = pcx - dcx;
  101055. ccy = pcy - dcy;
  101056. ccz = pcz - dcz;
  101057. nx = -ncx;
  101058. ny = -ncy;
  101059. nz = -ncz;
  101060. } else {
  101061. ccx = pcx + dcx;
  101062. ccy = pcy + dcy;
  101063. ccz = pcz + dcz;
  101064. nx = ncx;
  101065. ny = ncy;
  101066. nz = ncz;
  101067. }
  101068. var v1x;
  101069. var v1y;
  101070. var v1z;
  101071. var v2x;
  101072. var v2y;
  101073. var v2z;
  101074. var v3x;
  101075. var v3y;
  101076. var v3z;
  101077. var v4x;
  101078. var v4y;
  101079. var v4z;
  101080. dot = 1;
  101081. state = 0;
  101082. dot1 = nwx * nx + nwy * ny + nwz * nz;
  101083. if (dot1 < dot) {
  101084. dot = dot1;
  101085. state = 0;
  101086. }
  101087. if (-dot1 < dot) {
  101088. dot = -dot1;
  101089. state = 1;
  101090. }
  101091. dot1 = nhx * nx + nhy * ny + nhz * nz;
  101092. if (dot1 < dot) {
  101093. dot = dot1;
  101094. state = 2;
  101095. }
  101096. if (-dot1 < dot) {
  101097. dot = -dot1;
  101098. state = 3;
  101099. }
  101100. dot1 = ndx * nx + ndy * ny + ndz * nz;
  101101. if (dot1 < dot) {
  101102. dot = dot1;
  101103. state = 4;
  101104. }
  101105. if (-dot1 < dot) {
  101106. dot = -dot1;
  101107. state = 5;
  101108. }
  101109. var v = b.elements;
  101110. switch (state) {
  101111. case 0:
  101112. //v=b.vertex1;
  101113. v1x = v[0];//v.x;
  101114. v1y = v[1];//v.y;
  101115. v1z = v[2];//v.z;
  101116. //v=b.vertex3;
  101117. v2x = v[6];//v.x;
  101118. v2y = v[7];//v.y;
  101119. v2z = v[8];//v.z;
  101120. //v=b.vertex4;
  101121. v3x = v[9];//v.x;
  101122. v3y = v[10];//v.y;
  101123. v3z = v[11];//v.z;
  101124. //v=b.vertex2;
  101125. v4x = v[3];//v.x;
  101126. v4y = v[4];//v.y;
  101127. v4z = v[5];//v.z;
  101128. break;
  101129. case 1:
  101130. //v=b.vertex6;
  101131. v1x = v[15];//v.x;
  101132. v1y = v[16];//v.y;
  101133. v1z = v[17];//v.z;
  101134. //v=b.vertex8;
  101135. v2x = v[21];//v.x;
  101136. v2y = v[22];//v.y;
  101137. v2z = v[23];//v.z;
  101138. //v=b.vertex7;
  101139. v3x = v[18];//v.x;
  101140. v3y = v[19];//v.y;
  101141. v3z = v[20];//v.z;
  101142. //v=b.vertex5;
  101143. v4x = v[12];//v.x;
  101144. v4y = v[13];//v.y;
  101145. v4z = v[14];//v.z;
  101146. break;
  101147. case 2:
  101148. //v=b.vertex5;
  101149. v1x = v[12];//v.x;
  101150. v1y = v[13];//v.y;
  101151. v1z = v[14];//v.z;
  101152. //v=b.vertex1;
  101153. v2x = v[0];//v.x;
  101154. v2y = v[1];//v.y;
  101155. v2z = v[2];//v.z;
  101156. //v=b.vertex2;
  101157. v3x = v[3];//v.x;
  101158. v3y = v[4];//v.y;
  101159. v3z = v[5];//v.z;
  101160. //v=b.vertex6;
  101161. v4x = v[15];//v.x;
  101162. v4y = v[16];//v.y;
  101163. v4z = v[17];//v.z;
  101164. break;
  101165. case 3:
  101166. //v=b.vertex8;
  101167. v1x = v[21];//v.x;
  101168. v1y = v[22];//v.y;
  101169. v1z = v[23];//v.z;
  101170. //v=b.vertex4;
  101171. v2x = v[9];//v.x;
  101172. v2y = v[10];//v.y;
  101173. v2z = v[11];//v.z;
  101174. //v=b.vertex3;
  101175. v3x = v[6];//v.x;
  101176. v3y = v[7];//v.y;
  101177. v3z = v[8];//v.z;
  101178. //v=b.vertex7;
  101179. v4x = v[18];//v.x;
  101180. v4y = v[19];//v.y;
  101181. v4z = v[20];//v.z;
  101182. break;
  101183. case 4:
  101184. //v=b.vertex5;
  101185. v1x = v[12];//v.x;
  101186. v1y = v[13];//v.y;
  101187. v1z = v[14];//v.z;
  101188. //v=b.vertex7;
  101189. v2x = v[18];//v.x;
  101190. v2y = v[19];//v.y;
  101191. v2z = v[20];//v.z;
  101192. //v=b.vertex3;
  101193. v3x = v[6];//v.x;
  101194. v3y = v[7];//v.y;
  101195. v3z = v[8];//v.z;
  101196. //v=b.vertex1;
  101197. v4x = v[0];//v.x;
  101198. v4y = v[1];//v.y;
  101199. v4z = v[2];//v.z;
  101200. break;
  101201. case 5:
  101202. //v=b.vertex2;
  101203. v1x = v[3];//v.x;
  101204. v1y = v[4];//v.y;
  101205. v1z = v[5];//v.z;
  101206. //v=b.vertex4;
  101207. v2x = v[9];//v.x;
  101208. v2y = v[10];//v.y;
  101209. v2z = v[11];//v.z;
  101210. //v=b.vertex8;
  101211. v3x = v[21];//v.x;
  101212. v3y = v[22];//v.y;
  101213. v3z = v[23];//v.z;
  101214. //v=b.vertex6;
  101215. v4x = v[15];//v.x;
  101216. v4y = v[16];//v.y;
  101217. v4z = v[17];//v.z;
  101218. break;
  101219. }
  101220. pd = nx * (v1x - ccx) + ny * (v1y - ccy) + nz * (v1z - ccz);
  101221. if (pd <= 0) manifold.addPoint(v1x, v1y, v1z, -nx, -ny, -nz, pd, this.flip);
  101222. pd = nx * (v2x - ccx) + ny * (v2y - ccy) + nz * (v2z - ccz);
  101223. if (pd <= 0) manifold.addPoint(v2x, v2y, v2z, -nx, -ny, -nz, pd, this.flip);
  101224. pd = nx * (v3x - ccx) + ny * (v3y - ccy) + nz * (v3z - ccz);
  101225. if (pd <= 0) manifold.addPoint(v3x, v3y, v3z, -nx, -ny, -nz, pd, this.flip);
  101226. pd = nx * (v4x - ccx) + ny * (v4y - ccy) + nz * (v4z - ccz);
  101227. if (pd <= 0) manifold.addPoint(v4x, v4y, v4z, -nx, -ny, -nz, pd, this.flip);
  101228. } else {
  101229. switch (state) {
  101230. case 1:
  101231. if (right1) {
  101232. cbx = pbx + dwx;
  101233. cby = pby + dwy;
  101234. cbz = pbz + dwz;
  101235. nx = nwx;
  101236. ny = nwy;
  101237. nz = nwz;
  101238. } else {
  101239. cbx = pbx - dwx;
  101240. cby = pby - dwy;
  101241. cbz = pbz - dwz;
  101242. nx = -nwx;
  101243. ny = -nwy;
  101244. nz = -nwz;
  101245. }
  101246. dir1x = nhx;
  101247. dir1y = nhy;
  101248. dir1z = nhz;
  101249. dir1l = bh;
  101250. dir2x = ndx;
  101251. dir2y = ndy;
  101252. dir2z = ndz;
  101253. dir2l = bd;
  101254. break;
  101255. case 2:
  101256. if (right2) {
  101257. cbx = pbx + dhx;
  101258. cby = pby + dhy;
  101259. cbz = pbz + dhz;
  101260. nx = nhx;
  101261. ny = nhy;
  101262. nz = nhz;
  101263. } else {
  101264. cbx = pbx - dhx;
  101265. cby = pby - dhy;
  101266. cbz = pbz - dhz;
  101267. nx = -nhx;
  101268. ny = -nhy;
  101269. nz = -nhz;
  101270. }
  101271. dir1x = nwx;
  101272. dir1y = nwy;
  101273. dir1z = nwz;
  101274. dir1l = bw;
  101275. dir2x = ndx;
  101276. dir2y = ndy;
  101277. dir2z = ndz;
  101278. dir2l = bd;
  101279. break;
  101280. case 3:
  101281. if (right3) {
  101282. cbx = pbx + ddx;
  101283. cby = pby + ddy;
  101284. cbz = pbz + ddz;
  101285. nx = ndx;
  101286. ny = ndy;
  101287. nz = ndz;
  101288. } else {
  101289. cbx = pbx - ddx;
  101290. cby = pby - ddy;
  101291. cbz = pbz - ddz;
  101292. nx = -ndx;
  101293. ny = -ndy;
  101294. nz = -ndz;
  101295. }
  101296. dir1x = nwx;
  101297. dir1y = nwy;
  101298. dir1z = nwz;
  101299. dir1l = bw;
  101300. dir2x = nhx;
  101301. dir2y = nhy;
  101302. dir2z = nhz;
  101303. dir2l = bh;
  101304. break;
  101305. }
  101306. dot = nx * ncx + ny * ncy + nz * ncz;
  101307. if (dot < 0) len = ch;
  101308. else len = -ch;
  101309. ccx = pcx + len * ncx;
  101310. ccy = pcy + len * ncy;
  101311. ccz = pcz + len * ncz;
  101312. if (dotc >= 0.999999) {
  101313. tx = -ny;
  101314. ty = nz;
  101315. tz = nx;
  101316. } else {
  101317. tx = nx;
  101318. ty = ny;
  101319. tz = nz;
  101320. }
  101321. len = tx * ncx + ty * ncy + tz * ncz;
  101322. dx = len * ncx - tx;
  101323. dy = len * ncy - ty;
  101324. dz = len * ncz - tz;
  101325. len = OIMO.sqrt(dx * dx + dy * dy + dz * dz);
  101326. if (len == 0) return;
  101327. len = r / len;
  101328. dx *= len;
  101329. dy *= len;
  101330. dz *= len;
  101331. tx = ccx + dx;
  101332. ty = ccy + dy;
  101333. tz = ccz + dz;
  101334. if (dot < -0.96 || dot > 0.96) {
  101335. r00 = ncx * ncx * 1.5 - 0.5;
  101336. r01 = ncx * ncy * 1.5 - ncz * 0.866025403;
  101337. r02 = ncx * ncz * 1.5 + ncy * 0.866025403;
  101338. r10 = ncy * ncx * 1.5 + ncz * 0.866025403;
  101339. r11 = ncy * ncy * 1.5 - 0.5;
  101340. r12 = ncy * ncz * 1.5 - ncx * 0.866025403;
  101341. r20 = ncz * ncx * 1.5 - ncy * 0.866025403;
  101342. r21 = ncz * ncy * 1.5 + ncx * 0.866025403;
  101343. r22 = ncz * ncz * 1.5 - 0.5;
  101344. px = tx;
  101345. py = ty;
  101346. pz = tz;
  101347. pd = nx * (px - cbx) + ny * (py - cby) + nz * (pz - cbz);
  101348. tx = px - pd * nx - cbx;
  101349. ty = py - pd * ny - cby;
  101350. tz = pz - pd * nz - cbz;
  101351. sd = dir1x * tx + dir1y * ty + dir1z * tz;
  101352. ed = dir2x * tx + dir2y * ty + dir2z * tz;
  101353. if (sd < -dir1l) sd = -dir1l;
  101354. else if (sd > dir1l) sd = dir1l;
  101355. if (ed < -dir2l) ed = -dir2l;
  101356. else if (ed > dir2l) ed = dir2l;
  101357. tx = sd * dir1x + ed * dir2x;
  101358. ty = sd * dir1y + ed * dir2y;
  101359. tz = sd * dir1z + ed * dir2z;
  101360. px = cbx + tx;
  101361. py = cby + ty;
  101362. pz = cbz + tz;
  101363. manifold.addPoint(px, py, pz, nx, ny, nz, pd, this.flip);
  101364. px = dx * r00 + dy * r01 + dz * r02;
  101365. py = dx * r10 + dy * r11 + dz * r12;
  101366. pz = dx * r20 + dy * r21 + dz * r22;
  101367. px = (dx = px) + ccx;
  101368. py = (dy = py) + ccy;
  101369. pz = (dz = pz) + ccz;
  101370. pd = nx * (px - cbx) + ny * (py - cby) + nz * (pz - cbz);
  101371. if (pd <= 0) {
  101372. tx = px - pd * nx - cbx;
  101373. ty = py - pd * ny - cby;
  101374. tz = pz - pd * nz - cbz;
  101375. sd = dir1x * tx + dir1y * ty + dir1z * tz;
  101376. ed = dir2x * tx + dir2y * ty + dir2z * tz;
  101377. if (sd < -dir1l) sd = -dir1l;
  101378. else if (sd > dir1l) sd = dir1l;
  101379. if (ed < -dir2l) ed = -dir2l;
  101380. else if (ed > dir2l) ed = dir2l;
  101381. tx = sd * dir1x + ed * dir2x;
  101382. ty = sd * dir1y + ed * dir2y;
  101383. tz = sd * dir1z + ed * dir2z;
  101384. px = cbx + tx;
  101385. py = cby + ty;
  101386. pz = cbz + tz;
  101387. //manifold.addPoint(px,py,pz,nx,ny,nz,pd,b,c,2,0,false);
  101388. manifold.addPoint(px, py, pz, nx, ny, nz, pd, this.flip);
  101389. }
  101390. px = dx * r00 + dy * r01 + dz * r02;
  101391. py = dx * r10 + dy * r11 + dz * r12;
  101392. pz = dx * r20 + dy * r21 + dz * r22;
  101393. px = (dx = px) + ccx;
  101394. py = (dy = py) + ccy;
  101395. pz = (dz = pz) + ccz;
  101396. pd = nx * (px - cbx) + ny * (py - cby) + nz * (pz - cbz);
  101397. if (pd <= 0) {
  101398. tx = px - pd * nx - cbx;
  101399. ty = py - pd * ny - cby;
  101400. tz = pz - pd * nz - cbz;
  101401. sd = dir1x * tx + dir1y * ty + dir1z * tz;
  101402. ed = dir2x * tx + dir2y * ty + dir2z * tz;
  101403. if (sd < -dir1l) sd = -dir1l;
  101404. else if (sd > dir1l) sd = dir1l;
  101405. if (ed < -dir2l) ed = -dir2l;
  101406. else if (ed > dir2l) ed = dir2l;
  101407. tx = sd * dir1x + ed * dir2x;
  101408. ty = sd * dir1y + ed * dir2y;
  101409. tz = sd * dir1z + ed * dir2z;
  101410. px = cbx + tx;
  101411. py = cby + ty;
  101412. pz = cbz + tz;
  101413. //manifold.addPoint(px,py,pz,nx,ny,nz,pd,b,c,3,0,false);
  101414. manifold.addPoint(px, py, pz, nx, ny, nz, pd, this.flip);
  101415. }
  101416. } else {
  101417. sx = tx;
  101418. sy = ty;
  101419. sz = tz;
  101420. sd = nx * (sx - cbx) + ny * (sy - cby) + nz * (sz - cbz);
  101421. sx -= sd * nx;
  101422. sy -= sd * ny;
  101423. sz -= sd * nz;
  101424. if (dot > 0) {
  101425. ex = tx + dcx * 2;
  101426. ey = ty + dcy * 2;
  101427. ez = tz + dcz * 2;
  101428. } else {
  101429. ex = tx - dcx * 2;
  101430. ey = ty - dcy * 2;
  101431. ez = tz - dcz * 2;
  101432. }
  101433. ed = nx * (ex - cbx) + ny * (ey - cby) + nz * (ez - cbz);
  101434. ex -= ed * nx;
  101435. ey -= ed * ny;
  101436. ez -= ed * nz;
  101437. d1x = sx - cbx;
  101438. d1y = sy - cby;
  101439. d1z = sz - cbz;
  101440. d2x = ex - cbx;
  101441. d2y = ey - cby;
  101442. d2z = ez - cbz;
  101443. tx = ex - sx;
  101444. ty = ey - sy;
  101445. tz = ez - sz;
  101446. td = ed - sd;
  101447. dotw = d1x * dir1x + d1y * dir1y + d1z * dir1z;
  101448. doth = d2x * dir1x + d2y * dir1y + d2z * dir1z;
  101449. dot1 = dotw - dir1l;
  101450. dot2 = doth - dir1l;
  101451. if (dot1 > 0) {
  101452. if (dot2 > 0) return;
  101453. t1 = dot1 / (dot1 - dot2);
  101454. sx = sx + tx * t1;
  101455. sy = sy + ty * t1;
  101456. sz = sz + tz * t1;
  101457. sd = sd + td * t1;
  101458. d1x = sx - cbx;
  101459. d1y = sy - cby;
  101460. d1z = sz - cbz;
  101461. dotw = d1x * dir1x + d1y * dir1y + d1z * dir1z;
  101462. tx = ex - sx;
  101463. ty = ey - sy;
  101464. tz = ez - sz;
  101465. td = ed - sd;
  101466. } else if (dot2 > 0) {
  101467. t1 = dot1 / (dot1 - dot2);
  101468. ex = sx + tx * t1;
  101469. ey = sy + ty * t1;
  101470. ez = sz + tz * t1;
  101471. ed = sd + td * t1;
  101472. d2x = ex - cbx;
  101473. d2y = ey - cby;
  101474. d2z = ez - cbz;
  101475. doth = d2x * dir1x + d2y * dir1y + d2z * dir1z;
  101476. tx = ex - sx;
  101477. ty = ey - sy;
  101478. tz = ez - sz;
  101479. td = ed - sd;
  101480. }
  101481. dot1 = dotw + dir1l;
  101482. dot2 = doth + dir1l;
  101483. if (dot1 < 0) {
  101484. if (dot2 < 0) return;
  101485. t1 = dot1 / (dot1 - dot2);
  101486. sx = sx + tx * t1;
  101487. sy = sy + ty * t1;
  101488. sz = sz + tz * t1;
  101489. sd = sd + td * t1;
  101490. d1x = sx - cbx;
  101491. d1y = sy - cby;
  101492. d1z = sz - cbz;
  101493. tx = ex - sx;
  101494. ty = ey - sy;
  101495. tz = ez - sz;
  101496. td = ed - sd;
  101497. } else if (dot2 < 0) {
  101498. t1 = dot1 / (dot1 - dot2);
  101499. ex = sx + tx * t1;
  101500. ey = sy + ty * t1;
  101501. ez = sz + tz * t1;
  101502. ed = sd + td * t1;
  101503. d2x = ex - cbx;
  101504. d2y = ey - cby;
  101505. d2z = ez - cbz;
  101506. tx = ex - sx;
  101507. ty = ey - sy;
  101508. tz = ez - sz;
  101509. td = ed - sd;
  101510. }
  101511. dotw = d1x * dir2x + d1y * dir2y + d1z * dir2z;
  101512. doth = d2x * dir2x + d2y * dir2y + d2z * dir2z;
  101513. dot1 = dotw - dir2l;
  101514. dot2 = doth - dir2l;
  101515. if (dot1 > 0) {
  101516. if (dot2 > 0) return;
  101517. t1 = dot1 / (dot1 - dot2);
  101518. sx = sx + tx * t1;
  101519. sy = sy + ty * t1;
  101520. sz = sz + tz * t1;
  101521. sd = sd + td * t1;
  101522. d1x = sx - cbx;
  101523. d1y = sy - cby;
  101524. d1z = sz - cbz;
  101525. dotw = d1x * dir2x + d1y * dir2y + d1z * dir2z;
  101526. tx = ex - sx;
  101527. ty = ey - sy;
  101528. tz = ez - sz;
  101529. td = ed - sd;
  101530. } else if (dot2 > 0) {
  101531. t1 = dot1 / (dot1 - dot2);
  101532. ex = sx + tx * t1;
  101533. ey = sy + ty * t1;
  101534. ez = sz + tz * t1;
  101535. ed = sd + td * t1;
  101536. d2x = ex - cbx;
  101537. d2y = ey - cby;
  101538. d2z = ez - cbz;
  101539. doth = d2x * dir2x + d2y * dir2y + d2z * dir2z;
  101540. tx = ex - sx;
  101541. ty = ey - sy;
  101542. tz = ez - sz;
  101543. td = ed - sd;
  101544. }
  101545. dot1 = dotw + dir2l;
  101546. dot2 = doth + dir2l;
  101547. if (dot1 < 0) {
  101548. if (dot2 < 0) return;
  101549. t1 = dot1 / (dot1 - dot2);
  101550. sx = sx + tx * t1;
  101551. sy = sy + ty * t1;
  101552. sz = sz + tz * t1;
  101553. sd = sd + td * t1;
  101554. } else if (dot2 < 0) {
  101555. t1 = dot1 / (dot1 - dot2);
  101556. ex = sx + tx * t1;
  101557. ey = sy + ty * t1;
  101558. ez = sz + tz * t1;
  101559. ed = sd + td * t1;
  101560. }
  101561. if (sd < 0) {
  101562. //manifold.addPoint(sx,sy,sz,nx,ny,nz,sd,b,c,1,0,false);
  101563. manifold.addPoint(sx, sy, sz, nx, ny, nz, sd, this.flip);
  101564. }
  101565. if (ed < 0) {
  101566. //manifold.addPoint(ex,ey,ez,nx,ny,nz,ed,b,c,4,0,false);
  101567. manifold.addPoint(ex, ey, ez, nx, ny, nz, ed, this.flip);
  101568. }
  101569. }
  101570. }
  101571. };
  101572. OIMO.CylinderCylinderCollisionDetector = function () {
  101573. OIMO.CollisionDetector.call(this);
  101574. };
  101575. OIMO.CylinderCylinderCollisionDetector.prototype = Object.create(OIMO.CollisionDetector.prototype);
  101576. OIMO.CylinderCylinderCollisionDetector.prototype.constructor = OIMO.CylinderCylinderCollisionDetector;
  101577. OIMO.CylinderCylinderCollisionDetector.prototype.getSep = function (c1, c2, sep, pos, dep) {
  101578. var t1x;
  101579. var t1y;
  101580. var t1z;
  101581. var t2x;
  101582. var t2y;
  101583. var t2z;
  101584. var sup = new OIMO.Vec3();
  101585. var len;
  101586. var p1x;
  101587. var p1y;
  101588. var p1z;
  101589. var p2x;
  101590. var p2y;
  101591. var p2z;
  101592. var v01x = c1.position.x;
  101593. var v01y = c1.position.y;
  101594. var v01z = c1.position.z;
  101595. var v02x = c2.position.x;
  101596. var v02y = c2.position.y;
  101597. var v02z = c2.position.z;
  101598. var v0x = v02x - v01x;
  101599. var v0y = v02y - v01y;
  101600. var v0z = v02z - v01z;
  101601. if (v0x * v0x + v0y * v0y + v0z * v0z == 0) v0y = 0.001;
  101602. var nx = -v0x;
  101603. var ny = -v0y;
  101604. var nz = -v0z;
  101605. this.supportPoint(c1, -nx, -ny, -nz, sup);
  101606. var v11x = sup.x;
  101607. var v11y = sup.y;
  101608. var v11z = sup.z;
  101609. this.supportPoint(c2, nx, ny, nz, sup);
  101610. var v12x = sup.x;
  101611. var v12y = sup.y;
  101612. var v12z = sup.z;
  101613. var v1x = v12x - v11x;
  101614. var v1y = v12y - v11y;
  101615. var v1z = v12z - v11z;
  101616. if (v1x * nx + v1y * ny + v1z * nz <= 0) {
  101617. return false;
  101618. }
  101619. nx = v1y * v0z - v1z * v0y;
  101620. ny = v1z * v0x - v1x * v0z;
  101621. nz = v1x * v0y - v1y * v0x;
  101622. if (nx * nx + ny * ny + nz * nz == 0) {
  101623. sep.init(v1x - v0x, v1y - v0y, v1z - v0z);
  101624. sep.normalize(sep);
  101625. pos.init((v11x + v12x) * 0.5, (v11y + v12y) * 0.5, (v11z + v12z) * 0.5);
  101626. return true;
  101627. }
  101628. this.supportPoint(c1, -nx, -ny, -nz, sup);
  101629. var v21x = sup.x;
  101630. var v21y = sup.y;
  101631. var v21z = sup.z;
  101632. this.supportPoint(c2, nx, ny, nz, sup);
  101633. var v22x = sup.x;
  101634. var v22y = sup.y;
  101635. var v22z = sup.z;
  101636. var v2x = v22x - v21x;
  101637. var v2y = v22y - v21y;
  101638. var v2z = v22z - v21z;
  101639. if (v2x * nx + v2y * ny + v2z * nz <= 0) {
  101640. return false;
  101641. }
  101642. t1x = v1x - v0x;
  101643. t1y = v1y - v0y;
  101644. t1z = v1z - v0z;
  101645. t2x = v2x - v0x;
  101646. t2y = v2y - v0y;
  101647. t2z = v2z - v0z;
  101648. nx = t1y * t2z - t1z * t2y;
  101649. ny = t1z * t2x - t1x * t2z;
  101650. nz = t1x * t2y - t1y * t2x;
  101651. if (nx * v0x + ny * v0y + nz * v0z > 0) {
  101652. t1x = v1x;
  101653. t1y = v1y;
  101654. t1z = v1z;
  101655. v1x = v2x;
  101656. v1y = v2y;
  101657. v1z = v2z;
  101658. v2x = t1x;
  101659. v2y = t1y;
  101660. v2z = t1z;
  101661. t1x = v11x;
  101662. t1y = v11y;
  101663. t1z = v11z;
  101664. v11x = v21x;
  101665. v11y = v21y;
  101666. v11z = v21z;
  101667. v21x = t1x;
  101668. v21y = t1y;
  101669. v21z = t1z;
  101670. t1x = v12x;
  101671. t1y = v12y;
  101672. t1z = v12z;
  101673. v12x = v22x;
  101674. v12y = v22y;
  101675. v12z = v22z;
  101676. v22x = t1x;
  101677. v22y = t1y;
  101678. v22z = t1z;
  101679. nx = -nx;
  101680. ny = -ny;
  101681. nz = -nz;
  101682. }
  101683. var iterations = 0;
  101684. while (true) {
  101685. if (++iterations > 100) {
  101686. return false;
  101687. }
  101688. this.supportPoint(c1, -nx, -ny, -nz, sup);
  101689. var v31x = sup.x;
  101690. var v31y = sup.y;
  101691. var v31z = sup.z;
  101692. this.supportPoint(c2, nx, ny, nz, sup);
  101693. var v32x = sup.x;
  101694. var v32y = sup.y;
  101695. var v32z = sup.z;
  101696. var v3x = v32x - v31x;
  101697. var v3y = v32y - v31y;
  101698. var v3z = v32z - v31z;
  101699. if (v3x * nx + v3y * ny + v3z * nz <= 0) {
  101700. return false;
  101701. }
  101702. if ((v1y * v3z - v1z * v3y) * v0x + (v1z * v3x - v1x * v3z) * v0y + (v1x * v3y - v1y * v3x) * v0z < 0) {
  101703. v2x = v3x;
  101704. v2y = v3y;
  101705. v2z = v3z;
  101706. v21x = v31x;
  101707. v21y = v31y;
  101708. v21z = v31z;
  101709. v22x = v32x;
  101710. v22y = v32y;
  101711. v22z = v32z;
  101712. t1x = v1x - v0x;
  101713. t1y = v1y - v0y;
  101714. t1z = v1z - v0z;
  101715. t2x = v3x - v0x;
  101716. t2y = v3y - v0y;
  101717. t2z = v3z - v0z;
  101718. nx = t1y * t2z - t1z * t2y;
  101719. ny = t1z * t2x - t1x * t2z;
  101720. nz = t1x * t2y - t1y * t2x;
  101721. continue;
  101722. }
  101723. if ((v3y * v2z - v3z * v2y) * v0x + (v3z * v2x - v3x * v2z) * v0y + (v3x * v2y - v3y * v2x) * v0z < 0) {
  101724. v1x = v3x;
  101725. v1y = v3y;
  101726. v1z = v3z;
  101727. v11x = v31x;
  101728. v11y = v31y;
  101729. v11z = v31z;
  101730. v12x = v32x;
  101731. v12y = v32y;
  101732. v12z = v32z;
  101733. t1x = v3x - v0x;
  101734. t1y = v3y - v0y;
  101735. t1z = v3z - v0z;
  101736. t2x = v2x - v0x;
  101737. t2y = v2y - v0y;
  101738. t2z = v2z - v0z;
  101739. nx = t1y * t2z - t1z * t2y;
  101740. ny = t1z * t2x - t1x * t2z;
  101741. nz = t1x * t2y - t1y * t2x;
  101742. continue;
  101743. }
  101744. var hit = false;
  101745. while (true) {
  101746. t1x = v2x - v1x;
  101747. t1y = v2y - v1y;
  101748. t1z = v2z - v1z;
  101749. t2x = v3x - v1x;
  101750. t2y = v3y - v1y;
  101751. t2z = v3z - v1z;
  101752. nx = t1y * t2z - t1z * t2y;
  101753. ny = t1z * t2x - t1x * t2z;
  101754. nz = t1x * t2y - t1y * t2x;
  101755. len = 1 / OIMO.sqrt(nx * nx + ny * ny + nz * nz);
  101756. nx *= len;
  101757. ny *= len;
  101758. nz *= len;
  101759. if (nx * v1x + ny * v1y + nz * v1z >= 0 && !hit) {
  101760. var b0 = (v1y * v2z - v1z * v2y) * v3x + (v1z * v2x - v1x * v2z) * v3y + (v1x * v2y - v1y * v2x) * v3z;
  101761. var b1 = (v3y * v2z - v3z * v2y) * v0x + (v3z * v2x - v3x * v2z) * v0y + (v3x * v2y - v3y * v2x) * v0z;
  101762. var b2 = (v0y * v1z - v0z * v1y) * v3x + (v0z * v1x - v0x * v1z) * v3y + (v0x * v1y - v0y * v1x) * v3z;
  101763. var b3 = (v2y * v1z - v2z * v1y) * v0x + (v2z * v1x - v2x * v1z) * v0y + (v2x * v1y - v2y * v1x) * v0z;
  101764. var sum = b0 + b1 + b2 + b3;
  101765. if (sum <= 0) {
  101766. b0 = 0;
  101767. b1 = (v2y * v3z - v2z * v3y) * nx + (v2z * v3x - v2x * v3z) * ny + (v2x * v3y - v2y * v3x) * nz;
  101768. b2 = (v3y * v2z - v3z * v2y) * nx + (v3z * v2x - v3x * v2z) * ny + (v3x * v2y - v3y * v2x) * nz;
  101769. b3 = (v1y * v2z - v1z * v2y) * nx + (v1z * v2x - v1x * v2z) * ny + (v1x * v2y - v1y * v2x) * nz;
  101770. sum = b1 + b2 + b3;
  101771. }
  101772. var inv = 1 / sum;
  101773. p1x = (v01x * b0 + v11x * b1 + v21x * b2 + v31x * b3) * inv;
  101774. p1y = (v01y * b0 + v11y * b1 + v21y * b2 + v31y * b3) * inv;
  101775. p1z = (v01z * b0 + v11z * b1 + v21z * b2 + v31z * b3) * inv;
  101776. p2x = (v02x * b0 + v12x * b1 + v22x * b2 + v32x * b3) * inv;
  101777. p2y = (v02y * b0 + v12y * b1 + v22y * b2 + v32y * b3) * inv;
  101778. p2z = (v02z * b0 + v12z * b1 + v22z * b2 + v32z * b3) * inv;
  101779. hit = true;
  101780. }
  101781. this.supportPoint(c1, -nx, -ny, -nz, sup);
  101782. var v41x = sup.x;
  101783. var v41y = sup.y;
  101784. var v41z = sup.z;
  101785. this.supportPoint(c2, nx, ny, nz, sup);
  101786. var v42x = sup.x;
  101787. var v42y = sup.y;
  101788. var v42z = sup.z;
  101789. var v4x = v42x - v41x;
  101790. var v4y = v42y - v41y;
  101791. var v4z = v42z - v41z;
  101792. var separation = -(v4x * nx + v4y * ny + v4z * nz);
  101793. if ((v4x - v3x) * nx + (v4y - v3y) * ny + (v4z - v3z) * nz <= 0.01 || separation >= 0) {
  101794. if (hit) {
  101795. sep.init(-nx, -ny, -nz);
  101796. pos.init((p1x + p2x) * 0.5, (p1y + p2y) * 0.5, (p1z + p2z) * 0.5);
  101797. dep.x = separation;
  101798. return true;
  101799. }
  101800. return false;
  101801. }
  101802. if (
  101803. (v4y * v1z - v4z * v1y) * v0x +
  101804. (v4z * v1x - v4x * v1z) * v0y +
  101805. (v4x * v1y - v4y * v1x) * v0z < 0
  101806. ) {
  101807. if (
  101808. (v4y * v2z - v4z * v2y) * v0x +
  101809. (v4z * v2x - v4x * v2z) * v0y +
  101810. (v4x * v2y - v4y * v2x) * v0z < 0
  101811. ) {
  101812. v1x = v4x;
  101813. v1y = v4y;
  101814. v1z = v4z;
  101815. v11x = v41x;
  101816. v11y = v41y;
  101817. v11z = v41z;
  101818. v12x = v42x;
  101819. v12y = v42y;
  101820. v12z = v42z;
  101821. } else {
  101822. v3x = v4x;
  101823. v3y = v4y;
  101824. v3z = v4z;
  101825. v31x = v41x;
  101826. v31y = v41y;
  101827. v31z = v41z;
  101828. v32x = v42x;
  101829. v32y = v42y;
  101830. v32z = v42z;
  101831. }
  101832. } else {
  101833. if (
  101834. (v4y * v3z - v4z * v3y) * v0x +
  101835. (v4z * v3x - v4x * v3z) * v0y +
  101836. (v4x * v3y - v4y * v3x) * v0z < 0
  101837. ) {
  101838. v2x = v4x;
  101839. v2y = v4y;
  101840. v2z = v4z;
  101841. v21x = v41x;
  101842. v21y = v41y;
  101843. v21z = v41z;
  101844. v22x = v42x;
  101845. v22y = v42y;
  101846. v22z = v42z;
  101847. } else {
  101848. v1x = v4x;
  101849. v1y = v4y;
  101850. v1z = v4z;
  101851. v11x = v41x;
  101852. v11y = v41y;
  101853. v11z = v41z;
  101854. v12x = v42x;
  101855. v12y = v42y;
  101856. v12z = v42z;
  101857. }
  101858. }
  101859. }
  101860. }
  101861. //return false;
  101862. };
  101863. OIMO.CylinderCylinderCollisionDetector.prototype.supportPoint = function (c, dx, dy, dz, out) {
  101864. var rot = c.rotation.elements;
  101865. var ldx = rot[0] * dx + rot[3] * dy + rot[6] * dz;
  101866. var ldy = rot[1] * dx + rot[4] * dy + rot[7] * dz;
  101867. var ldz = rot[2] * dx + rot[5] * dy + rot[8] * dz;
  101868. var radx = ldx;
  101869. var radz = ldz;
  101870. var len = radx * radx + radz * radz;
  101871. var rad = c.radius;
  101872. var hh = c.halfHeight;
  101873. var ox;
  101874. var oy;
  101875. var oz;
  101876. if (len == 0) {
  101877. if (ldy < 0) {
  101878. ox = rad;
  101879. oy = -hh;
  101880. oz = 0;
  101881. } else {
  101882. ox = rad;
  101883. oy = hh;
  101884. oz = 0;
  101885. }
  101886. } else {
  101887. len = c.radius / OIMO.sqrt(len);
  101888. if (ldy < 0) {
  101889. ox = radx * len;
  101890. oy = -hh;
  101891. oz = radz * len;
  101892. } else {
  101893. ox = radx * len;
  101894. oy = hh;
  101895. oz = radz * len;
  101896. }
  101897. }
  101898. ldx = rot[0] * ox + rot[1] * oy + rot[2] * oz + c.position.x;
  101899. ldy = rot[3] * ox + rot[4] * oy + rot[5] * oz + c.position.y;
  101900. ldz = rot[6] * ox + rot[7] * oy + rot[8] * oz + c.position.z;
  101901. out.init(ldx, ldy, ldz);
  101902. };
  101903. OIMO.CylinderCylinderCollisionDetector.prototype.detectCollision = function (shape1, shape2, manifold) {
  101904. var c1;
  101905. var c2;
  101906. if (shape1.id < shape2.id) {
  101907. c1 = shape1;
  101908. c2 = shape2;
  101909. } else {
  101910. c1 = shape2;
  101911. c2 = shape1;
  101912. }
  101913. var p1 = c1.position;
  101914. var p2 = c2.position;
  101915. var p1x = p1.x;
  101916. var p1y = p1.y;
  101917. var p1z = p1.z;
  101918. var p2x = p2.x;
  101919. var p2y = p2.y;
  101920. var p2z = p2.z;
  101921. var h1 = c1.halfHeight;
  101922. var h2 = c2.halfHeight;
  101923. var n1 = c1.normalDirection;
  101924. var n2 = c2.normalDirection;
  101925. var d1 = c1.halfDirection;
  101926. var d2 = c2.halfDirection;
  101927. var r1 = c1.radius;
  101928. var r2 = c2.radius;
  101929. var n1x = n1.x;
  101930. var n1y = n1.y;
  101931. var n1z = n1.z;
  101932. var n2x = n2.x;
  101933. var n2y = n2.y;
  101934. var n2z = n2.z;
  101935. var d1x = d1.x;
  101936. var d1y = d1.y;
  101937. var d1z = d1.z;
  101938. var d2x = d2.x;
  101939. var d2y = d2.y;
  101940. var d2z = d2.z;
  101941. var dx = p1x - p2x;
  101942. var dy = p1y - p2y;
  101943. var dz = p1z - p2z;
  101944. var len;
  101945. var len1;
  101946. var len2;
  101947. var c;
  101948. var c1x;
  101949. var c1y;
  101950. var c1z;
  101951. var c2x;
  101952. var c2y;
  101953. var c2z;
  101954. var tx;
  101955. var ty;
  101956. var tz;
  101957. var sx;
  101958. var sy;
  101959. var sz;
  101960. var ex;
  101961. var ey;
  101962. var ez;
  101963. var depth1;
  101964. var depth2;
  101965. var dot;
  101966. var t1;
  101967. var t2;
  101968. var sep = new OIMO.Vec3();
  101969. var pos = new OIMO.Vec3();
  101970. var dep = new OIMO.Vec3();
  101971. if (!this.getSep(c1, c2, sep, pos, dep)) return;
  101972. var dot1 = sep.x * n1x + sep.y * n1y + sep.z * n1z;
  101973. var dot2 = sep.x * n2x + sep.y * n2y + sep.z * n2z;
  101974. var right1 = dot1 > 0;
  101975. var right2 = dot2 > 0;
  101976. if (!right1) dot1 = -dot1;
  101977. if (!right2) dot2 = -dot2;
  101978. var state = 0;
  101979. if (dot1 > 0.999 || dot2 > 0.999) {
  101980. if (dot1 > dot2) state = 1;
  101981. else state = 2;
  101982. }
  101983. var nx;
  101984. var ny;
  101985. var nz;
  101986. var depth = dep.x;
  101987. var r00;
  101988. var r01;
  101989. var r02;
  101990. var r10;
  101991. var r11;
  101992. var r12;
  101993. var r20;
  101994. var r21;
  101995. var r22;
  101996. var px;
  101997. var py;
  101998. var pz;
  101999. var pd;
  102000. var a;
  102001. var b;
  102002. var e;
  102003. var f;
  102004. nx = sep.x;
  102005. ny = sep.y;
  102006. nz = sep.z;
  102007. switch (state) {
  102008. case 0:
  102009. manifold.addPoint(pos.x, pos.y, pos.z, nx, ny, nz, depth, false);
  102010. break;
  102011. case 1:
  102012. if (right1) {
  102013. c1x = p1x + d1x;
  102014. c1y = p1y + d1y;
  102015. c1z = p1z + d1z;
  102016. nx = n1x;
  102017. ny = n1y;
  102018. nz = n1z;
  102019. } else {
  102020. c1x = p1x - d1x;
  102021. c1y = p1y - d1y;
  102022. c1z = p1z - d1z;
  102023. nx = -n1x;
  102024. ny = -n1y;
  102025. nz = -n1z;
  102026. }
  102027. dot = nx * n2x + ny * n2y + nz * n2z;
  102028. if (dot < 0) len = h2;
  102029. else len = -h2;
  102030. c2x = p2x + len * n2x;
  102031. c2y = p2y + len * n2y;
  102032. c2z = p2z + len * n2z;
  102033. if (dot2 >= 0.999999) {
  102034. tx = -ny;
  102035. ty = nz;
  102036. tz = nx;
  102037. } else {
  102038. tx = nx;
  102039. ty = ny;
  102040. tz = nz;
  102041. }
  102042. len = tx * n2x + ty * n2y + tz * n2z;
  102043. dx = len * n2x - tx;
  102044. dy = len * n2y - ty;
  102045. dz = len * n2z - tz;
  102046. len = OIMO.sqrt(dx * dx + dy * dy + dz * dz);
  102047. if (len == 0) break;
  102048. len = r2 / len;
  102049. dx *= len;
  102050. dy *= len;
  102051. dz *= len;
  102052. tx = c2x + dx;
  102053. ty = c2y + dy;
  102054. tz = c2z + dz;
  102055. if (dot < -0.96 || dot > 0.96) {
  102056. r00 = n2x * n2x * 1.5 - 0.5;
  102057. r01 = n2x * n2y * 1.5 - n2z * 0.866025403;
  102058. r02 = n2x * n2z * 1.5 + n2y * 0.866025403;
  102059. r10 = n2y * n2x * 1.5 + n2z * 0.866025403;
  102060. r11 = n2y * n2y * 1.5 - 0.5;
  102061. r12 = n2y * n2z * 1.5 - n2x * 0.866025403;
  102062. r20 = n2z * n2x * 1.5 - n2y * 0.866025403;
  102063. r21 = n2z * n2y * 1.5 + n2x * 0.866025403;
  102064. r22 = n2z * n2z * 1.5 - 0.5;
  102065. px = tx;
  102066. py = ty;
  102067. pz = tz;
  102068. pd = nx * (px - c1x) + ny * (py - c1y) + nz * (pz - c1z);
  102069. tx = px - pd * nx - c1x;
  102070. ty = py - pd * ny - c1y;
  102071. tz = pz - pd * nz - c1z;
  102072. len = tx * tx + ty * ty + tz * tz;
  102073. if (len > r1 * r1) {
  102074. len = r1 / OIMO.sqrt(len);
  102075. tx *= len;
  102076. ty *= len;
  102077. tz *= len;
  102078. }
  102079. px = c1x + tx;
  102080. py = c1y + ty;
  102081. pz = c1z + tz;
  102082. manifold.addPoint(px, py, pz, nx, ny, nz, pd, false);
  102083. px = dx * r00 + dy * r01 + dz * r02;
  102084. py = dx * r10 + dy * r11 + dz * r12;
  102085. pz = dx * r20 + dy * r21 + dz * r22;
  102086. px = (dx = px) + c2x;
  102087. py = (dy = py) + c2y;
  102088. pz = (dz = pz) + c2z;
  102089. pd = nx * (px - c1x) + ny * (py - c1y) + nz * (pz - c1z);
  102090. if (pd <= 0) {
  102091. tx = px - pd * nx - c1x;
  102092. ty = py - pd * ny - c1y;
  102093. tz = pz - pd * nz - c1z;
  102094. len = tx * tx + ty * ty + tz * tz;
  102095. if (len > r1 * r1) {
  102096. len = r1 / OIMO.sqrt(len);
  102097. tx *= len;
  102098. ty *= len;
  102099. tz *= len;
  102100. }
  102101. px = c1x + tx;
  102102. py = c1y + ty;
  102103. pz = c1z + tz;
  102104. manifold.addPoint(px, py, pz, nx, ny, nz, pd, false);
  102105. }
  102106. px = dx * r00 + dy * r01 + dz * r02;
  102107. py = dx * r10 + dy * r11 + dz * r12;
  102108. pz = dx * r20 + dy * r21 + dz * r22;
  102109. px = (dx = px) + c2x;
  102110. py = (dy = py) + c2y;
  102111. pz = (dz = pz) + c2z;
  102112. pd = nx * (px - c1x) + ny * (py - c1y) + nz * (pz - c1z);
  102113. if (pd <= 0) {
  102114. tx = px - pd * nx - c1x;
  102115. ty = py - pd * ny - c1y;
  102116. tz = pz - pd * nz - c1z;
  102117. len = tx * tx + ty * ty + tz * tz;
  102118. if (len > r1 * r1) {
  102119. len = r1 / OIMO.sqrt(len);
  102120. tx *= len;
  102121. ty *= len;
  102122. tz *= len;
  102123. }
  102124. px = c1x + tx;
  102125. py = c1y + ty;
  102126. pz = c1z + tz;
  102127. manifold.addPoint(px, py, pz, nx, ny, nz, pd, false);
  102128. }
  102129. } else {
  102130. sx = tx;
  102131. sy = ty;
  102132. sz = tz;
  102133. depth1 = nx * (sx - c1x) + ny * (sy - c1y) + nz * (sz - c1z);
  102134. sx -= depth1 * nx;
  102135. sy -= depth1 * ny;
  102136. sz -= depth1 * nz;
  102137. if (dot > 0) {
  102138. ex = tx + n2x * h2 * 2;
  102139. ey = ty + n2y * h2 * 2;
  102140. ez = tz + n2z * h2 * 2;
  102141. } else {
  102142. ex = tx - n2x * h2 * 2;
  102143. ey = ty - n2y * h2 * 2;
  102144. ez = tz - n2z * h2 * 2;
  102145. }
  102146. depth2 = nx * (ex - c1x) + ny * (ey - c1y) + nz * (ez - c1z);
  102147. ex -= depth2 * nx;
  102148. ey -= depth2 * ny;
  102149. ez -= depth2 * nz;
  102150. dx = c1x - sx;
  102151. dy = c1y - sy;
  102152. dz = c1z - sz;
  102153. tx = ex - sx;
  102154. ty = ey - sy;
  102155. tz = ez - sz;
  102156. a = dx * dx + dy * dy + dz * dz;
  102157. b = dx * tx + dy * ty + dz * tz;
  102158. e = tx * tx + ty * ty + tz * tz;
  102159. f = b * b - e * (a - r1 * r1);
  102160. if (f < 0) break;
  102161. f = OIMO.sqrt(f);
  102162. t1 = (b + f) / e;
  102163. t2 = (b - f) / e;
  102164. if (t2 < t1) {
  102165. len = t1;
  102166. t1 = t2;
  102167. t2 = len;
  102168. }
  102169. if (t2 > 1) t2 = 1;
  102170. if (t1 < 0) t1 = 0;
  102171. tx = sx + (ex - sx) * t1;
  102172. ty = sy + (ey - sy) * t1;
  102173. tz = sz + (ez - sz) * t1;
  102174. ex = sx + (ex - sx) * t2;
  102175. ey = sy + (ey - sy) * t2;
  102176. ez = sz + (ez - sz) * t2;
  102177. sx = tx;
  102178. sy = ty;
  102179. sz = tz;
  102180. len = depth1 + (depth2 - depth1) * t1;
  102181. depth2 = depth1 + (depth2 - depth1) * t2;
  102182. depth1 = len;
  102183. if (depth1 < 0) manifold.addPoint(sx, sy, sz, nx, ny, nz, pd, false);
  102184. if (depth2 < 0) manifold.addPoint(ex, ey, ez, nx, ny, nz, pd, false);
  102185. }
  102186. break;
  102187. case 2:
  102188. if (right2) {
  102189. c2x = p2x - d2x;
  102190. c2y = p2y - d2y;
  102191. c2z = p2z - d2z;
  102192. nx = -n2x;
  102193. ny = -n2y;
  102194. nz = -n2z;
  102195. } else {
  102196. c2x = p2x + d2x;
  102197. c2y = p2y + d2y;
  102198. c2z = p2z + d2z;
  102199. nx = n2x;
  102200. ny = n2y;
  102201. nz = n2z;
  102202. }
  102203. dot = nx * n1x + ny * n1y + nz * n1z;
  102204. if (dot < 0) len = h1;
  102205. else len = -h1;
  102206. c1x = p1x + len * n1x;
  102207. c1y = p1y + len * n1y;
  102208. c1z = p1z + len * n1z;
  102209. if (dot1 >= 0.999999) {
  102210. tx = -ny;
  102211. ty = nz;
  102212. tz = nx;
  102213. } else {
  102214. tx = nx;
  102215. ty = ny;
  102216. tz = nz;
  102217. }
  102218. len = tx * n1x + ty * n1y + tz * n1z;
  102219. dx = len * n1x - tx;
  102220. dy = len * n1y - ty;
  102221. dz = len * n1z - tz;
  102222. len = OIMO.sqrt(dx * dx + dy * dy + dz * dz);
  102223. if (len == 0) break;
  102224. len = r1 / len;
  102225. dx *= len;
  102226. dy *= len;
  102227. dz *= len;
  102228. tx = c1x + dx;
  102229. ty = c1y + dy;
  102230. tz = c1z + dz;
  102231. if (dot < -0.96 || dot > 0.96) {
  102232. r00 = n1x * n1x * 1.5 - 0.5;
  102233. r01 = n1x * n1y * 1.5 - n1z * 0.866025403;
  102234. r02 = n1x * n1z * 1.5 + n1y * 0.866025403;
  102235. r10 = n1y * n1x * 1.5 + n1z * 0.866025403;
  102236. r11 = n1y * n1y * 1.5 - 0.5;
  102237. r12 = n1y * n1z * 1.5 - n1x * 0.866025403;
  102238. r20 = n1z * n1x * 1.5 - n1y * 0.866025403;
  102239. r21 = n1z * n1y * 1.5 + n1x * 0.866025403;
  102240. r22 = n1z * n1z * 1.5 - 0.5;
  102241. px = tx;
  102242. py = ty;
  102243. pz = tz;
  102244. pd = nx * (px - c2x) + ny * (py - c2y) + nz * (pz - c2z);
  102245. tx = px - pd * nx - c2x;
  102246. ty = py - pd * ny - c2y;
  102247. tz = pz - pd * nz - c2z;
  102248. len = tx * tx + ty * ty + tz * tz;
  102249. if (len > r2 * r2) {
  102250. len = r2 / OIMO.sqrt(len);
  102251. tx *= len;
  102252. ty *= len;
  102253. tz *= len;
  102254. }
  102255. px = c2x + tx;
  102256. py = c2y + ty;
  102257. pz = c2z + tz;
  102258. manifold.addPoint(px, py, pz, -nx, -ny, -nz, pd, false);
  102259. px = dx * r00 + dy * r01 + dz * r02;
  102260. py = dx * r10 + dy * r11 + dz * r12;
  102261. pz = dx * r20 + dy * r21 + dz * r22;
  102262. px = (dx = px) + c1x;
  102263. py = (dy = py) + c1y;
  102264. pz = (dz = pz) + c1z;
  102265. pd = nx * (px - c2x) + ny * (py - c2y) + nz * (pz - c2z);
  102266. if (pd <= 0) {
  102267. tx = px - pd * nx - c2x;
  102268. ty = py - pd * ny - c2y;
  102269. tz = pz - pd * nz - c2z;
  102270. len = tx * tx + ty * ty + tz * tz;
  102271. if (len > r2 * r2) {
  102272. len = r2 / OIMO.sqrt(len);
  102273. tx *= len;
  102274. ty *= len;
  102275. tz *= len;
  102276. }
  102277. px = c2x + tx;
  102278. py = c2y + ty;
  102279. pz = c2z + tz;
  102280. manifold.addPoint(px, py, pz, -nx, -ny, -nz, pd, false);
  102281. }
  102282. px = dx * r00 + dy * r01 + dz * r02;
  102283. py = dx * r10 + dy * r11 + dz * r12;
  102284. pz = dx * r20 + dy * r21 + dz * r22;
  102285. px = (dx = px) + c1x;
  102286. py = (dy = py) + c1y;
  102287. pz = (dz = pz) + c1z;
  102288. pd = nx * (px - c2x) + ny * (py - c2y) + nz * (pz - c2z);
  102289. if (pd <= 0) {
  102290. tx = px - pd * nx - c2x;
  102291. ty = py - pd * ny - c2y;
  102292. tz = pz - pd * nz - c2z;
  102293. len = tx * tx + ty * ty + tz * tz;
  102294. if (len > r2 * r2) {
  102295. len = r2 / OIMO.sqrt(len);
  102296. tx *= len;
  102297. ty *= len;
  102298. tz *= len;
  102299. }
  102300. px = c2x + tx;
  102301. py = c2y + ty;
  102302. pz = c2z + tz;
  102303. manifold.addPoint(px, py, pz, -nx, -ny, -nz, pd, false);
  102304. }
  102305. } else {
  102306. sx = tx;
  102307. sy = ty;
  102308. sz = tz;
  102309. depth1 = nx * (sx - c2x) + ny * (sy - c2y) + nz * (sz - c2z);
  102310. sx -= depth1 * nx;
  102311. sy -= depth1 * ny;
  102312. sz -= depth1 * nz;
  102313. if (dot > 0) {
  102314. ex = tx + n1x * h1 * 2;
  102315. ey = ty + n1y * h1 * 2;
  102316. ez = tz + n1z * h1 * 2;
  102317. } else {
  102318. ex = tx - n1x * h1 * 2;
  102319. ey = ty - n1y * h1 * 2;
  102320. ez = tz - n1z * h1 * 2;
  102321. }
  102322. depth2 = nx * (ex - c2x) + ny * (ey - c2y) + nz * (ez - c2z);
  102323. ex -= depth2 * nx;
  102324. ey -= depth2 * ny;
  102325. ez -= depth2 * nz;
  102326. dx = c2x - sx;
  102327. dy = c2y - sy;
  102328. dz = c2z - sz;
  102329. tx = ex - sx;
  102330. ty = ey - sy;
  102331. tz = ez - sz;
  102332. a = dx * dx + dy * dy + dz * dz;
  102333. b = dx * tx + dy * ty + dz * tz;
  102334. e = tx * tx + ty * ty + tz * tz;
  102335. f = b * b - e * (a - r2 * r2);
  102336. if (f < 0) break;
  102337. f = OIMO.sqrt(f);
  102338. t1 = (b + f) / e;
  102339. t2 = (b - f) / e;
  102340. if (t2 < t1) {
  102341. len = t1;
  102342. t1 = t2;
  102343. t2 = len;
  102344. }
  102345. if (t2 > 1) t2 = 1;
  102346. if (t1 < 0) t1 = 0;
  102347. tx = sx + (ex - sx) * t1;
  102348. ty = sy + (ey - sy) * t1;
  102349. tz = sz + (ez - sz) * t1;
  102350. ex = sx + (ex - sx) * t2;
  102351. ey = sy + (ey - sy) * t2;
  102352. ez = sz + (ez - sz) * t2;
  102353. sx = tx;
  102354. sy = ty;
  102355. sz = tz;
  102356. len = depth1 + (depth2 - depth1) * t1;
  102357. depth2 = depth1 + (depth2 - depth1) * t2;
  102358. depth1 = len;
  102359. if (depth1 < 0) {
  102360. manifold.addPoint(sx, sy, sz, -nx, -ny, -nz, depth1, false);
  102361. }
  102362. if (depth2 < 0) {
  102363. manifold.addPoint(ex, ey, ez, -nx, -ny, -nz, depth2, false);
  102364. }
  102365. }
  102366. break;
  102367. }
  102368. };
  102369. OIMO.SphereCylinderCollisionDetector = function (flip) {
  102370. OIMO.CollisionDetector.call(this);
  102371. this.flip = flip;
  102372. };
  102373. OIMO.SphereCylinderCollisionDetector.prototype = Object.create(OIMO.CollisionDetector.prototype);
  102374. OIMO.SphereCylinderCollisionDetector.prototype.constructor = OIMO.SphereCylinderCollisionDetector;
  102375. OIMO.SphereCylinderCollisionDetector.prototype.detectCollision = function (shape1, shape2, manifold) {
  102376. var s;
  102377. var c;
  102378. if (this.flip) {
  102379. s = shape2;
  102380. c = shape1;
  102381. } else {
  102382. s = shape1;
  102383. c = shape2;
  102384. }
  102385. var ps = s.position;
  102386. var psx = ps.x;
  102387. var psy = ps.y;
  102388. var psz = ps.z;
  102389. var pc = c.position;
  102390. var pcx = pc.x;
  102391. var pcy = pc.y;
  102392. var pcz = pc.z;
  102393. var dirx = c.normalDirection.x;
  102394. var diry = c.normalDirection.y;
  102395. var dirz = c.normalDirection.z;
  102396. var rads = s.radius;
  102397. var radc = c.radius;
  102398. var rad2 = rads + radc;
  102399. var halfh = c.halfHeight;
  102400. var dx = psx - pcx;
  102401. var dy = psy - pcy;
  102402. var dz = psz - pcz;
  102403. var dot = dx * dirx + dy * diry + dz * dirz;
  102404. if (dot < -halfh - rads || dot > halfh + rads) return;
  102405. var cx = pcx + dot * dirx;
  102406. var cy = pcy + dot * diry;
  102407. var cz = pcz + dot * dirz;
  102408. var d2x = psx - cx;
  102409. var d2y = psy - cy;
  102410. var d2z = psz - cz;
  102411. var len = d2x * d2x + d2y * d2y + d2z * d2z;
  102412. if (len > rad2 * rad2) return;
  102413. if (len > radc * radc) {
  102414. len = radc / OIMO.sqrt(len);
  102415. d2x *= len;
  102416. d2y *= len;
  102417. d2z *= len;
  102418. }
  102419. if (dot < -halfh) dot = -halfh;
  102420. else if (dot > halfh) dot = halfh;
  102421. cx = pcx + dot * dirx + d2x;
  102422. cy = pcy + dot * diry + d2y;
  102423. cz = pcz + dot * dirz + d2z;
  102424. dx = cx - psx;
  102425. dy = cy - psy;
  102426. dz = cz - psz;
  102427. len = dx * dx + dy * dy + dz * dz;
  102428. var invLen;
  102429. if (len > 0 && len < rads * rads) {
  102430. len = OIMO.sqrt(len);
  102431. invLen = 1 / len;
  102432. dx *= invLen;
  102433. dy *= invLen;
  102434. dz *= invLen;
  102435. ///result.addContactInfo(psx+dx*rads,psy+dy*rads,psz+dz*rads,dx,dy,dz,len-rads,s,c,0,0,false);
  102436. manifold.addPoint(psx + dx * rads, psy + dy * rads, psz + dz * rads, dx, dy, dz, len - rads, this.flip);
  102437. }
  102438. };
  102439. /**
  102440. * Class for checking collisions between 2 tetras,
  102441. * a shape that is made with 4 vertices and 4 faces
  102442. * arranged in triangles. With this algorigthm, soft
  102443. * body physics are possible and easier to implement.
  102444. * @author xprogram
  102445. */
  102446. OIMO.TetraTetraCollisionDetector = function () {
  102447. OIMO.CollisionDetector.call(this);
  102448. };
  102449. OIMO.TetraTetraCollisionDetector.prototype = Object.create(OIMO.CollisionDetector.prototype);
  102450. OIMO.TetraTetraCollisionDetector.prototype.constructor = OIMO.TetraTetraCollisionDetector;
  102451. OIMO.TetraTetraCollisionDetector.prototype.detectCollision = function (tet1, tet2, manifold) {
  102452. /*
  102453. * What we are doing:
  102454. * Each tetra is represented by four 3D triangles. The only
  102455. * quick way of finding if another tetra is within the other
  102456. * tetra is to see if a single vertex is within the triangles
  102457. * of the other tetra. So, for example, a tetra is represented
  102458. * by points B, C, D and E with triangles BCD, BCE, DCE and BDE.
  102459. * There is another tetra with a vertex A which was detected for
  102460. * collision by the broadphase. Now, if the point A is between ALL
  102461. * triangles of the other tetra (BCD, BCE, etc.) then the collision
  102462. * is valid and we can pass point A to the manifold. Since the only
  102463. * points on the tetra are the 4 vertices, collision detection is
  102464. * not so complex. However, it can be time-consuming because we
  102465. * need to split the 3D triangles into three 2D triangles each for
  102466. * collision detection.
  102467. */
  102468. var i, j, vec, fs1 = tet1.faces, vs1 = tet1.verts, fs2 = tet2.faces, vs2 = tet2.verts;
  102469. var j1, j2, j3, ts = 0; // Triangle vertices `j1`, `j2` and `j3`
  102470. // fs is undeclared
  102471. var fs = fs1;
  102472. for (i = 0; i < 4; i++) {
  102473. vec = vs1[i];
  102474. for (j = 0; j < 4; j++) {
  102475. j1 = vs2[fs[i].a];
  102476. j2 = vs2[fs[i].b];
  102477. j3 = vs2[fs[i].c];
  102478. if (
  102479. tricheck(pt(vec.x, vec.y), pt(j1.x, j1.y), pt(j2.x, j2.y), pt(j3.x, j3.y)) &&
  102480. tricheck(pt(vec.x, vec.z), pt(j1.x, j1.z), pt(j2.x, j2.z), pt(j3.x, j3.z)) &&
  102481. tricheck(pt(vec.z, vec.y), pt(j1.z, j1.y), pt(j2.z, j2.y), pt(j3.z, j3.y))
  102482. )
  102483. ts++;
  102484. if (ts === 4) // Only add point if it is inside all 4 triangles
  102485. manifold.addPoint(vec);
  102486. }
  102487. }
  102488. };
  102489. // Taken from: http://jsfiddle.net/PerroAZUL/zdaY8/1/
  102490. function tricheck(p, p0, p1, p2) {
  102491. var A = 0.5 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  102492. var sg = A < 0 ? -1 : 1;
  102493. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sg;
  102494. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sg;
  102495. return s > 0 && t > 0 && (s + t) < 2 * A * sg;
  102496. }
  102497. function pt(x, y) { return { x: x, y: y }; }
  102498. /**
  102499. * An axis-aligned bounding box.
  102500. * @author saharan
  102501. * @author lo-th
  102502. */
  102503. OIMO.AABB = function (minX, maxX, minY, maxY, minZ, maxZ) {
  102504. this.elements = new OIMO_ARRAY_TYPE(6);
  102505. var te = this.elements;
  102506. te[0] = minX || 0; te[1] = minY || 0; te[2] = minZ || 0;
  102507. te[3] = maxX || 0; te[4] = maxY || 0; te[5] = maxZ || 0;
  102508. };
  102509. OIMO.AABB.prototype = {
  102510. constructor: OIMO.AABB,
  102511. set: function (minX, maxX, minY, maxY, minZ, maxZ) {
  102512. var te = this.elements;
  102513. te[0] = minX; te[3] = maxX;
  102514. te[1] = minY; te[4] = maxY;
  102515. te[2] = minZ; te[5] = maxZ;
  102516. return this;
  102517. },
  102518. intersectTest: function (aabb) {
  102519. var te = this.elements;
  102520. var ue = aabb.elements;
  102521. 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];
  102522. },
  102523. intersectTestTwo: function (aabb) {
  102524. var te = this.elements;
  102525. var ue = aabb.elements;
  102526. 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];
  102527. },
  102528. clone: function () {
  102529. return new this.constructor().fromArray(this.elements);
  102530. },
  102531. copy: function (aabb, margin) {
  102532. var m = margin || 0;
  102533. var me = aabb.elements;
  102534. this.set(me[0] - m, me[3] + m, me[1] - m, me[4] + m, me[2] - m, me[5] + m);
  102535. return this;
  102536. },
  102537. fromArray: function (array) {
  102538. this.elements.set(array);
  102539. return this;
  102540. },
  102541. // Set this AABB to the combined AABB of aabb1 and aabb2.
  102542. combine: function (aabb1, aabb2) {
  102543. var a = aabb1.elements;
  102544. var b = aabb2.elements;
  102545. var te = this.elements;
  102546. te[0] = a[0] < b[0] ? a[0] : b[0];
  102547. te[1] = a[1] < b[1] ? a[1] : b[1];
  102548. te[2] = a[2] < b[2] ? a[2] : b[2];
  102549. te[3] = a[3] > b[3] ? a[3] : b[3];
  102550. te[4] = a[4] > b[4] ? a[4] : b[4];
  102551. te[5] = a[5] > b[5] ? a[5] : b[5];
  102552. return this;
  102553. },
  102554. // Get the surface area.
  102555. surfaceArea: function () {
  102556. var te = this.elements;
  102557. var a = te[3] - te[0];
  102558. var h = te[4] - te[1];
  102559. var d = te[5] - te[2];
  102560. return 2 * (a * (h + d) + h * d);
  102561. },
  102562. // Get whether the AABB intersects with the point or not.
  102563. intersectsWithPoint: function (x, y, z) {
  102564. var te = this.elements;
  102565. return x >= te[0] && x <= te[3] && y >= te[1] && y <= te[4] && z >= te[2] && z <= te[5];
  102566. },
  102567. /**
  102568. * Set the AABB from an array
  102569. * of vertices. From THREE.
  102570. * @author mrdoob
  102571. * @author xprogram
  102572. */
  102573. setFromPoints: function (arr) {
  102574. this.makeEmpty();
  102575. for (var i = 0; i < arr.length; i++) {
  102576. this.expandByPoint(arr[i]);
  102577. }
  102578. },
  102579. makeEmpty: function () {
  102580. this.set(-Infinity, -Infinity, -Infinity, Infinity, Infinity, Infinity);
  102581. },
  102582. expandByPoint: function (pt) {
  102583. var te = this.elements;
  102584. this.set(
  102585. OIMO.min(te[0], pt.x), OIMO.min(te[1], pt.y), OIMO.min(te[2], pt.z),
  102586. OIMO.max(te[3], pt.x), OIMO.max(te[4], pt.y), OIMO.max(te[5], pt.z)
  102587. );
  102588. }
  102589. };
  102590. /**
  102591. * A proxy is used for broad-phase collecting pairs that can be colliding.
  102592. */
  102593. OIMO.Proxy = function (shape) {
  102594. // The parent shape.
  102595. this.shape = shape;
  102596. // The axis-aligned bounding box.
  102597. this.aabb = shape.aabb;
  102598. };
  102599. OIMO.Proxy.prototype = {
  102600. constructor: OIMO.Proxy,
  102601. // Update the proxy.
  102602. update: function () {
  102603. OIMO.Error("Proxy", "Inheritance error.");
  102604. }
  102605. };
  102606. /**
  102607. * A basic implementation of proxies.
  102608. * @author saharan
  102609. */
  102610. OIMO.BasicProxy = function (shape) {
  102611. OIMO.Proxy.call(this, shape);
  102612. this.id = OIMO.proxyID++;
  102613. };
  102614. OIMO.BasicProxy.prototype = Object.create(OIMO.Proxy.prototype);
  102615. OIMO.BasicProxy.prototype.constructor = OIMO.BasicProxy;
  102616. OIMO.BasicProxy.prototype.update = function () {
  102617. };
  102618. /**
  102619. * The broad-phase is used for collecting all possible pairs for collision.
  102620. */
  102621. OIMO.BroadPhase = function () {
  102622. this.types = OIMO.BR_NULL;
  102623. this.numPairChecks = 0;
  102624. this.numPairs = 0;
  102625. this.pairs = [];
  102626. };
  102627. OIMO.BroadPhase.prototype = {
  102628. constructor: OIMO.BroadPhase,
  102629. /**
  102630. * Create a new proxy.
  102631. * @param shape
  102632. * @return
  102633. */
  102634. createProxy: function (shape) {
  102635. OIMO.Error("BroadPhase", "Inheritance error.");
  102636. },
  102637. /**
  102638. * Add the proxy into the broad-phase.
  102639. * @param proxy
  102640. */
  102641. addProxy: function (proxy) {
  102642. OIMO.Error("BroadPhase", "Inheritance error.");
  102643. },
  102644. /**
  102645. * Remove the proxy from the broad-phase.
  102646. * @param proxy
  102647. */
  102648. removeProxy: function (proxy) {
  102649. OIMO.Error("BroadPhase", "Inheritance error.");
  102650. },
  102651. /**
  102652. * Returns whether the pair is available or not.
  102653. * @param s1
  102654. * @param s2
  102655. * @return
  102656. */
  102657. isAvailablePair: function (s1, s2) {
  102658. var b1 = s1.parent;
  102659. var b2 = s2.parent;
  102660. if (b1 == b2 || // same parents
  102661. (!b1.isDynamic && !b2.isDynamic) || // static or kinematic object
  102662. (s1.belongsTo & s2.collidesWith) == 0 ||
  102663. (s2.belongsTo & s1.collidesWith) == 0 // collision filtering
  102664. ) { return false; }
  102665. var js;
  102666. if (b1.numJoints < b2.numJoints) js = b1.jointLink;
  102667. else js = b2.jointLink;
  102668. while (js !== null) {
  102669. var joint = js.joint;
  102670. if (!joint.allowCollision && ((joint.body1 == b1 && joint.body2 == b2) || (joint.body1 == b2 && joint.body2 == b1))) { return false; }
  102671. js = js.next;
  102672. }
  102673. return true;
  102674. },
  102675. // Detect overlapping pairs.
  102676. detectPairs: function () {
  102677. // clear old
  102678. this.pairs = [];
  102679. this.numPairs = 0;
  102680. this.numPairChecks = 0;
  102681. this.collectPairs();
  102682. },
  102683. collectPairs: function () {
  102684. OIMO.Error("BroadPhase", "Inheritance error.");
  102685. },
  102686. addPair: function (s1, s2) {
  102687. var pair = new OIMO.Pair(s1, s2);
  102688. this.pairs.push(pair);
  102689. this.numPairs++;
  102690. }
  102691. };
  102692. /**
  102693. * A broad-phase algorithm with brute-force search.
  102694. * This always checks for all possible pairs.
  102695. */
  102696. OIMO.BruteForceBroadPhase = function () {
  102697. OIMO.BroadPhase.call(this);
  102698. this.types = OIMO.BR_BRUTE_FORCE;;
  102699. //this.numProxies=0;
  102700. ///this.maxProxies = 256;
  102701. this.proxies = [];
  102702. //this.proxies.length = 256;
  102703. };
  102704. OIMO.BruteForceBroadPhase.prototype = Object.create(OIMO.BroadPhase.prototype);
  102705. OIMO.BruteForceBroadPhase.prototype.constructor = OIMO.BruteForceBroadPhase;
  102706. OIMO.BruteForceBroadPhase.prototype.createProxy = function (shape) {
  102707. return new OIMO.BasicProxy(shape);
  102708. };
  102709. OIMO.BruteForceBroadPhase.prototype.addProxy = function (proxy) {
  102710. /*if(this.numProxies==this.maxProxies){
  102711. //this.maxProxies<<=1;
  102712. this.maxProxies*=2;
  102713. var newProxies=[];
  102714. newProxies.length = this.maxProxies;
  102715. var i = this.numProxies;
  102716. while(i--){
  102717. //for(var i=0, l=this.numProxies;i<l;i++){
  102718. newProxies[i]=this.proxies[i];
  102719. }
  102720. this.proxies=newProxies;
  102721. }*/
  102722. //this.proxies[this.numProxies++] = proxy;
  102723. this.proxies.push(proxy);
  102724. //this.numProxies++;
  102725. };
  102726. OIMO.BruteForceBroadPhase.prototype.removeProxy = function (proxy) {
  102727. var n = this.proxies.indexOf(proxy);
  102728. if (n > -1) {
  102729. this.proxies.splice(n, 1);
  102730. //this.numProxies--;
  102731. }
  102732. /*var i = this.numProxies;
  102733. while(i--){
  102734. //for(var i=0, l=this.numProxies;i<l;i++){
  102735. if(this.proxies[i] == proxy){
  102736. this.proxies[i] = this.proxies[--this.numProxies];
  102737. this.proxies[this.numProxies] = null;
  102738. return;
  102739. }
  102740. }*/
  102741. };
  102742. OIMO.BruteForceBroadPhase.prototype.collectPairs = function () {
  102743. var i = 0, j, p1, p2;
  102744. var px = this.proxies;
  102745. var l = px.length;//this.numProxies;
  102746. //var ar1 = [];
  102747. //var ar2 = [];
  102748. //for( i = px.length ; i-- ; ar1[ i ] = px[ i ] ){};
  102749. //for( i = px.length ; i-- ; ar2[ i ] = px[ i ] ){};
  102750. //var ar1 = JSON.parse(JSON.stringify(this.proxies))
  102751. //var ar2 = JSON.parse(JSON.stringify(this.proxies))
  102752. this.numPairChecks = l * (l - 1) >> 1;
  102753. //this.numPairChecks=this.numProxies*(this.numProxies-1)*0.5;
  102754. while (i < l) {
  102755. p1 = px[i++];
  102756. j = i + 1;
  102757. while (j < l) {
  102758. p2 = px[j++];
  102759. if (p1.aabb.intersectTest(p2.aabb) || !this.isAvailablePair(p1.shape, p2.shape)) continue;
  102760. this.addPair(p1.shape, p2.shape);
  102761. }
  102762. }
  102763. };
  102764. /**
  102765. * A pair of shapes that may collide.
  102766. * @author saharan
  102767. */
  102768. OIMO.Pair = function (s1, s2) {
  102769. // The first shape.
  102770. this.shape1 = s1 || null;
  102771. // The second shape.
  102772. this.shape2 = s2 || null;
  102773. };
  102774. /**
  102775. * A projection axis for sweep and prune broad-phase.
  102776. * @author saharan
  102777. */
  102778. OIMO.SAPAxis = function () {
  102779. this.numElements = 0;
  102780. this.bufferSize = 256;
  102781. this.elements = [];
  102782. this.elements.length = this.bufferSize;
  102783. this.stack = new OIMO_ARRAY_TYPE(64);
  102784. };
  102785. OIMO.SAPAxis.prototype = {
  102786. constructor: OIMO.SAPAxis,
  102787. addElements: function (min, max) {
  102788. if (this.numElements + 2 >= this.bufferSize) {
  102789. //this.bufferSize<<=1;
  102790. this.bufferSize *= 2;
  102791. var newElements = [];
  102792. var i = this.numElements;
  102793. while (i--) {
  102794. //for(var i=0, l=this.numElements; i<l; i++){
  102795. newElements[i] = this.elements[i];
  102796. }
  102797. }
  102798. this.elements[this.numElements++] = min;
  102799. this.elements[this.numElements++] = max;
  102800. },
  102801. removeElements: function (min, max) {
  102802. var minIndex = -1;
  102803. var maxIndex = -1;
  102804. for (var i = 0, l = this.numElements; i < l; i++) {
  102805. var e = this.elements[i];
  102806. if (e == min || e == max) {
  102807. if (minIndex == -1) {
  102808. minIndex = i;
  102809. } else {
  102810. maxIndex = i;
  102811. break;
  102812. }
  102813. }
  102814. }
  102815. for (i = minIndex + 1, l = maxIndex; i < l; i++) {
  102816. this.elements[i - 1] = this.elements[i];
  102817. }
  102818. for (i = maxIndex + 1, l = this.numElements; i < l; i++) {
  102819. this.elements[i - 2] = this.elements[i];
  102820. }
  102821. this.elements[--this.numElements] = null;
  102822. this.elements[--this.numElements] = null;
  102823. },
  102824. sort: function () {
  102825. var count = 0;
  102826. var threshold = 1;
  102827. while ((this.numElements >> threshold) != 0) threshold++;
  102828. threshold = threshold * this.numElements >> 2;
  102829. count = 0;
  102830. var giveup = false;
  102831. var elements = this.elements;
  102832. for (var i = 1, l = this.numElements; i < l; i++) { // try insertion sort
  102833. var tmp = elements[i];
  102834. var pivot = tmp.value;
  102835. var tmp2 = elements[i - 1];
  102836. if (tmp2.value > pivot) {
  102837. var j = i;
  102838. do {
  102839. elements[j] = tmp2;
  102840. if (--j == 0) break;
  102841. tmp2 = elements[j - 1];
  102842. } while (tmp2.value > pivot);
  102843. elements[j] = tmp;
  102844. count += i - j;
  102845. if (count > threshold) {
  102846. giveup = true; // stop and use quick sort
  102847. break;
  102848. }
  102849. }
  102850. }
  102851. if (!giveup) return;
  102852. count = 2; var stack = this.stack;
  102853. stack[0] = 0;
  102854. stack[1] = this.numElements - 1;
  102855. while (count > 0) {
  102856. var right = stack[--count];
  102857. var left = stack[--count];
  102858. var diff = right - left;
  102859. if (diff > 16) { // quick sort
  102860. //var mid=left+(diff>>1);
  102861. var mid = left + (OIMO.floor(diff * 0.5));
  102862. tmp = elements[mid];
  102863. elements[mid] = elements[right];
  102864. elements[right] = tmp;
  102865. pivot = tmp.value;
  102866. i = left - 1;
  102867. j = right;
  102868. while (true) {
  102869. var ei;
  102870. var ej;
  102871. do { ei = elements[++i]; } while (ei.value < pivot);
  102872. do { ej = elements[--j]; } while (pivot < ej.value && j != left);
  102873. if (i >= j) break;
  102874. elements[i] = ej;
  102875. elements[j] = ei;
  102876. }
  102877. elements[right] = elements[i];
  102878. elements[i] = tmp;
  102879. if (i - left > right - i) {
  102880. stack[count++] = left;
  102881. stack[count++] = i - 1;
  102882. stack[count++] = i + 1;
  102883. stack[count++] = right;
  102884. } else {
  102885. stack[count++] = i + 1;
  102886. stack[count++] = right;
  102887. stack[count++] = left;
  102888. stack[count++] = i - 1;
  102889. }
  102890. } else {
  102891. for (i = left + 1; i <= right; i++) {
  102892. tmp = elements[i];
  102893. pivot = tmp.value;
  102894. tmp2 = elements[i - 1];
  102895. if (tmp2.value > pivot) {
  102896. j = i;
  102897. do {
  102898. elements[j] = tmp2;
  102899. if (--j == 0) break;
  102900. tmp2 = elements[j - 1];
  102901. } while (tmp2.value > pivot);
  102902. elements[j] = tmp;
  102903. }
  102904. }
  102905. }
  102906. }
  102907. },
  102908. calculateTestCount: function () {
  102909. var num = 1;
  102910. var sum = 0;
  102911. for (var i = 1, l = this.numElements; i < l; i++) {
  102912. if (this.elements[i].max) {
  102913. num--;
  102914. } else {
  102915. sum += num;
  102916. num++;
  102917. }
  102918. }
  102919. return sum;
  102920. }
  102921. }
  102922. /**
  102923. * A broad-phase collision detection algorithm using sweep and prune.
  102924. * @author saharan
  102925. * @author lo-th
  102926. */
  102927. OIMO.SAPBroadPhase = function () {
  102928. OIMO.BroadPhase.call(this);
  102929. this.types = OIMO.BR_SWEEP_AND_PRUNE;
  102930. this.numElementsD = 0;
  102931. this.numElementsS = 0;
  102932. // dynamic proxies
  102933. this.axesD = [
  102934. new OIMO.SAPAxis(),
  102935. new OIMO.SAPAxis(),
  102936. new OIMO.SAPAxis()
  102937. ];
  102938. // static or sleeping proxies
  102939. this.axesS = [
  102940. new OIMO.SAPAxis(),
  102941. new OIMO.SAPAxis(),
  102942. new OIMO.SAPAxis()
  102943. ];
  102944. this.index1 = 0;
  102945. this.index2 = 1;
  102946. };
  102947. OIMO.SAPBroadPhase.prototype = Object.create(OIMO.BroadPhase.prototype);
  102948. OIMO.SAPBroadPhase.prototype.constructor = OIMO.SAPBroadPhase;
  102949. OIMO.SAPBroadPhase.prototype.createProxy = function (shape) {
  102950. return new OIMO.SAPProxy(this, shape);
  102951. };
  102952. OIMO.SAPBroadPhase.prototype.addProxy = function (proxy) {
  102953. var p = proxy;
  102954. if (p.isDynamic()) {
  102955. this.axesD[0].addElements(p.min[0], p.max[0]);
  102956. this.axesD[1].addElements(p.min[1], p.max[1]);
  102957. this.axesD[2].addElements(p.min[2], p.max[2]);
  102958. p.belongsTo = 1;
  102959. this.numElementsD += 2;
  102960. } else {
  102961. this.axesS[0].addElements(p.min[0], p.max[0]);
  102962. this.axesS[1].addElements(p.min[1], p.max[1]);
  102963. this.axesS[2].addElements(p.min[2], p.max[2]);
  102964. p.belongsTo = 2;
  102965. this.numElementsS += 2;
  102966. }
  102967. };
  102968. OIMO.SAPBroadPhase.prototype.removeProxy = function (proxy) {
  102969. var p = proxy;
  102970. if (p.belongsTo == 0) return;
  102971. /*else if ( p.belongsTo == 1 ) {
  102972. this.axesD[0].removeElements( p.min[0], p.max[0] );
  102973. this.axesD[1].removeElements( p.min[1], p.max[1] );
  102974. this.axesD[2].removeElements( p.min[2], p.max[2] );
  102975. this.numElementsD -= 2;
  102976. } else if ( p.belongsTo == 2 ) {
  102977. this.axesS[0].removeElements( p.min[0], p.max[0] );
  102978. this.axesS[1].removeElements( p.min[1], p.max[1] );
  102979. this.axesS[2].removeElements( p.min[2], p.max[2] );
  102980. this.numElementsS -= 2;
  102981. }*/
  102982. switch (p.belongsTo) {
  102983. case 1:
  102984. this.axesD[0].removeElements(p.min[0], p.max[0]);
  102985. this.axesD[1].removeElements(p.min[1], p.max[1]);
  102986. this.axesD[2].removeElements(p.min[2], p.max[2]);
  102987. this.numElementsD -= 2;
  102988. break;
  102989. case 2:
  102990. this.axesS[0].removeElements(p.min[0], p.max[0]);
  102991. this.axesS[1].removeElements(p.min[1], p.max[1]);
  102992. this.axesS[2].removeElements(p.min[2], p.max[2]);
  102993. this.numElementsS -= 2;
  102994. break;
  102995. }
  102996. p.belongsTo = 0;
  102997. };
  102998. OIMO.SAPBroadPhase.prototype.collectPairs = function () {
  102999. if (this.numElementsD == 0) return;
  103000. var axis1 = this.axesD[this.index1];
  103001. var axis2 = this.axesD[this.index2];
  103002. axis1.sort();
  103003. axis2.sort();
  103004. var count1 = axis1.calculateTestCount();
  103005. var count2 = axis2.calculateTestCount();
  103006. var elementsD;
  103007. var elementsS;
  103008. if (count1 <= count2) {// select the best axis
  103009. axis2 = this.axesS[this.index1];
  103010. axis2.sort();
  103011. elementsD = axis1.elements;
  103012. elementsS = axis2.elements;
  103013. } else {
  103014. axis1 = this.axesS[this.index2];
  103015. axis1.sort();
  103016. elementsD = axis2.elements;
  103017. elementsS = axis1.elements;
  103018. this.index1 ^= this.index2;
  103019. this.index2 ^= this.index1;
  103020. this.index1 ^= this.index2;
  103021. }
  103022. var activeD;
  103023. var activeS;
  103024. var p = 0;
  103025. var q = 0;
  103026. while (p < this.numElementsD) {
  103027. var e1;
  103028. var dyn;
  103029. if (q == this.numElementsS) {
  103030. e1 = elementsD[p];
  103031. dyn = true;
  103032. p++;
  103033. } else {
  103034. var d = elementsD[p];
  103035. var s = elementsS[q];
  103036. if (d.value < s.value) {
  103037. e1 = d;
  103038. dyn = true;
  103039. p++;
  103040. } else {
  103041. e1 = s;
  103042. dyn = false;
  103043. q++;
  103044. }
  103045. }
  103046. if (!e1.max) {
  103047. var s1 = e1.proxy.shape;
  103048. var min1 = e1.min1.value;
  103049. var max1 = e1.max1.value;
  103050. var min2 = e1.min2.value;
  103051. var max2 = e1.max2.value;
  103052. for (var e2 = activeD; e2 != null; e2 = e2.pair) {// test for dynamic
  103053. var s2 = e2.proxy.shape;
  103054. this.numPairChecks++;
  103055. if (min1 > e2.max1.value || max1 < e2.min1.value || min2 > e2.max2.value || max2 < e2.min2.value || !this.isAvailablePair(s1, s2)) continue;
  103056. this.addPair(s1, s2);
  103057. }
  103058. if (dyn) {
  103059. for (e2 = activeS; e2 != null; e2 = e2.pair) {// test for static
  103060. s2 = e2.proxy.shape;
  103061. this.numPairChecks++;
  103062. if (min1 > e2.max1.value || max1 < e2.min1.value || min2 > e2.max2.value || max2 < e2.min2.value || !this.isAvailablePair(s1, s2)) continue;
  103063. this.addPair(s1, s2);
  103064. }
  103065. e1.pair = activeD;
  103066. activeD = e1;
  103067. } else {
  103068. e1.pair = activeS;
  103069. activeS = e1;
  103070. }
  103071. } else {
  103072. var min = e1.pair;
  103073. if (dyn) {
  103074. if (min == activeD) {
  103075. activeD = activeD.pair;
  103076. continue;
  103077. } else {
  103078. e1 = activeD;
  103079. }
  103080. } else {
  103081. if (min == activeS) {
  103082. activeS = activeS.pair;
  103083. continue;
  103084. } else {
  103085. e1 = activeS;
  103086. }
  103087. }
  103088. do {
  103089. e2 = e1.pair;
  103090. if (e2 == min) {
  103091. e1.pair = e2.pair;
  103092. break;
  103093. }
  103094. e1 = e2;
  103095. } while (e1 != null);
  103096. }
  103097. }
  103098. this.index2 = (this.index1 | this.index2) ^ 3;
  103099. };
  103100. /**
  103101. * An element of proxies.
  103102. * @author saharan
  103103. */
  103104. OIMO.SAPElement = function (proxy, max) {
  103105. // The parent proxy
  103106. this.proxy = proxy;
  103107. // The pair element.
  103108. this.pair = null;
  103109. // The minimum element on other axis.
  103110. this.min1 = null;
  103111. // The maximum element on other axis.
  103112. this.max1 = null;
  103113. // The minimum element on other axis.
  103114. this.min2 = null;
  103115. // The maximum element on other axis.
  103116. this.max2 = null;
  103117. // Whether the element has maximum value or not.
  103118. this.max = max;
  103119. // The value of the element.
  103120. this.value = 0;
  103121. };
  103122. /**
  103123. * A proxy for sweep and prune broad-phase.
  103124. * @author saharan
  103125. * @author lo-th
  103126. */
  103127. OIMO.SAPProxy = function (sap, shape) {
  103128. OIMO.Proxy.call(this, shape);
  103129. // Type of the axis to which the proxy belongs to. [0:none, 1:dynamic, 2:static]
  103130. this.belongsTo = 0;
  103131. // The maximum elements on each axis.
  103132. this.max = [];
  103133. // The minimum elements on each axis.
  103134. this.min = [];
  103135. this.sap = sap;
  103136. this.min[0] = new OIMO.SAPElement(this, false);
  103137. this.max[0] = new OIMO.SAPElement(this, true);
  103138. this.min[1] = new OIMO.SAPElement(this, false);
  103139. this.max[1] = new OIMO.SAPElement(this, true);
  103140. this.min[2] = new OIMO.SAPElement(this, false);
  103141. this.max[2] = new OIMO.SAPElement(this, true);
  103142. this.max[0].pair = this.min[0];
  103143. this.max[1].pair = this.min[1];
  103144. this.max[2].pair = this.min[2];
  103145. this.min[0].min1 = this.min[1];
  103146. this.min[0].max1 = this.max[1];
  103147. this.min[0].min2 = this.min[2];
  103148. this.min[0].max2 = this.max[2];
  103149. this.min[1].min1 = this.min[0];
  103150. this.min[1].max1 = this.max[0];
  103151. this.min[1].min2 = this.min[2];
  103152. this.min[1].max2 = this.max[2];
  103153. this.min[2].min1 = this.min[0];
  103154. this.min[2].max1 = this.max[0];
  103155. this.min[2].min2 = this.min[1];
  103156. this.min[2].max2 = this.max[1];
  103157. };
  103158. OIMO.SAPProxy.prototype = Object.create(OIMO.Proxy.prototype);
  103159. OIMO.SAPProxy.prototype.constructor = OIMO.SAPProxy;
  103160. // Returns whether the proxy is dynamic or not.
  103161. OIMO.SAPProxy.prototype.isDynamic = function () {
  103162. var body = this.shape.parent;
  103163. return body.isDynamic && !body.sleeping;
  103164. };
  103165. OIMO.SAPProxy.prototype.update = function () {
  103166. var te = this.aabb.elements;
  103167. this.min[0].value = te[0];
  103168. this.min[1].value = te[1];
  103169. this.min[2].value = te[2];
  103170. this.max[0].value = te[3];
  103171. this.max[1].value = te[4];
  103172. this.max[2].value = te[5];
  103173. if (this.belongsTo == 1 && !this.isDynamic() || this.belongsTo == 2 && this.isDynamic()) {
  103174. this.sap.removeProxy(this);
  103175. this.sap.addProxy(this);
  103176. }
  103177. };
  103178. /**
  103179. * A dynamic bounding volume tree for the broad-phase algorithm.
  103180. * @author saharan
  103181. * @author lo-th
  103182. */
  103183. OIMO.DBVT = function () {
  103184. // The root of the tree.
  103185. this.root = null;
  103186. this.freeNodes = [];
  103187. this.freeNodes.length = 16384;
  103188. this.numFreeNodes = 0;
  103189. this.aabb = new OIMO.AABB();
  103190. };
  103191. OIMO.DBVT.prototype = {
  103192. constructor: OIMO.DBVT,
  103193. /**
  103194. * Move a leaf.
  103195. * @param leaf
  103196. */
  103197. moveLeaf: function (leaf) {
  103198. this.deleteLeaf(leaf);
  103199. this.insertLeaf(leaf);
  103200. },
  103201. /**
  103202. * Insert a leaf to the tree.
  103203. * @param node
  103204. */
  103205. insertLeaf: function (leaf) {
  103206. if (this.root == null) {
  103207. this.root = leaf;
  103208. return;
  103209. }
  103210. var lb = leaf.aabb;
  103211. var sibling = this.root;
  103212. var oldArea;
  103213. var newArea;
  103214. while (sibling.proxy == null) { // descend the node to search the best pair
  103215. var c1 = sibling.child1;
  103216. var c2 = sibling.child2;
  103217. var b = sibling.aabb;
  103218. var c1b = c1.aabb;
  103219. var c2b = c2.aabb;
  103220. oldArea = b.surfaceArea();
  103221. this.aabb.combine(lb, b);
  103222. newArea = this.aabb.surfaceArea();
  103223. var creatingCost = newArea * 2;
  103224. var incrementalCost = (newArea - oldArea) * 2; // cost of creating a new pair with the node
  103225. var discendingCost1 = incrementalCost;
  103226. this.aabb.combine(lb, c1b);
  103227. if (c1.proxy != null) {
  103228. // leaf cost = area(combined aabb)
  103229. discendingCost1 += this.aabb.surfaceArea();
  103230. } else {
  103231. // node cost = area(combined aabb) - area(old aabb)
  103232. discendingCost1 += this.aabb.surfaceArea() - c1b.surfaceArea();
  103233. }
  103234. var discendingCost2 = incrementalCost;
  103235. this.aabb.combine(lb, c2b);
  103236. if (c2.proxy != null) {
  103237. // leaf cost = area(combined aabb)
  103238. discendingCost2 += this.aabb.surfaceArea();
  103239. } else {
  103240. // node cost = area(combined aabb) - area(old aabb)
  103241. discendingCost2 += this.aabb.surfaceArea() - c2b.surfaceArea();
  103242. }
  103243. if (discendingCost1 < discendingCost2) {
  103244. if (creatingCost < discendingCost1) {
  103245. break;// stop descending
  103246. } else {
  103247. sibling = c1;// descend into first child
  103248. }
  103249. } else {
  103250. if (creatingCost < discendingCost2) {
  103251. break;// stop descending
  103252. } else {
  103253. sibling = c2;// descend into second child
  103254. }
  103255. }
  103256. }
  103257. var oldParent = sibling.parent;
  103258. var newParent;
  103259. if (this.numFreeNodes > 0) {
  103260. newParent = this.freeNodes[--this.numFreeNodes];
  103261. } else {
  103262. newParent = new OIMO.DBVTNode();
  103263. }
  103264. newParent.parent = oldParent;
  103265. newParent.child1 = leaf;
  103266. newParent.child2 = sibling;
  103267. newParent.aabb.combine(leaf.aabb, sibling.aabb);
  103268. newParent.height = sibling.height + 1;
  103269. sibling.parent = newParent;
  103270. leaf.parent = newParent;
  103271. if (sibling == this.root) {
  103272. // replace root
  103273. this.root = newParent;
  103274. } else {
  103275. // replace child
  103276. if (oldParent.child1 == sibling) {
  103277. oldParent.child1 = newParent;
  103278. } else {
  103279. oldParent.child2 = newParent;
  103280. }
  103281. }
  103282. // update whole tree
  103283. do {
  103284. newParent = this.balance(newParent);
  103285. this.fix(newParent);
  103286. newParent = newParent.parent;
  103287. } while (newParent != null);
  103288. },
  103289. getBalance: function (node) {
  103290. if (node.proxy != null) return 0;
  103291. return node.child1.height - node.child2.height;
  103292. },
  103293. /*print:function(node,indent,text){
  103294. var hasChild=node.proxy==null;
  103295. if(hasChild)text=this.print(node.child1,indent+1,text);
  103296. for(var i=indent*2;i>=0;i--){
  103297. text+=" ";
  103298. }
  103299. text+=(hasChild?this.getBalance(node):"["+node.proxy.aabb.minX+"]")+"\n";
  103300. if(hasChild)text=this.print(node.child2,indent+1,text);
  103301. return text;
  103302. },*/
  103303. /**
  103304. * Delete a leaf from the tree.
  103305. * @param node
  103306. */
  103307. deleteLeaf: function (leaf) {
  103308. if (leaf == this.root) {
  103309. this.root = null;
  103310. return;
  103311. }
  103312. var parent = leaf.parent;
  103313. var sibling;
  103314. if (parent.child1 == leaf) {
  103315. sibling = parent.child2;
  103316. } else {
  103317. sibling = parent.child1;
  103318. }
  103319. if (parent == this.root) {
  103320. this.root = sibling;
  103321. sibling.parent = null;
  103322. return;
  103323. }
  103324. var grandParent = parent.parent;
  103325. sibling.parent = grandParent;
  103326. if (grandParent.child1 == parent) {
  103327. grandParent.child1 = sibling;
  103328. } else {
  103329. grandParent.child2 = sibling;
  103330. }
  103331. if (this.numFreeNodes < 16384) {
  103332. this.freeNodes[this.numFreeNodes++] = parent;
  103333. }
  103334. do {
  103335. grandParent = this.balance(grandParent);
  103336. this.fix(grandParent);
  103337. grandParent = grandParent.parent;
  103338. } while (grandParent != null);
  103339. },
  103340. balance: function (node) {
  103341. var nh = node.height;
  103342. if (nh < 2) {
  103343. return node;
  103344. }
  103345. var p = node.parent;
  103346. var l = node.child1;
  103347. var r = node.child2;
  103348. var lh = l.height;
  103349. var rh = r.height;
  103350. var balance = lh - rh;
  103351. var t;// for bit operation
  103352. // [ N ]
  103353. // / \
  103354. // [ L ] [ R ]
  103355. // / \ / \
  103356. // [L-L] [L-R] [R-L] [R-R]
  103357. // Is the tree balanced?
  103358. if (balance > 1) {
  103359. var ll = l.child1;
  103360. var lr = l.child2;
  103361. var llh = ll.height;
  103362. var lrh = lr.height;
  103363. // Is L-L higher than L-R?
  103364. if (llh > lrh) {
  103365. // set N to L-R
  103366. l.child2 = node;
  103367. node.parent = l;
  103368. // [ L ]
  103369. // / \
  103370. // [L-L] [ N ]
  103371. // / \ / \
  103372. // [...] [...] [ L ] [ R ]
  103373. // set L-R
  103374. node.child1 = lr;
  103375. lr.parent = node;
  103376. // [ L ]
  103377. // / \
  103378. // [L-L] [ N ]
  103379. // / \ / \
  103380. // [...] [...] [L-R] [ R ]
  103381. // fix bounds and heights
  103382. node.aabb.combine(lr.aabb, r.aabb);
  103383. t = lrh - rh;
  103384. node.height = lrh - (t & t >> 31) + 1;
  103385. l.aabb.combine(ll.aabb, node.aabb);
  103386. t = llh - nh;
  103387. l.height = llh - (t & t >> 31) + 1;
  103388. } else {
  103389. // set N to L-L
  103390. l.child1 = node;
  103391. node.parent = l;
  103392. // [ L ]
  103393. // / \
  103394. // [ N ] [L-R]
  103395. // / \ / \
  103396. // [ L ] [ R ] [...] [...]
  103397. // set L-L
  103398. node.child1 = ll;
  103399. ll.parent = node;
  103400. // [ L ]
  103401. // / \
  103402. // [ N ] [L-R]
  103403. // / \ / \
  103404. // [L-L] [ R ] [...] [...]
  103405. // fix bounds and heights
  103406. node.aabb.combine(ll.aabb, r.aabb);
  103407. t = llh - rh;
  103408. node.height = llh - (t & t >> 31) + 1;
  103409. l.aabb.combine(node.aabb, lr.aabb);
  103410. t = nh - lrh;
  103411. l.height = nh - (t & t >> 31) + 1;
  103412. }
  103413. // set new parent of L
  103414. if (p != null) {
  103415. if (p.child1 == node) {
  103416. p.child1 = l;
  103417. } else {
  103418. p.child2 = l;
  103419. }
  103420. } else {
  103421. this.root = l;
  103422. }
  103423. l.parent = p;
  103424. return l;
  103425. } else if (balance < -1) {
  103426. var rl = r.child1;
  103427. var rr = r.child2;
  103428. var rlh = rl.height;
  103429. var rrh = rr.height;
  103430. // Is R-L higher than R-R?
  103431. if (rlh > rrh) {
  103432. // set N to R-R
  103433. r.child2 = node;
  103434. node.parent = r;
  103435. // [ R ]
  103436. // / \
  103437. // [R-L] [ N ]
  103438. // / \ / \
  103439. // [...] [...] [ L ] [ R ]
  103440. // set R-R
  103441. node.child2 = rr;
  103442. rr.parent = node;
  103443. // [ R ]
  103444. // / \
  103445. // [R-L] [ N ]
  103446. // / \ / \
  103447. // [...] [...] [ L ] [R-R]
  103448. // fix bounds and heights
  103449. node.aabb.combine(l.aabb, rr.aabb);
  103450. t = lh - rrh;
  103451. node.height = lh - (t & t >> 31) + 1;
  103452. r.aabb.combine(rl.aabb, node.aabb);
  103453. t = rlh - nh;
  103454. r.height = rlh - (t & t >> 31) + 1;
  103455. } else {
  103456. // set N to R-L
  103457. r.child1 = node;
  103458. node.parent = r;
  103459. // [ R ]
  103460. // / \
  103461. // [ N ] [R-R]
  103462. // / \ / \
  103463. // [ L ] [ R ] [...] [...]
  103464. // set R-L
  103465. node.child2 = rl;
  103466. rl.parent = node;
  103467. // [ R ]
  103468. // / \
  103469. // [ N ] [R-R]
  103470. // / \ / \
  103471. // [ L ] [R-L] [...] [...]
  103472. // fix bounds and heights
  103473. node.aabb.combine(l.aabb, rl.aabb);
  103474. t = lh - rlh;
  103475. node.height = lh - (t & t >> 31) + 1;
  103476. r.aabb.combine(node.aabb, rr.aabb);
  103477. t = nh - rrh;
  103478. r.height = nh - (t & t >> 31) + 1;
  103479. }
  103480. // set new parent of R
  103481. if (p != null) {
  103482. if (p.child1 == node) {
  103483. p.child1 = r;
  103484. } else {
  103485. p.child2 = r;
  103486. }
  103487. } else {
  103488. this.root = r;
  103489. }
  103490. r.parent = p;
  103491. return r;
  103492. }
  103493. return node;
  103494. },
  103495. fix: function (node) {
  103496. var c1 = node.child1;
  103497. var c2 = node.child2;
  103498. node.aabb.combine(c1.aabb, c2.aabb);
  103499. //var h1 = c1.height;
  103500. //var h2 = c2.height;
  103501. node.height = c1.height < c2.height ? c2.height + 1 : c1.height + 1;
  103502. /*if( h1 < h2 ) {
  103503. node.height = h2+1;
  103504. }else{
  103505. node.height = h1+1;
  103506. }*/
  103507. }
  103508. }
  103509. /**
  103510. * A broad-phase algorithm using dynamic bounding volume tree.
  103511. * @author saharan
  103512. * @author lo-th
  103513. */
  103514. OIMO.DBVTBroadPhase = function () {
  103515. OIMO.BroadPhase.call(this);
  103516. this.types = OIMO.BR_BOUNDING_VOLUME_TREE;
  103517. this.tree = new OIMO.DBVT();
  103518. this.stack = [];
  103519. this.leaves = [];
  103520. this.numLeaves = 0;
  103521. };
  103522. OIMO.DBVTBroadPhase.prototype = Object.create(OIMO.BroadPhase.prototype);
  103523. OIMO.DBVTBroadPhase.prototype.constructor = OIMO.DBVTBroadPhase;
  103524. OIMO.DBVTBroadPhase.prototype.createProxy = function (shape) {
  103525. return new OIMO.DBVTProxy(shape);
  103526. };
  103527. OIMO.DBVTBroadPhase.prototype.addProxy = function (proxy) {
  103528. this.tree.insertLeaf(proxy.leaf);
  103529. this.leaves.push(proxy.leaf);
  103530. this.numLeaves++;
  103531. };
  103532. OIMO.DBVTBroadPhase.prototype.removeProxy = function (proxy) {
  103533. this.tree.deleteLeaf(proxy.leaf);
  103534. var n = this.leaves.indexOf(proxy.leaf);
  103535. if (n > -1) {
  103536. this.leaves.splice(n, 1);
  103537. this.numLeaves--;
  103538. }
  103539. };
  103540. OIMO.DBVTBroadPhase.prototype.collectPairs = function () {
  103541. if (this.numLeaves < 2) return;
  103542. var leaf, margin = 0.1, i = this.numLeaves;
  103543. while (i--) {
  103544. leaf = this.leaves[i];
  103545. if (leaf.proxy.aabb.intersectTestTwo(leaf.aabb)) {
  103546. leaf.aabb.copy(leaf.proxy.aabb, margin);
  103547. this.tree.deleteLeaf(leaf);
  103548. this.tree.insertLeaf(leaf);
  103549. this.collide(leaf, this.tree.root);
  103550. }
  103551. }
  103552. };
  103553. OIMO.DBVTBroadPhase.prototype.collide = function (node1, node2) {
  103554. var stackCount = 2;
  103555. var s1, s2, n1, n2, l1, l2;
  103556. this.stack[0] = node1;
  103557. this.stack[1] = node2;
  103558. while (stackCount > 0) {
  103559. n1 = this.stack[--stackCount];
  103560. n2 = this.stack[--stackCount];
  103561. l1 = n1.proxy != null;
  103562. l2 = n2.proxy != null;
  103563. this.numPairChecks++;
  103564. if (l1 && l2) {
  103565. s1 = n1.proxy.shape;
  103566. s2 = n2.proxy.shape;
  103567. if (s1 == s2 || s1.aabb.intersectTest(s2.aabb) || !this.isAvailablePair(s1, s2)) continue;
  103568. this.addPair(s1, s2);
  103569. } else {
  103570. if (n1.aabb.intersectTest(n2.aabb)) continue;
  103571. /*if(stackCount+4>=this.maxStack){// expand the stack
  103572. //this.maxStack<<=1;
  103573. this.maxStack*=2;
  103574. var newStack = [];// vector
  103575. newStack.length = this.maxStack;
  103576. for(var i=0;i<stackCount;i++){
  103577. newStack[i] = this.stack[i];
  103578. }
  103579. this.stack = newStack;
  103580. }*/
  103581. if (l2 || !l1 && (n1.aabb.surfaceArea() > n2.aabb.surfaceArea())) {
  103582. this.stack[stackCount++] = n1.child1;
  103583. this.stack[stackCount++] = n2;
  103584. this.stack[stackCount++] = n1.child2;
  103585. this.stack[stackCount++] = n2;
  103586. } else {
  103587. this.stack[stackCount++] = n1;
  103588. this.stack[stackCount++] = n2.child1;
  103589. this.stack[stackCount++] = n1;
  103590. this.stack[stackCount++] = n2.child2;
  103591. }
  103592. }
  103593. }
  103594. };
  103595. /**
  103596. * A node of the dynamic bounding volume tree.
  103597. * @author saharan
  103598. */
  103599. OIMO.DBVTNode = function () {
  103600. // The first child node of this node.
  103601. this.child1 = null;
  103602. // The second child node of this node.
  103603. this.child2 = null;
  103604. // The parent node of this tree.
  103605. this.parent = null;
  103606. // The proxy of this node. This has no value if this node is not leaf.
  103607. this.proxy = null;
  103608. // The maximum distance from leaf nodes.
  103609. this.height = 0;
  103610. // The AABB of this node.
  103611. this.aabb = new OIMO.AABB();
  103612. };
  103613. /**
  103614. * A proxy for dynamic bounding volume tree broad-phase.
  103615. * @author saharan
  103616. */
  103617. OIMO.DBVTProxy = function (shape) {
  103618. OIMO.Proxy.call(this, shape);
  103619. // The leaf of the proxy.
  103620. this.leaf = new OIMO.DBVTNode();
  103621. this.leaf.proxy = this;
  103622. };
  103623. OIMO.DBVTProxy.prototype = Object.create(OIMO.Proxy.prototype);
  103624. OIMO.DBVTProxy.prototype.constructor = OIMO.DBVTProxy;
  103625. OIMO.DBVTProxy.prototype.update = function () {
  103626. };
  103627. OIMO.World.prototype.add = function (obj) {
  103628. obj = obj || {};
  103629. var type = obj.type || "box";
  103630. if (typeof type === 'string') type = [type];// single shape
  103631. if (type[0].substring(0, 5) == 'joint') { // is joint
  103632. if (type[0] === 'joint') type[0] = 'jointHinge';
  103633. var axe1 = obj.axe1 || [1, 0, 0];
  103634. var axe2 = obj.axe2 || [1, 0, 0];
  103635. var pos1 = obj.pos1 || [0, 0, 0];
  103636. var pos2 = obj.pos2 || [0, 0, 0];
  103637. pos1 = pos1.map(function (x) { return x * OIMO.INV_SCALE; });
  103638. pos2 = pos2.map(function (x) { return x * OIMO.INV_SCALE; });
  103639. var min, max;
  103640. if (type[0] === "jointDistance") {
  103641. min = obj.min || 0;
  103642. max = obj.max || 10;
  103643. min = min * OIMO.INV_SCALE;
  103644. max = max * OIMO.INV_SCALE;
  103645. } else {
  103646. min = obj.min || 57.29578;
  103647. max = obj.max || 0;
  103648. min = min * OIMO.degtorad;
  103649. max = max * OIMO.degtorad;
  103650. }
  103651. var limit = obj.limit || null;
  103652. var spring = obj.spring || null;
  103653. var motor = obj.motor || null;
  103654. // joint setting
  103655. var jc = new OIMO.JointConfig();
  103656. jc.allowCollision = obj.collision || false;;
  103657. jc.localAxis1.init(axe1[0], axe1[1], axe1[2]);
  103658. jc.localAxis2.init(axe2[0], axe2[1], axe2[2]);
  103659. jc.localAnchorPoint1.init(pos1[0], pos1[1], pos1[2]);
  103660. jc.localAnchorPoint2.init(pos2[0], pos2[1], pos2[2]);
  103661. if (typeof obj.body1 == 'string' || obj.body1 instanceof String) obj.body1 = this.getByName(obj.body1);
  103662. if (typeof obj.body2 == 'string' || obj.body2 instanceof String) obj.body2 = this.getByName(obj.body2);
  103663. jc.body1 = obj.body1;
  103664. jc.body2 = obj.body2;
  103665. var joint;
  103666. switch (type[0]) {
  103667. case "jointDistance": joint = new OIMO.DistanceJoint(jc, min, max);
  103668. if (spring !== null) joint.limitMotor.setSpring(spring[0], spring[1]);
  103669. if (motor !== null) joint.limitMotor.setSpring(motor[0], motor[1]);
  103670. break;
  103671. case "jointHinge": joint = new OIMO.HingeJoint(jc, min, max);
  103672. if (spring !== null) joint.limitMotor.setSpring(spring[0], spring[1]);// soften the joint ex: 100, 0.2
  103673. if (motor !== null) joint.limitMotor.setSpring(motor[0], motor[1]);
  103674. break;
  103675. case "jointPrisme": joint = new OIMO.PrismaticJoint(jc, min, max); break;
  103676. case "jointSlide": joint = new OIMO.SliderJoint(jc, min, max); break;
  103677. case "jointBall": joint = new OIMO.BallAndSocketJoint(jc); break;
  103678. case "jointWheel": joint = new OIMO.WheelJoint(jc);
  103679. if (limit !== null) joint.rotationalLimitMotor1.setLimit(limit[0], limit[1]);
  103680. if (spring !== null) joint.rotationalLimitMotor1.setSpring(spring[0], spring[1]);
  103681. if (motor !== null) joint.rotationalLimitMotor1.setSpring(motor[0], motor[1]);
  103682. break;
  103683. }
  103684. joint.name = obj.name || '';
  103685. // finaly add to physics world
  103686. this.addJoint(joint);
  103687. return joint;
  103688. } else { // is body
  103689. // I'm dynamique or not
  103690. var move = obj.move || false;
  103691. // I can sleep or not
  103692. var noSleep = obj.noSleep || false;
  103693. // My start position
  103694. var p = obj.pos || [0, 0, 0];
  103695. p = p.map(function (x) { return x * OIMO.INV_SCALE; });
  103696. // My size
  103697. var s = obj.size || [1, 1, 1];
  103698. s = s.map(function (x) { return x * OIMO.INV_SCALE; });
  103699. // My rotation in degre
  103700. var rot = obj.rot || [0, 0, 0];
  103701. rot = rot.map(function (x) { return x * OIMO.degtorad; });
  103702. var r = [];
  103703. for (var i = 0; i < rot.length / 3; i++) {
  103704. var tmp = OIMO.EulerToAxis(rot[i + 0], rot[i + 1], rot[i + 2]);
  103705. r.push(tmp[0]); r.push(tmp[1]); r.push(tmp[2]); r.push(tmp[3]);
  103706. }
  103707. // My physics setting
  103708. var sc = new OIMO.ShapeConfig();
  103709. if (obj.sc !== undefined) sc = obj.sc;
  103710. if (obj.config) {
  103711. // The density of the shape.
  103712. sc.density = obj.config[0] === undefined ? 1 : obj.config[0];
  103713. // The coefficient of friction of the shape.
  103714. sc.friction = obj.config[1] === undefined ? 0.4 : obj.config[1];
  103715. // The coefficient of restitution of the shape.
  103716. sc.restitution = obj.config[2] === undefined ? 0.2 : obj.config[2];
  103717. // The bits of the collision groups to which the shape belongs.
  103718. sc.belongsTo = obj.config[3] || 1;
  103719. //sc.belongsTo = obj.config[3] === undefined ? 1 : obj.config[3];
  103720. // The bits of the collision groups with which the shape collides.
  103721. sc.collidesWith = obj.config[4] || 0xffffffff;
  103722. //sc.collidesWith = obj.config[4] === undefined ? 0xffffffff : obj.config[4];
  103723. }
  103724. // direct physics setting
  103725. if (obj.density !== undefined) sc.density = obj.density;
  103726. if (obj.friction !== undefined) sc.friction = obj.friction;
  103727. if (obj.restitution !== undefined) sc.restitution = obj.restitution;
  103728. if (obj.belongsTo !== undefined) sc.belongsTo = obj.belongsTo;
  103729. if (obj.collidesWith !== undefined) sc.collidesWith = obj.collidesWith;
  103730. if (obj.massPos) {
  103731. obj.massPos = obj.massPos.map(function (x) { return x * OIMO.INV_SCALE; });
  103732. sc.relativePosition.init(obj.massPos[0], obj.massPos[1], obj.massPos[2]);
  103733. }
  103734. if (obj.massRot) {
  103735. obj.massRot = obj.massRot.map(function (x) { return x * OIMO.degtorad; });
  103736. sc.relativeRotation = OIMO.EulerToMatrix(obj.massRot[0], obj.massRot[1], obj.massRot[2]);
  103737. }
  103738. // My rigidbody
  103739. var body = new OIMO.RigidBody(p[0], p[1], p[2], r[0], r[1], r[2], r[3]);
  103740. // My shapes
  103741. var shapes = [];
  103742. //if( typeof type === 'string' ) type = [type];// single shape
  103743. var n, n2;
  103744. for (var i = 0; i < type.length; i++) {
  103745. n = i * 3;
  103746. n2 = i * 4;
  103747. switch (type[i]) {
  103748. case "sphere": shapes[i] = new OIMO.SphereShape(sc, s[n]); break;
  103749. case "cylinder": shapes[i] = new OIMO.CylinderShape(sc, s[n], s[n + 1]); break;
  103750. case "box": shapes[i] = new OIMO.BoxShape(sc, s[n], s[n + 1], s[n + 2]); break;
  103751. }
  103752. body.addShape(shapes[i]);
  103753. if (i > 0) {
  103754. //shapes[i].position.init(p[0]+p[n+0], p[1]+p[n+1], p[2]+p[n+2] );
  103755. shapes[i].relativePosition = new OIMO.Vec3(p[n], p[n + 1], p[n + 2]);
  103756. if (r[n2 + 0]) shapes[i].relativeRotation = [r[n2], r[n2 + 1], r[n2 + 2], r[n2 + 3]];
  103757. }
  103758. }
  103759. // I'm static or i move
  103760. if (move) {
  103761. if (obj.massPos || obj.massRot) body.setupMass(0x1, false);
  103762. else body.setupMass(0x1, true);
  103763. if (noSleep) body.allowSleep = false;
  103764. else body.allowSleep = true;
  103765. } else {
  103766. body.setupMass(0x2);
  103767. }
  103768. body.name = obj.name || ' ';
  103769. // finaly add to physics world
  103770. this.addRigidBody(body);
  103771. return body;
  103772. }
  103773. }
  103774. //UMD simplified
  103775. var root = this;
  103776. if (!root['OIMO']) {
  103777. if (true)
  103778. module.exports = OIMO;
  103779. else if (typeof define === 'function' && define.amd)
  103780. define([], function () {
  103781. return OIMO;
  103782. });
  103783. else if (typeof exports === 'object')
  103784. exports["OIMO"] = OIMO;
  103785. else {
  103786. root["OIMO"] = OIMO;
  103787. }
  103788. }
  103789. /***/ }),
  103790. /* 19 */
  103791. /***/ (function(module, exports, __webpack_require__) {
  103792. "use strict";
  103793. Object.defineProperty(exports, "__esModule", { value: true });
  103794. var babylonjs_1 = __webpack_require__(0);
  103795. var helper_1 = __webpack_require__(2);
  103796. var TemplateManager = (function () {
  103797. function TemplateManager(containerElement) {
  103798. this.containerElement = containerElement;
  103799. this.templates = {};
  103800. this.onInit = new babylonjs_1.Observable();
  103801. this.onLoaded = new babylonjs_1.Observable();
  103802. this.onStateChange = new babylonjs_1.Observable();
  103803. this.onAllLoaded = new babylonjs_1.Observable();
  103804. this.onEventTriggered = new babylonjs_1.Observable();
  103805. this.eventManager = new eventManager_1.EventManager(this);
  103806. }
  103807. TemplateManager.prototype.initTemplate = function (templates) {
  103808. var _this = this;
  103809. var internalInit = function (dependencyMap, name, parentTemplate) {
  103810. var template = _this.templates[name];
  103811. var childrenTemplates = Object.keys(dependencyMap).map(function (childName) {
  103812. return internalInit(dependencyMap[childName], childName, template);
  103813. });
  103814. var addToParent = function () {
  103815. var containingElement = parentTemplate && parentTemplate.parent.querySelector(helper_1.camelToKebab(name)) || _this.containerElement;
  103816. template.appendTo(containingElement);
  103817. _this.checkLoadedState();
  103818. };
  103819. if (parentTemplate && !parentTemplate.parent) {
  103820. parentTemplate.onAppended.add(function () {
  103821. addToParent();
  103822. });
  103823. }
  103824. else {
  103825. addToParent();
  103826. }
  103827. return template;
  103828. };
  103829. return this.buildHTMLTree(templates).then(function (htmlTree) {
  103830. if (_this.templates['main']) {
  103831. internalInit(htmlTree, 'main');
  103832. }
  103833. else {
  103834. _this.checkLoadedState();
  103835. }
  103836. return;
  103837. });
  103838. };
  103839. TemplateManager.prototype.buildHTMLTree = function (templates) {
  103840. var _this = this;
  103841. var promises = Object.keys(templates).map(function (name) {
  103842. if (!templates[name])
  103843. return Promise.resolve(false);
  103844. var template = new Template(name, templates[name]);
  103845. template.onEventTriggered.add(function (eventData) { return _this.onEventTriggered.notifyObservers(eventData); });
  103846. _this.templates[name] = template;
  103847. return template.initPromise;
  103848. });
  103849. return Promise.all(promises).then(function () {
  103850. var templateStructure = {};
  103851. var buildTree = function (parentObject, name) {
  103852. _this.templates[name].isInHtmlTree = true;
  103853. var childNodes = _this.templates[name].getChildElements().filter(function (n) { return !!_this.templates[n]; });
  103854. childNodes.forEach(function (element) {
  103855. parentObject[element] = {};
  103856. buildTree(parentObject[element], element);
  103857. });
  103858. };
  103859. if (_this.templates['main']) {
  103860. buildTree(templateStructure, "main");
  103861. }
  103862. return templateStructure;
  103863. });
  103864. };
  103865. TemplateManager.prototype.getCanvas = function () {
  103866. return this.containerElement.querySelector('canvas');
  103867. };
  103868. TemplateManager.prototype.getTemplate = function (name) {
  103869. return this.templates[name];
  103870. };
  103871. TemplateManager.prototype.checkLoadedState = function () {
  103872. var _this = this;
  103873. var done = Object.keys(this.templates).length === 0 || Object.keys(this.templates).every(function (key) {
  103874. return (_this.templates[key].isLoaded && !!_this.templates[key].parent) || !_this.templates[key].isInHtmlTree;
  103875. });
  103876. if (done) {
  103877. this.onAllLoaded.notifyObservers(this);
  103878. }
  103879. };
  103880. TemplateManager.prototype.dispose = function () {
  103881. var _this = this;
  103882. Object.keys(this.templates).forEach(function (template) {
  103883. _this.templates[template].dispose();
  103884. });
  103885. this.onInit.clear();
  103886. this.onAllLoaded.clear();
  103887. this.onEventTriggered.clear();
  103888. this.onLoaded.clear();
  103889. this.onStateChange.clear();
  103890. };
  103891. return TemplateManager;
  103892. }());
  103893. exports.TemplateManager = TemplateManager;
  103894. var Handlebars = __webpack_require__(20);
  103895. var eventManager_1 = __webpack_require__(21);
  103896. Handlebars.registerHelper('eachInMap', function (map, block) {
  103897. var out = '';
  103898. Object.keys(map).map(function (prop) {
  103899. var data = map[prop];
  103900. if (typeof data === 'object') {
  103901. data.id = data.id || prop;
  103902. out += block.fn(data);
  103903. }
  103904. else {
  103905. out += block.fn({ id: prop, value: data });
  103906. }
  103907. });
  103908. return out;
  103909. });
  103910. var Template = (function () {
  103911. function Template(name, _configuration) {
  103912. var _this = this;
  103913. this.name = name;
  103914. this._configuration = _configuration;
  103915. this.onInit = new babylonjs_1.Observable();
  103916. this.onLoaded = new babylonjs_1.Observable();
  103917. this.onAppended = new babylonjs_1.Observable();
  103918. this.onStateChange = new babylonjs_1.Observable();
  103919. this.onEventTriggered = new babylonjs_1.Observable();
  103920. this.loadRequests = [];
  103921. this.isLoaded = false;
  103922. this.isShown = false;
  103923. this.isInHtmlTree = false;
  103924. this.onInit.notifyObservers(this);
  103925. var htmlContentPromise = this.getTemplateAsHtml(_configuration);
  103926. this.initPromise = htmlContentPromise.then(function (htmlTemplate) {
  103927. if (htmlTemplate) {
  103928. _this.htmlTemplate = htmlTemplate;
  103929. var compiledTemplate = Handlebars.compile(htmlTemplate);
  103930. var config = _this._configuration.params || {};
  103931. var rawHtml = compiledTemplate(config);
  103932. _this.fragment = document.createRange().createContextualFragment(rawHtml);
  103933. _this.isLoaded = true;
  103934. _this.isShown = true;
  103935. _this.onLoaded.notifyObservers(_this);
  103936. }
  103937. return _this;
  103938. });
  103939. }
  103940. Template.prototype.updateParams = function (params) {
  103941. this._configuration.params = params;
  103942. if (this.isLoaded) {
  103943. this.dispose();
  103944. }
  103945. var compiledTemplate = Handlebars.compile(this.htmlTemplate);
  103946. var config = this._configuration.params || {};
  103947. var rawHtml = compiledTemplate(config);
  103948. this.fragment = document.createRange().createContextualFragment(rawHtml);
  103949. if (this.parent) {
  103950. this.appendTo(this.parent, true);
  103951. }
  103952. };
  103953. Object.defineProperty(Template.prototype, "configuration", {
  103954. get: function () {
  103955. return this._configuration;
  103956. },
  103957. enumerable: true,
  103958. configurable: true
  103959. });
  103960. Template.prototype.getChildElements = function () {
  103961. var childrenArray = [];
  103962. var children = this.fragment.children;
  103963. if (!children) {
  103964. children = this.fragment.querySelectorAll('*');
  103965. }
  103966. for (var i = 0; i < children.length; ++i) {
  103967. childrenArray.push(helper_1.kebabToCamel(children.item(i).nodeName.toLowerCase()));
  103968. }
  103969. return childrenArray;
  103970. };
  103971. Template.prototype.appendTo = function (parent, forceRemove) {
  103972. var _this = this;
  103973. if (this.parent) {
  103974. if (forceRemove) {
  103975. this.parent.removeChild(this.fragment);
  103976. }
  103977. else {
  103978. return;
  103979. }
  103980. }
  103981. this.parent = parent;
  103982. if (this._configuration.id) {
  103983. this.parent.id = this._configuration.id;
  103984. }
  103985. this.fragment = this.parent.appendChild(this.fragment);
  103986. setTimeout(function () {
  103987. _this.registerEvents();
  103988. _this.onAppended.notifyObservers(_this);
  103989. });
  103990. };
  103991. Template.prototype.show = function (visibilityFunction) {
  103992. var _this = this;
  103993. if (this.isHiding)
  103994. return Promise.resolve(this);
  103995. return Promise.resolve().then(function () {
  103996. _this.isShowing = true;
  103997. if (visibilityFunction) {
  103998. return visibilityFunction(_this);
  103999. }
  104000. else {
  104001. _this.parent.style.display = 'flex';
  104002. return _this;
  104003. }
  104004. }).then(function () {
  104005. _this.isShown = true;
  104006. _this.isShowing = false;
  104007. _this.onStateChange.notifyObservers(_this);
  104008. return _this;
  104009. });
  104010. };
  104011. Template.prototype.hide = function (visibilityFunction) {
  104012. var _this = this;
  104013. if (this.isShowing)
  104014. return Promise.resolve(this);
  104015. return Promise.resolve().then(function () {
  104016. _this.isHiding = true;
  104017. if (visibilityFunction) {
  104018. return visibilityFunction(_this);
  104019. }
  104020. else {
  104021. _this.parent.style.display = 'hide';
  104022. return _this;
  104023. }
  104024. }).then(function () {
  104025. _this.isShown = false;
  104026. _this.isHiding = false;
  104027. _this.onStateChange.notifyObservers(_this);
  104028. return _this;
  104029. });
  104030. };
  104031. Template.prototype.dispose = function () {
  104032. this.onAppended.clear();
  104033. this.onEventTriggered.clear();
  104034. this.onInit.clear();
  104035. this.onLoaded.clear();
  104036. this.onStateChange.clear();
  104037. this.isLoaded = false;
  104038. this.parent.removeChild(this.fragment);
  104039. this.loadRequests.forEach(function (request) {
  104040. request.abort();
  104041. });
  104042. };
  104043. Template.prototype.getTemplateAsHtml = function (templateConfig) {
  104044. var _this = this;
  104045. if (!templateConfig) {
  104046. return Promise.reject('No templateConfig provided');
  104047. }
  104048. else if (templateConfig.html !== undefined) {
  104049. return Promise.resolve(templateConfig.html);
  104050. }
  104051. else {
  104052. var location_1 = getTemplateLocation(templateConfig);
  104053. if (helper_1.isUrl(location_1)) {
  104054. return new Promise(function (resolve, reject) {
  104055. var fileRequest = babylonjs_1.Tools.LoadFile(location_1, function (data) {
  104056. resolve(data);
  104057. }, undefined, undefined, false, function (request, error) {
  104058. reject(error);
  104059. });
  104060. _this.loadRequests.push(fileRequest);
  104061. });
  104062. }
  104063. else {
  104064. location_1 = location_1.replace('#', '');
  104065. var element = document.getElementById(location_1);
  104066. if (element) {
  104067. return Promise.resolve(element.innerHTML);
  104068. }
  104069. else {
  104070. return Promise.reject('Template ID not found');
  104071. }
  104072. }
  104073. }
  104074. };
  104075. Template.prototype.registerEvents = function () {
  104076. var _this = this;
  104077. this.registeredEvents = this.registeredEvents || [];
  104078. if (this.registeredEvents.length) {
  104079. this.registeredEvents.forEach(function (evt) {
  104080. evt.htmlElement.removeEventListener(evt.eventName, evt.function);
  104081. });
  104082. }
  104083. if (this._configuration.events) {
  104084. var _loop_1 = function (eventName) {
  104085. if (this_1._configuration.events && this_1._configuration.events[eventName]) {
  104086. var functionToFire_1 = function (selector, event) {
  104087. _this.onEventTriggered.notifyObservers({ event: event, template: _this, selector: selector });
  104088. };
  104089. if (typeof this_1._configuration.events[eventName] === 'boolean') {
  104090. this_1.parent.addEventListener(eventName, functionToFire_1.bind(this_1, '#' + this_1.parent.id), false);
  104091. }
  104092. else if (typeof this_1._configuration.events[eventName] === 'object') {
  104093. var selectorsArray = Object.keys(this_1._configuration.events[eventName] || {});
  104094. var event_1 = this_1._configuration.events[eventName] || {};
  104095. selectorsArray.filter(function (selector) { return event_1[selector]; }).forEach(function (selector) {
  104096. if (selector && selector.indexOf('#') !== 0) {
  104097. selector = '#' + selector;
  104098. }
  104099. var htmlElement = _this.parent.querySelector(selector);
  104100. if (htmlElement) {
  104101. var binding = functionToFire_1.bind(_this, selector);
  104102. htmlElement.addEventListener(eventName, binding, false);
  104103. _this.registeredEvents.push({
  104104. htmlElement: htmlElement,
  104105. eventName: eventName,
  104106. function: binding
  104107. });
  104108. }
  104109. });
  104110. }
  104111. }
  104112. };
  104113. var this_1 = this;
  104114. for (var eventName in this._configuration.events) {
  104115. _loop_1(eventName);
  104116. }
  104117. }
  104118. };
  104119. return Template;
  104120. }());
  104121. exports.Template = Template;
  104122. function getTemplateLocation(templateConfig) {
  104123. if (!templateConfig || typeof templateConfig === 'string') {
  104124. return templateConfig;
  104125. }
  104126. else {
  104127. return templateConfig.location;
  104128. }
  104129. }
  104130. exports.getTemplateLocation = getTemplateLocation;
  104131. /***/ }),
  104132. /* 20 */
  104133. /***/ (function(module, exports, __webpack_require__) {
  104134. /**!
  104135. @license
  104136. handlebars v4.0.11
  104137. Copyright (C) 2011-2017 by Yehuda Katz
  104138. Permission is hereby granted, free of charge, to any person obtaining a copy
  104139. of this software and associated documentation files (the "Software"), to deal
  104140. in the Software without restriction, including without limitation the rights
  104141. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  104142. copies of the Software, and to permit persons to whom the Software is
  104143. furnished to do so, subject to the following conditions:
  104144. The above copyright notice and this permission notice shall be included in
  104145. all copies or substantial portions of the Software.
  104146. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  104147. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  104148. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  104149. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  104150. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  104151. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  104152. THE SOFTWARE.
  104153. */
  104154. !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],
  104155. 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){
  104156. 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"]}])});
  104157. /***/ }),
  104158. /* 21 */
  104159. /***/ (function(module, exports, __webpack_require__) {
  104160. "use strict";
  104161. Object.defineProperty(exports, "__esModule", { value: true });
  104162. var EventManager = (function () {
  104163. function EventManager(templateManager) {
  104164. var _this = this;
  104165. this.templateManager = templateManager;
  104166. this.callbacksContainer = {};
  104167. this.templateManager.onEventTriggered.add(function (eventData) {
  104168. _this.eventTriggered(eventData);
  104169. });
  104170. }
  104171. EventManager.prototype.registerCallback = function (templateName, callback, eventType, selector) {
  104172. if (!this.callbacksContainer[templateName]) {
  104173. this.callbacksContainer[templateName] = [];
  104174. }
  104175. this.callbacksContainer[templateName].push({
  104176. eventType: eventType,
  104177. callback: callback
  104178. });
  104179. };
  104180. EventManager.prototype.unregisterCallback = function (templateName, callback, eventType, selector) {
  104181. var callbackDefs = this.callbacksContainer[templateName] || [];
  104182. this.callbacksContainer[templateName] = callbackDefs.filter(function (callbackDef) { return (!callbackDef.eventType || callbackDef.eventType === eventType) && (!callbackDef.selector || callbackDef.selector === selector); });
  104183. };
  104184. EventManager.prototype.eventTriggered = function (data) {
  104185. var templateName = data.template.name;
  104186. var eventType = data.event.type;
  104187. var selector = data.selector;
  104188. var callbackDefs = this.callbacksContainer[templateName] || [];
  104189. callbackDefs.filter(function (callbackDef) { return (!callbackDef.eventType || callbackDef.eventType === eventType) && (!callbackDef.selector || callbackDef.selector === selector); }).forEach(function (callbackDef) {
  104190. callbackDef.callback(data);
  104191. });
  104192. };
  104193. return EventManager;
  104194. }());
  104195. exports.EventManager = EventManager;
  104196. /***/ }),
  104197. /* 22 */
  104198. /***/ (function(module, exports, __webpack_require__) {
  104199. "use strict";
  104200. Object.defineProperty(exports, "__esModule", { value: true });
  104201. var mappers_1 = __webpack_require__(1);
  104202. var types_1 = __webpack_require__(23);
  104203. var deepmerge = __webpack_require__(13);
  104204. var babylonjs_1 = __webpack_require__(0);
  104205. var ConfigurationLoader = (function () {
  104206. function ConfigurationLoader() {
  104207. this.configurationCache = {};
  104208. this.loadRequests = [];
  104209. }
  104210. ConfigurationLoader.prototype.loadConfiguration = function (initConfig, callback) {
  104211. var _this = this;
  104212. if (initConfig === void 0) { initConfig = {}; }
  104213. var loadedConfig = deepmerge({}, initConfig);
  104214. var extendedConfiguration = types_1.getConfigurationType(loadedConfig.extends || "");
  104215. loadedConfig = deepmerge(extendedConfiguration, loadedConfig);
  104216. if (loadedConfig.configuration) {
  104217. var mapperType_1 = "json";
  104218. return Promise.resolve().then(function () {
  104219. if (typeof loadedConfig.configuration === "string" || (loadedConfig.configuration && loadedConfig.configuration.url)) {
  104220. var url = '';
  104221. if (typeof loadedConfig.configuration === "string") {
  104222. url = loadedConfig.configuration;
  104223. }
  104224. if (typeof loadedConfig.configuration === "object" && loadedConfig.configuration.url) {
  104225. url = loadedConfig.configuration.url;
  104226. var type = loadedConfig.configuration.mapper;
  104227. if (!type) {
  104228. type = loadedConfig.configuration.url.split('.').pop();
  104229. }
  104230. mapperType_1 = type || mapperType_1;
  104231. }
  104232. return _this.loadFile(url);
  104233. }
  104234. else {
  104235. if (typeof loadedConfig.configuration === "object") {
  104236. mapperType_1 = loadedConfig.configuration.mapper || mapperType_1;
  104237. return loadedConfig.configuration.payload || {};
  104238. }
  104239. return {};
  104240. }
  104241. }).then(function (data) {
  104242. var mapper = mappers_1.mapperManager.getMapper(mapperType_1);
  104243. var parsed = mapper.map(data);
  104244. var merged = deepmerge(loadedConfig, parsed);
  104245. if (callback)
  104246. callback(merged);
  104247. return merged;
  104248. });
  104249. }
  104250. else {
  104251. if (callback)
  104252. callback(loadedConfig);
  104253. return Promise.resolve(loadedConfig);
  104254. }
  104255. };
  104256. ConfigurationLoader.prototype.dispose = function () {
  104257. this.loadRequests.forEach(function (request) {
  104258. request.abort();
  104259. });
  104260. };
  104261. ConfigurationLoader.prototype.loadFile = function (url) {
  104262. var _this = this;
  104263. var cacheReference = this.configurationCache;
  104264. if (cacheReference[url]) {
  104265. return Promise.resolve(cacheReference[url]);
  104266. }
  104267. return new Promise(function (resolve, reject) {
  104268. var fileRequest = babylonjs_1.Tools.LoadFile(url, resolve, undefined, undefined, false, function (request, error) {
  104269. reject(error);
  104270. });
  104271. _this.loadRequests.push(fileRequest);
  104272. });
  104273. };
  104274. return ConfigurationLoader;
  104275. }());
  104276. exports.ConfigurationLoader = ConfigurationLoader;
  104277. exports.configurationLoader = new ConfigurationLoader();
  104278. exports.default = exports.configurationLoader;
  104279. /***/ }),
  104280. /* 23 */
  104281. /***/ (function(module, exports, __webpack_require__) {
  104282. "use strict";
  104283. Object.defineProperty(exports, "__esModule", { value: true });
  104284. var minimal_1 = __webpack_require__(24);
  104285. exports.minimalConfiguration = minimal_1.minimalConfiguration;
  104286. var default_1 = __webpack_require__(25);
  104287. exports.defaultConfiguration = default_1.defaultConfiguration;
  104288. var getConfigurationType = function (type) {
  104289. switch (type) {
  104290. case 'default':
  104291. return default_1.defaultConfiguration;
  104292. case 'minimal':
  104293. return minimal_1.minimalConfiguration;
  104294. case 'none':
  104295. return {};
  104296. default:
  104297. return default_1.defaultConfiguration;
  104298. }
  104299. };
  104300. exports.getConfigurationType = getConfigurationType;
  104301. /***/ }),
  104302. /* 24 */
  104303. /***/ (function(module, exports, __webpack_require__) {
  104304. "use strict";
  104305. Object.defineProperty(exports, "__esModule", { value: true });
  104306. exports.minimalConfiguration = {
  104307. version: "0.1",
  104308. templates: {
  104309. main: {
  104310. html: __webpack_require__(6)
  104311. },
  104312. loadingScreen: {
  104313. html: __webpack_require__(7),
  104314. params: {
  104315. backgroundColor: "#000000",
  104316. loadingImage: __webpack_require__(8)
  104317. }
  104318. },
  104319. viewer: {
  104320. html: __webpack_require__(9),
  104321. },
  104322. overlay: {
  104323. html: __webpack_require__(10),
  104324. params: {
  104325. closeImage: __webpack_require__(11),
  104326. closeText: 'Close'
  104327. }
  104328. },
  104329. error: {
  104330. html: __webpack_require__(12)
  104331. }
  104332. },
  104333. engine: {
  104334. antialiasing: true
  104335. }
  104336. };
  104337. /***/ }),
  104338. /* 25 */
  104339. /***/ (function(module, exports, __webpack_require__) {
  104340. "use strict";
  104341. Object.defineProperty(exports, "__esModule", { value: true });
  104342. exports.defaultConfiguration = {
  104343. version: "3.2.0-alpha4",
  104344. templates: {
  104345. main: {
  104346. html: __webpack_require__(6)
  104347. },
  104348. loadingScreen: {
  104349. html: __webpack_require__(7),
  104350. params: {
  104351. backgroundColor: "#000000",
  104352. loadingImage: __webpack_require__(8)
  104353. }
  104354. },
  104355. viewer: {
  104356. html: __webpack_require__(9),
  104357. events: {
  104358. pointerout: true,
  104359. pointerdown: true,
  104360. pointerup: true
  104361. }
  104362. },
  104363. navBar: {
  104364. html: __webpack_require__(26),
  104365. params: {
  104366. buttons: {
  104367. "fullscreen-button": {
  104368. altText: "Fullscreen",
  104369. image: __webpack_require__(27)
  104370. }
  104371. },
  104372. visibilityTimeout: 2000
  104373. },
  104374. events: {
  104375. pointerdown: { 'fullscreen-button': true },
  104376. pointerover: true
  104377. }
  104378. },
  104379. overlay: {
  104380. html: __webpack_require__(10),
  104381. params: {
  104382. closeImage: __webpack_require__(11),
  104383. closeText: 'Close'
  104384. }
  104385. },
  104386. help: {
  104387. html: __webpack_require__(28)
  104388. },
  104389. share: {
  104390. html: __webpack_require__(29)
  104391. },
  104392. error: {
  104393. html: __webpack_require__(12)
  104394. }
  104395. },
  104396. camera: {
  104397. behaviors: {
  104398. autoRotate: 0,
  104399. framing: {
  104400. type: 2,
  104401. zoomOnBoundingInfo: true,
  104402. zoomStopsAnimation: false
  104403. }
  104404. }
  104405. },
  104406. skybox: {
  104407. pbr: true,
  104408. blur: 0.7,
  104409. infiniteDIstance: false,
  104410. },
  104411. ground: true,
  104412. engine: {
  104413. antialiasing: true
  104414. },
  104415. scene: {
  104416. imageProcessingConfiguration: {
  104417. exposure: 1.4,
  104418. contrast: 1.66,
  104419. toneMappingEnabled: true
  104420. }
  104421. }
  104422. };
  104423. /***/ }),
  104424. /* 26 */
  104425. /***/ (function(module, exports) {
  104426. 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>";
  104427. /***/ }),
  104428. /* 27 */
  104429. /***/ (function(module, exports) {
  104430. module.exports = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwAQAAAAB/ecQqAAAAAnRSTlMAAHaTzTgAAAAeSURBVHgBY6ASsP/A/wcXZQNGhCkyAfE24HUndQAAXlkXcQ24P7gAAAAASUVORK5CYII="
  104431. /***/ }),
  104432. /* 28 */
  104433. /***/ (function(module, exports) {
  104434. module.exports = "HELP";
  104435. /***/ }),
  104436. /* 29 */
  104437. /***/ (function(module, exports) {
  104438. module.exports = "SHARE";
  104439. /***/ }),
  104440. /* 30 */
  104441. /***/ (function(module, exports, __webpack_require__) {
  104442. "use strict";
  104443. Object.defineProperty(exports, "__esModule", { value: true });
  104444. var babylonjs_1 = __webpack_require__(0);
  104445. var modelAnimation_1 = __webpack_require__(31);
  104446. var ViewerModel = (function () {
  104447. function ViewerModel(_modelConfiguration, _scene, disableAutoLoad) {
  104448. if (disableAutoLoad === void 0) { disableAutoLoad = false; }
  104449. this._modelConfiguration = _modelConfiguration;
  104450. this._scene = _scene;
  104451. this.onLoadedObservable = new babylonjs_1.Observable();
  104452. this.onLoadErrorObservable = new babylonjs_1.Observable();
  104453. this.onLoadProgressObservable = new babylonjs_1.Observable();
  104454. this._animations = [];
  104455. if (!disableAutoLoad) {
  104456. this._initLoad();
  104457. }
  104458. }
  104459. ViewerModel.prototype.load = function () {
  104460. if (this.loader) {
  104461. babylonjs_1.Tools.Error("Model was already loaded or in the process of loading.");
  104462. }
  104463. else {
  104464. this._initLoad();
  104465. }
  104466. };
  104467. ViewerModel.prototype.getAnimationNames = function () {
  104468. return this._animations.map(function (a) { return a.name; });
  104469. };
  104470. ViewerModel.prototype._getAnimationByName = function (name) {
  104471. var filtered = this._animations.filter(function (a) { return a.name === name; });
  104472. if (filtered.length === 1) {
  104473. return filtered[0];
  104474. }
  104475. else {
  104476. return null;
  104477. }
  104478. };
  104479. ViewerModel.prototype.playAnimation = function (name) {
  104480. var animation = this._getAnimationByName(name);
  104481. if (animation) {
  104482. if (this.currentAnimation) {
  104483. this.currentAnimation.stop();
  104484. }
  104485. this.currentAnimation = animation;
  104486. animation.start();
  104487. return animation;
  104488. }
  104489. else {
  104490. throw new Error("animation not found - " + name);
  104491. }
  104492. };
  104493. ViewerModel.prototype._initLoad = function () {
  104494. var _this = this;
  104495. if (!this._modelConfiguration || !this._modelConfiguration.url) {
  104496. return babylonjs_1.Tools.Error("No model URL to load.");
  104497. }
  104498. var parts = this._modelConfiguration.url.split('/');
  104499. var filename = parts.pop() || this._modelConfiguration.url;
  104500. var base = parts.length ? parts.join('/') + '/' : './';
  104501. var plugin = this._modelConfiguration.loader;
  104502. var animationsArray = this._scene.animationGroups.slice();
  104503. this.loader = babylonjs_1.SceneLoader.ImportMesh(undefined, base, filename, this._scene, function (meshes, particleSystems, skeletons) {
  104504. meshes.forEach(function (mesh) {
  104505. babylonjs_1.Tags.AddTagsTo(mesh, "viewerMesh");
  104506. });
  104507. _this.meshes = meshes;
  104508. _this.particleSystems = particleSystems;
  104509. _this.skeletons = skeletons;
  104510. if (_this.loader.name === 'gltf') {
  104511. _this._scene.animationGroups.forEach(function (ag) {
  104512. if (animationsArray.indexOf(ag) === -1) {
  104513. _this._animations.push(new modelAnimation_1.GroupModelAnimation(ag));
  104514. }
  104515. });
  104516. }
  104517. else {
  104518. skeletons.forEach(function (skeleton, idx) {
  104519. var ag = new BABYLON.AnimationGroup("animation-" + idx, _this._scene);
  104520. skeleton.getAnimatables().forEach(function (a) {
  104521. if (a.animations[0]) {
  104522. ag.addTargetedAnimation(a.animations[0], a);
  104523. }
  104524. });
  104525. _this._animations.push(new modelAnimation_1.GroupModelAnimation(ag));
  104526. });
  104527. }
  104528. if (_this._modelConfiguration.animation) {
  104529. if (_this._modelConfiguration.animation.playOnce) {
  104530. _this._animations.forEach(function (a) {
  104531. a.playMode = modelAnimation_1.AnimationPlayMode.ONCE;
  104532. });
  104533. }
  104534. if (_this._modelConfiguration.animation.autoStart && _this._animations.length) {
  104535. var animationName = _this._modelConfiguration.animation.autoStart === true ?
  104536. _this._animations[0].name : _this._modelConfiguration.animation.autoStart;
  104537. _this.playAnimation(animationName);
  104538. }
  104539. }
  104540. _this.onLoadedObservable.notifyObserversWithPromise(_this);
  104541. }, function (progressEvent) {
  104542. _this.onLoadProgressObservable.notifyObserversWithPromise(progressEvent);
  104543. }, function (e, m, exception) {
  104544. _this.onLoadErrorObservable.notifyObserversWithPromise({ message: m, exception: exception });
  104545. }, plugin);
  104546. this.loader['animationStartMode'] = 0;
  104547. };
  104548. ViewerModel.prototype.dispose = function () {
  104549. this.particleSystems.forEach(function (ps) { return ps.dispose(); });
  104550. this.skeletons.forEach(function (s) { return s.dispose(); });
  104551. this._animations.forEach(function (ag) { return ag.dispose(); });
  104552. this.meshes.forEach(function (m) { return m.dispose(); });
  104553. };
  104554. return ViewerModel;
  104555. }());
  104556. exports.ViewerModel = ViewerModel;
  104557. /***/ }),
  104558. /* 31 */
  104559. /***/ (function(module, exports, __webpack_require__) {
  104560. "use strict";
  104561. Object.defineProperty(exports, "__esModule", { value: true });
  104562. var AnimationPlayMode;
  104563. (function (AnimationPlayMode) {
  104564. AnimationPlayMode[AnimationPlayMode["ONCE"] = 0] = "ONCE";
  104565. AnimationPlayMode[AnimationPlayMode["LOOP"] = 1] = "LOOP";
  104566. })(AnimationPlayMode = exports.AnimationPlayMode || (exports.AnimationPlayMode = {}));
  104567. var AnimationState;
  104568. (function (AnimationState) {
  104569. AnimationState[AnimationState["INIT"] = 0] = "INIT";
  104570. AnimationState[AnimationState["PLAYING"] = 1] = "PLAYING";
  104571. AnimationState[AnimationState["PAUSED"] = 2] = "PAUSED";
  104572. AnimationState[AnimationState["STOPPED"] = 3] = "STOPPED";
  104573. AnimationState[AnimationState["ENDED"] = 4] = "ENDED";
  104574. })(AnimationState = exports.AnimationState || (exports.AnimationState = {}));
  104575. var GroupModelAnimation = (function () {
  104576. function GroupModelAnimation(_animationGroup) {
  104577. var _this = this;
  104578. this._animationGroup = _animationGroup;
  104579. this._state = AnimationState.INIT;
  104580. this._playMode = AnimationPlayMode.LOOP;
  104581. this._animationGroup.onAnimationEndObservable.add(function () {
  104582. _this.stop();
  104583. _this._state = AnimationState.ENDED;
  104584. });
  104585. }
  104586. Object.defineProperty(GroupModelAnimation.prototype, "name", {
  104587. get: function () {
  104588. return this._animationGroup.name;
  104589. },
  104590. enumerable: true,
  104591. configurable: true
  104592. });
  104593. Object.defineProperty(GroupModelAnimation.prototype, "state", {
  104594. get: function () {
  104595. return this._state;
  104596. },
  104597. enumerable: true,
  104598. configurable: true
  104599. });
  104600. Object.defineProperty(GroupModelAnimation.prototype, "speedRatio", {
  104601. get: function () {
  104602. return this._animationGroup.speedRatio;
  104603. },
  104604. set: function (value) {
  104605. this._animationGroup.speedRatio = value;
  104606. },
  104607. enumerable: true,
  104608. configurable: true
  104609. });
  104610. Object.defineProperty(GroupModelAnimation.prototype, "frames", {
  104611. get: function () {
  104612. var animationFrames = this._animationGroup.targetedAnimations.map(function (ta) {
  104613. var keys = ta.animation.getKeys();
  104614. return keys[keys.length - 1].frame;
  104615. });
  104616. return Math.max.apply(null, animationFrames);
  104617. },
  104618. enumerable: true,
  104619. configurable: true
  104620. });
  104621. Object.defineProperty(GroupModelAnimation.prototype, "currentFrame", {
  104622. get: function () {
  104623. for (var i = 0; i < this._animationGroup.animatables.length; ++i) {
  104624. var animatable = this._animationGroup.animatables[i];
  104625. var animations = animatable.getAnimations();
  104626. if (!animations || !animations.length) {
  104627. continue;
  104628. }
  104629. for (var idx = 0; idx < animations.length; ++idx) {
  104630. if (animations[idx].currentFrame) {
  104631. return animations[idx].currentFrame;
  104632. }
  104633. }
  104634. }
  104635. return 0;
  104636. },
  104637. enumerable: true,
  104638. configurable: true
  104639. });
  104640. Object.defineProperty(GroupModelAnimation.prototype, "fps", {
  104641. get: function () {
  104642. for (var i = 0; i < this._animationGroup.animatables.length; ++i) {
  104643. var animatable = this._animationGroup.animatables[i];
  104644. var animations = animatable.getAnimations();
  104645. if (!animations || !animations.length) {
  104646. continue;
  104647. }
  104648. for (var idx = 0; idx < animations.length; ++idx) {
  104649. if (animations[idx].animation && animations[idx].animation.framePerSecond) {
  104650. return animations[idx].animation.framePerSecond;
  104651. }
  104652. }
  104653. }
  104654. return 0;
  104655. },
  104656. enumerable: true,
  104657. configurable: true
  104658. });
  104659. Object.defineProperty(GroupModelAnimation.prototype, "playMode", {
  104660. get: function () {
  104661. return this._playMode;
  104662. },
  104663. set: function (value) {
  104664. if (value === this._playMode) {
  104665. return;
  104666. }
  104667. this._playMode = value;
  104668. if (this.state === AnimationState.PLAYING) {
  104669. this._animationGroup.play(this._playMode === AnimationPlayMode.LOOP);
  104670. }
  104671. else {
  104672. this._animationGroup.reset();
  104673. this._state = AnimationState.INIT;
  104674. }
  104675. },
  104676. enumerable: true,
  104677. configurable: true
  104678. });
  104679. GroupModelAnimation.prototype.reset = function () {
  104680. this._animationGroup.reset();
  104681. };
  104682. GroupModelAnimation.prototype.restart = function () {
  104683. this._animationGroup.restart();
  104684. };
  104685. GroupModelAnimation.prototype.goToFrame = function (frameNumber) {
  104686. this._animationGroup['_animatables'].forEach(function (a) {
  104687. a.goToFrame(frameNumber);
  104688. });
  104689. };
  104690. GroupModelAnimation.prototype.start = function () {
  104691. this._animationGroup.start(this.playMode === AnimationPlayMode.LOOP, this.speedRatio);
  104692. if (this._animationGroup.isStarted) {
  104693. this._state = AnimationState.PLAYING;
  104694. }
  104695. };
  104696. GroupModelAnimation.prototype.pause = function () {
  104697. this._animationGroup.pause();
  104698. this._state = AnimationState.PAUSED;
  104699. };
  104700. GroupModelAnimation.prototype.stop = function () {
  104701. this._animationGroup.stop();
  104702. if (!this._animationGroup.isStarted) {
  104703. this._state = AnimationState.STOPPED;
  104704. }
  104705. };
  104706. GroupModelAnimation.prototype.dispose = function () {
  104707. this._animationGroup.dispose();
  104708. };
  104709. return GroupModelAnimation;
  104710. }());
  104711. exports.GroupModelAnimation = GroupModelAnimation;
  104712. /***/ }),
  104713. /* 32 */
  104714. /***/ (function(module, exports, __webpack_require__) {
  104715. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  104716. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  104717. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  104718. 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;
  104719. return c > 3 && r && Object.defineProperty(target, key, r), r;
  104720. };
  104721. var __extends = (this && this.__extends) || (function () {
  104722. var extendStatics = Object.setPrototypeOf ||
  104723. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  104724. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  104725. return function (d, b) {
  104726. extendStatics(d, b);
  104727. function __() { this.constructor = d; }
  104728. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  104729. };
  104730. })();
  104731. (function universalModuleDefinition(root, factory) {
  104732. if(true)
  104733. module.exports = factory(__webpack_require__(0));
  104734. else if(typeof define === 'function' && define.amd)
  104735. define("babylonjs-loaders", ["babylonjs"], factory);
  104736. else if(typeof exports === 'object')
  104737. exports["babylonjs-loaders"] = factory(require("babylonjs"));
  104738. else {
  104739. root["BABYLON"] = factory(root["BABYLON"]);
  104740. }
  104741. })(this, function(BABYLON) {
  104742. var BABYLON;
  104743. (function (BABYLON) {
  104744. var STLFileLoader = /** @class */ (function () {
  104745. function STLFileLoader() {
  104746. this.solidPattern = /solid (\S*)([\S\s]*)endsolid[ ]*(\S*)/g;
  104747. this.facetsPattern = /facet([\s\S]*?)endfacet/g;
  104748. 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;
  104749. 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;
  104750. this.name = "stl";
  104751. // force data to come in as an ArrayBuffer
  104752. // we'll convert to string if it looks like it's an ASCII .stl
  104753. this.extensions = {
  104754. ".stl": { isBinary: true },
  104755. };
  104756. }
  104757. STLFileLoader.prototype.importMesh = function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  104758. var matches;
  104759. if (this.isBinary(data)) {
  104760. // binary .stl
  104761. var babylonMesh = new BABYLON.Mesh("stlmesh", scene);
  104762. this.parseBinary(babylonMesh, data);
  104763. if (meshes) {
  104764. meshes.push(babylonMesh);
  104765. }
  104766. return true;
  104767. }
  104768. // ASCII .stl
  104769. // convert to string
  104770. var array_buffer = new Uint8Array(data);
  104771. var str = '';
  104772. for (var i = 0; i < data.byteLength; i++) {
  104773. str += String.fromCharCode(array_buffer[i]); // implicitly assumes little-endian
  104774. }
  104775. data = str;
  104776. while (matches = this.solidPattern.exec(data)) {
  104777. var meshName = matches[1];
  104778. var meshNameFromEnd = matches[3];
  104779. if (meshName != meshNameFromEnd) {
  104780. BABYLON.Tools.Error("Error in STL, solid name != endsolid name");
  104781. return false;
  104782. }
  104783. // check meshesNames
  104784. if (meshesNames && meshName) {
  104785. if (meshesNames instanceof Array) {
  104786. if (!meshesNames.indexOf(meshName)) {
  104787. continue;
  104788. }
  104789. }
  104790. else {
  104791. if (meshName !== meshesNames) {
  104792. continue;
  104793. }
  104794. }
  104795. }
  104796. // stl mesh name can be empty as well
  104797. meshName = meshName || "stlmesh";
  104798. var babylonMesh = new BABYLON.Mesh(meshName, scene);
  104799. this.parseASCII(babylonMesh, matches[2]);
  104800. if (meshes) {
  104801. meshes.push(babylonMesh);
  104802. }
  104803. }
  104804. return true;
  104805. };
  104806. STLFileLoader.prototype.load = function (scene, data, rootUrl) {
  104807. var result = this.importMesh(null, scene, data, rootUrl, null, null, null);
  104808. if (result) {
  104809. scene.createDefaultCameraOrLight();
  104810. }
  104811. return result;
  104812. };
  104813. STLFileLoader.prototype.loadAssetContainer = function (scene, data, rootUrl, onError) {
  104814. var container = new BABYLON.AssetContainer(scene);
  104815. this.importMesh(null, scene, data, rootUrl, container.meshes, null, null);
  104816. container.removeAllFromScene();
  104817. return container;
  104818. };
  104819. STLFileLoader.prototype.isBinary = function (data) {
  104820. // check if file size is correct for binary stl
  104821. var faceSize, nFaces, reader;
  104822. reader = new DataView(data);
  104823. faceSize = (32 / 8 * 3) + ((32 / 8 * 3) * 3) + (16 / 8);
  104824. nFaces = reader.getUint32(80, true);
  104825. if (80 + (32 / 8) + (nFaces * faceSize) === reader.byteLength) {
  104826. return true;
  104827. }
  104828. // check characters higher than ASCII to confirm binary
  104829. var fileLength = reader.byteLength;
  104830. for (var index = 0; index < fileLength; index++) {
  104831. if (reader.getUint8(index) > 127) {
  104832. return true;
  104833. }
  104834. }
  104835. return false;
  104836. };
  104837. STLFileLoader.prototype.parseBinary = function (mesh, data) {
  104838. var reader = new DataView(data);
  104839. var faces = reader.getUint32(80, true);
  104840. var dataOffset = 84;
  104841. var faceLength = 12 * 4 + 2;
  104842. var offset = 0;
  104843. var positions = new Float32Array(faces * 3 * 3);
  104844. var normals = new Float32Array(faces * 3 * 3);
  104845. var indices = new Uint32Array(faces * 3);
  104846. var indicesCount = 0;
  104847. for (var face = 0; face < faces; face++) {
  104848. var start = dataOffset + face * faceLength;
  104849. var normalX = reader.getFloat32(start, true);
  104850. var normalY = reader.getFloat32(start + 4, true);
  104851. var normalZ = reader.getFloat32(start + 8, true);
  104852. for (var i = 1; i <= 3; i++) {
  104853. var vertexstart = start + i * 12;
  104854. // ordering is intentional to match ascii import
  104855. positions[offset] = reader.getFloat32(vertexstart, true);
  104856. positions[offset + 2] = reader.getFloat32(vertexstart + 4, true);
  104857. positions[offset + 1] = reader.getFloat32(vertexstart + 8, true);
  104858. normals[offset] = normalX;
  104859. normals[offset + 2] = normalY;
  104860. normals[offset + 1] = normalZ;
  104861. offset += 3;
  104862. }
  104863. indices[indicesCount] = indicesCount++;
  104864. indices[indicesCount] = indicesCount++;
  104865. indices[indicesCount] = indicesCount++;
  104866. }
  104867. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  104868. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  104869. mesh.setIndices(indices);
  104870. mesh.computeWorldMatrix(true);
  104871. };
  104872. STLFileLoader.prototype.parseASCII = function (mesh, solidData) {
  104873. var positions = [];
  104874. var normals = [];
  104875. var indices = [];
  104876. var indicesCount = 0;
  104877. //load facets, ignoring loop as the standard doesn't define it can contain more than vertices
  104878. var matches;
  104879. while (matches = this.facetsPattern.exec(solidData)) {
  104880. var facet = matches[1];
  104881. //one normal per face
  104882. var normalMatches = this.normalPattern.exec(facet);
  104883. this.normalPattern.lastIndex = 0;
  104884. if (!normalMatches) {
  104885. continue;
  104886. }
  104887. var normal = [Number(normalMatches[1]), Number(normalMatches[5]), Number(normalMatches[3])];
  104888. var vertexMatch;
  104889. while (vertexMatch = this.vertexPattern.exec(facet)) {
  104890. positions.push(Number(vertexMatch[1]), Number(vertexMatch[5]), Number(vertexMatch[3]));
  104891. normals.push(normal[0], normal[1], normal[2]);
  104892. }
  104893. indices.push(indicesCount++, indicesCount++, indicesCount++);
  104894. this.vertexPattern.lastIndex = 0;
  104895. }
  104896. this.facetsPattern.lastIndex = 0;
  104897. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  104898. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  104899. mesh.setIndices(indices);
  104900. mesh.computeWorldMatrix(true);
  104901. };
  104902. return STLFileLoader;
  104903. }());
  104904. BABYLON.STLFileLoader = STLFileLoader;
  104905. if (BABYLON.SceneLoader) {
  104906. BABYLON.SceneLoader.RegisterPlugin(new STLFileLoader());
  104907. }
  104908. })(BABYLON || (BABYLON = {}));
  104909. //# sourceMappingURL=babylon.stlFileLoader.js.map
  104910. var BABYLON;
  104911. (function (BABYLON) {
  104912. /**
  104913. * Class reading and parsing the MTL file bundled with the obj file.
  104914. */
  104915. var MTLFileLoader = /** @class */ (function () {
  104916. function MTLFileLoader() {
  104917. // All material loaded from the mtl will be set here
  104918. this.materials = [];
  104919. }
  104920. /**
  104921. * This function will read the mtl file and create each material described inside
  104922. * This function could be improve by adding :
  104923. * -some component missing (Ni, Tf...)
  104924. * -including the specific options available
  104925. *
  104926. * @param scene
  104927. * @param data
  104928. * @param rootUrl
  104929. */
  104930. MTLFileLoader.prototype.parseMTL = function (scene, data, rootUrl) {
  104931. //Split the lines from the file
  104932. var lines = data.split('\n');
  104933. //Space char
  104934. var delimiter_pattern = /\s+/;
  104935. //Array with RGB colors
  104936. var color;
  104937. //New material
  104938. var material = null;
  104939. //Look at each line
  104940. for (var i = 0; i < lines.length; i++) {
  104941. var line = lines[i].trim();
  104942. // Blank line or comment
  104943. if (line.length === 0 || line.charAt(0) === '#') {
  104944. continue;
  104945. }
  104946. //Get the first parameter (keyword)
  104947. var pos = line.indexOf(' ');
  104948. var key = (pos >= 0) ? line.substring(0, pos) : line;
  104949. key = key.toLowerCase();
  104950. //Get the data following the key
  104951. var value = (pos >= 0) ? line.substring(pos + 1).trim() : "";
  104952. //This mtl keyword will create the new material
  104953. if (key === "newmtl") {
  104954. //Check if it is the first material.
  104955. // Materials specifications are described after this keyword.
  104956. if (material) {
  104957. //Add the previous material in the material array.
  104958. this.materials.push(material);
  104959. }
  104960. //Create a new material.
  104961. // value is the name of the material read in the mtl file
  104962. material = new BABYLON.StandardMaterial(value, scene);
  104963. }
  104964. else if (key === "kd" && material) {
  104965. // Diffuse color (color under white light) using RGB values
  104966. //value = "r g b"
  104967. color = value.split(delimiter_pattern, 3).map(parseFloat);
  104968. //color = [r,g,b]
  104969. //Set tghe color into the material
  104970. material.diffuseColor = BABYLON.Color3.FromArray(color);
  104971. }
  104972. else if (key === "ka" && material) {
  104973. // Ambient color (color under shadow) using RGB values
  104974. //value = "r g b"
  104975. color = value.split(delimiter_pattern, 3).map(parseFloat);
  104976. //color = [r,g,b]
  104977. //Set tghe color into the material
  104978. material.ambientColor = BABYLON.Color3.FromArray(color);
  104979. }
  104980. else if (key === "ks" && material) {
  104981. // Specular color (color when light is reflected from shiny surface) using RGB values
  104982. //value = "r g b"
  104983. color = value.split(delimiter_pattern, 3).map(parseFloat);
  104984. //color = [r,g,b]
  104985. //Set the color into the material
  104986. material.specularColor = BABYLON.Color3.FromArray(color);
  104987. }
  104988. else if (key === "ke" && material) {
  104989. // Emissive color using RGB values
  104990. color = value.split(delimiter_pattern, 3).map(parseFloat);
  104991. material.emissiveColor = BABYLON.Color3.FromArray(color);
  104992. }
  104993. else if (key === "ns" && material) {
  104994. //value = "Integer"
  104995. material.specularPower = parseFloat(value);
  104996. }
  104997. else if (key === "d" && material) {
  104998. //d is dissolve for current material. It mean alpha for BABYLON
  104999. material.alpha = parseFloat(value);
  105000. //Texture
  105001. //This part can be improved by adding the possible options of texture
  105002. }
  105003. else if (key === "map_ka" && material) {
  105004. // ambient texture map with a loaded image
  105005. //We must first get the folder of the image
  105006. material.ambientTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  105007. }
  105008. else if (key === "map_kd" && material) {
  105009. // Diffuse texture map with a loaded image
  105010. material.diffuseTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  105011. }
  105012. else if (key === "map_ks" && material) {
  105013. // Specular texture map with a loaded image
  105014. //We must first get the folder of the image
  105015. material.specularTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  105016. }
  105017. else if (key === "map_ns") {
  105018. //Specular
  105019. //Specular highlight component
  105020. //We must first get the folder of the image
  105021. //
  105022. //Not supported by BABYLON
  105023. //
  105024. // continue;
  105025. }
  105026. else if (key === "map_bump" && material) {
  105027. //The bump texture
  105028. material.bumpTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  105029. }
  105030. else if (key === "map_d" && material) {
  105031. // The dissolve of the material
  105032. material.opacityTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  105033. //Options for illumination
  105034. }
  105035. else if (key === "illum") {
  105036. //Illumination
  105037. if (value === "0") {
  105038. //That mean Kd == Kd
  105039. }
  105040. else if (value === "1") {
  105041. //Color on and Ambient on
  105042. }
  105043. else if (value === "2") {
  105044. //Highlight on
  105045. }
  105046. else if (value === "3") {
  105047. //Reflection on and Ray trace on
  105048. }
  105049. else if (value === "4") {
  105050. //Transparency: Glass on, Reflection: Ray trace on
  105051. }
  105052. else if (value === "5") {
  105053. //Reflection: Fresnel on and Ray trace on
  105054. }
  105055. else if (value === "6") {
  105056. //Transparency: Refraction on, Reflection: Fresnel off and Ray trace on
  105057. }
  105058. else if (value === "7") {
  105059. //Transparency: Refraction on, Reflection: Fresnel on and Ray trace on
  105060. }
  105061. else if (value === "8") {
  105062. //Reflection on and Ray trace off
  105063. }
  105064. else if (value === "9") {
  105065. //Transparency: Glass on, Reflection: Ray trace off
  105066. }
  105067. else if (value === "10") {
  105068. //Casts shadows onto invisible surfaces
  105069. }
  105070. }
  105071. else {
  105072. // console.log("Unhandled expression at line : " + i +'\n' + "with value : " + line);
  105073. }
  105074. }
  105075. //At the end of the file, add the last material
  105076. if (material) {
  105077. this.materials.push(material);
  105078. }
  105079. };
  105080. /**
  105081. * Gets the texture for the material.
  105082. *
  105083. * If the material is imported from input file,
  105084. * We sanitize the url to ensure it takes the textre from aside the material.
  105085. *
  105086. * @param rootUrl The root url to load from
  105087. * @param value The value stored in the mtl
  105088. * @return The Texture
  105089. */
  105090. MTLFileLoader._getTexture = function (rootUrl, value, scene) {
  105091. if (!value) {
  105092. return null;
  105093. }
  105094. var url = rootUrl;
  105095. // Load from input file.
  105096. if (rootUrl === "file:") {
  105097. var lastDelimiter = value.lastIndexOf("\\");
  105098. if (lastDelimiter === -1) {
  105099. lastDelimiter = value.lastIndexOf("/");
  105100. }
  105101. if (lastDelimiter > -1) {
  105102. url += value.substr(lastDelimiter + 1);
  105103. }
  105104. else {
  105105. url += value;
  105106. }
  105107. }
  105108. else {
  105109. url += value;
  105110. }
  105111. return new BABYLON.Texture(url, scene);
  105112. };
  105113. return MTLFileLoader;
  105114. }());
  105115. BABYLON.MTLFileLoader = MTLFileLoader;
  105116. var OBJFileLoader = /** @class */ (function () {
  105117. function OBJFileLoader() {
  105118. this.name = "obj";
  105119. this.extensions = ".obj";
  105120. this.obj = /^o/;
  105121. this.group = /^g/;
  105122. this.mtllib = /^mtllib /;
  105123. this.usemtl = /^usemtl /;
  105124. this.smooth = /^s /;
  105125. this.vertexPattern = /v( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)/;
  105126. // vn float float float
  105127. this.normalPattern = /vn( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)/;
  105128. // vt float float
  105129. this.uvPattern = /vt( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)/;
  105130. // f vertex vertex vertex ...
  105131. this.facePattern1 = /f\s+(([\d]{1,}[\s]?){3,})+/;
  105132. // f vertex/uvs vertex/uvs vertex/uvs ...
  105133. this.facePattern2 = /f\s+((([\d]{1,}\/[\d]{1,}[\s]?){3,})+)/;
  105134. // f vertex/uvs/normal vertex/uvs/normal vertex/uvs/normal ...
  105135. this.facePattern3 = /f\s+((([\d]{1,}\/[\d]{1,}\/[\d]{1,}[\s]?){3,})+)/;
  105136. // f vertex//normal vertex//normal vertex//normal ...
  105137. this.facePattern4 = /f\s+((([\d]{1,}\/\/[\d]{1,}[\s]?){3,})+)/;
  105138. }
  105139. /**
  105140. * Calls synchronously the MTL file attached to this obj.
  105141. * Load function or importMesh function don't enable to load 2 files in the same time asynchronously.
  105142. * Without this function materials are not displayed in the first frame (but displayed after).
  105143. * In consequence it is impossible to get material information in your HTML file
  105144. *
  105145. * @param url The URL of the MTL file
  105146. * @param rootUrl
  105147. * @param onSuccess Callback function to be called when the MTL file is loaded
  105148. * @private
  105149. */
  105150. OBJFileLoader.prototype._loadMTL = function (url, rootUrl, onSuccess) {
  105151. //The complete path to the mtl file
  105152. var pathOfFile = BABYLON.Tools.BaseUrl + rootUrl + url;
  105153. // Loads through the babylon tools to allow fileInput search.
  105154. BABYLON.Tools.LoadFile(pathOfFile, onSuccess, undefined, undefined, false, function () { console.warn("Error - Unable to load " + pathOfFile); });
  105155. };
  105156. OBJFileLoader.prototype.importMesh = function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  105157. //get the meshes from OBJ file
  105158. var loadedMeshes = this._parseSolid(meshesNames, scene, data, rootUrl);
  105159. //Push meshes from OBJ file into the variable mesh of this function
  105160. if (meshes) {
  105161. loadedMeshes.forEach(function (mesh) {
  105162. meshes.push(mesh);
  105163. });
  105164. }
  105165. return true;
  105166. };
  105167. OBJFileLoader.prototype.load = function (scene, data, rootUrl) {
  105168. //Get the 3D model
  105169. return this.importMesh(null, scene, data, rootUrl, null, null, null);
  105170. };
  105171. OBJFileLoader.prototype.loadAssetContainer = function (scene, data, rootUrl, onError) {
  105172. var container = new BABYLON.AssetContainer(scene);
  105173. this.importMesh(null, scene, data, rootUrl, container.meshes, null, null);
  105174. container.removeAllFromScene();
  105175. return container;
  105176. };
  105177. /**
  105178. * Read the OBJ file and create an Array of meshes.
  105179. * Each mesh contains all information given by the OBJ and the MTL file.
  105180. * i.e. vertices positions and indices, optional normals values, optional UV values, optional material
  105181. *
  105182. * @param meshesNames
  105183. * @param scene BABYLON.Scene The scene where are displayed the data
  105184. * @param data String The content of the obj file
  105185. * @param rootUrl String The path to the folder
  105186. * @returns Array<AbstractMesh>
  105187. * @private
  105188. */
  105189. OBJFileLoader.prototype._parseSolid = function (meshesNames, scene, data, rootUrl) {
  105190. var positions = []; //values for the positions of vertices
  105191. var normals = []; //Values for the normals
  105192. var uvs = []; //Values for the textures
  105193. var meshesFromObj = []; //[mesh] Contains all the obj meshes
  105194. var handledMesh; //The current mesh of meshes array
  105195. var indicesForBabylon = []; //The list of indices for VertexData
  105196. var wrappedPositionForBabylon = []; //The list of position in vectors
  105197. var wrappedUvsForBabylon = []; //Array with all value of uvs to match with the indices
  105198. var wrappedNormalsForBabylon = []; //Array with all value of normals to match with the indices
  105199. var tuplePosNorm = []; //Create a tuple with indice of Position, Normal, UV [pos, norm, uvs]
  105200. var curPositionInIndices = 0;
  105201. var hasMeshes = false; //Meshes are defined in the file
  105202. var unwrappedPositionsForBabylon = []; //Value of positionForBabylon w/o Vector3() [x,y,z]
  105203. var unwrappedNormalsForBabylon = []; //Value of normalsForBabylon w/o Vector3() [x,y,z]
  105204. var unwrappedUVForBabylon = []; //Value of uvsForBabylon w/o Vector3() [x,y,z]
  105205. var triangles = []; //Indices from new triangles coming from polygons
  105206. var materialNameFromObj = ""; //The name of the current material
  105207. var fileToLoad = ""; //The name of the mtlFile to load
  105208. var materialsFromMTLFile = new MTLFileLoader();
  105209. var objMeshName = ""; //The name of the current obj mesh
  105210. var increment = 1; //Id for meshes created by the multimaterial
  105211. var isFirstMaterial = true;
  105212. /**
  105213. * Search for obj in the given array.
  105214. * This function is called to check if a couple of data already exists in an array.
  105215. *
  105216. * If found, returns the index of the founded tuple index. Returns -1 if not found
  105217. * @param arr Array<{ normals: Array<number>, idx: Array<number> }>
  105218. * @param obj Array<number>
  105219. * @returns {boolean}
  105220. */
  105221. var isInArray = function (arr, obj) {
  105222. if (!arr[obj[0]])
  105223. arr[obj[0]] = { normals: [], idx: [] };
  105224. var idx = arr[obj[0]].normals.indexOf(obj[1]);
  105225. return idx === -1 ? -1 : arr[obj[0]].idx[idx];
  105226. };
  105227. var isInArrayUV = function (arr, obj) {
  105228. if (!arr[obj[0]])
  105229. arr[obj[0]] = { normals: [], idx: [], uv: [] };
  105230. var idx = arr[obj[0]].normals.indexOf(obj[1]);
  105231. if (idx != 1 && (obj[2] == arr[obj[0]].uv[idx])) {
  105232. return arr[obj[0]].idx[idx];
  105233. }
  105234. return -1;
  105235. };
  105236. /**
  105237. * This function set the data for each triangle.
  105238. * Data are position, normals and uvs
  105239. * If a tuple of (position, normal) is not set, add the data into the corresponding array
  105240. * If the tuple already exist, add only their indice
  105241. *
  105242. * @param indicePositionFromObj Integer The index in positions array
  105243. * @param indiceUvsFromObj Integer The index in uvs array
  105244. * @param indiceNormalFromObj Integer The index in normals array
  105245. * @param positionVectorFromOBJ Vector3 The value of position at index objIndice
  105246. * @param textureVectorFromOBJ Vector3 The value of uvs
  105247. * @param normalsVectorFromOBJ Vector3 The value of normals at index objNormale
  105248. */
  105249. var setData = function (indicePositionFromObj, indiceUvsFromObj, indiceNormalFromObj, positionVectorFromOBJ, textureVectorFromOBJ, normalsVectorFromOBJ) {
  105250. //Check if this tuple already exists in the list of tuples
  105251. var _index;
  105252. if (OBJFileLoader.OPTIMIZE_WITH_UV) {
  105253. _index = isInArrayUV(tuplePosNorm, [
  105254. indicePositionFromObj,
  105255. indiceNormalFromObj,
  105256. indiceUvsFromObj
  105257. ]);
  105258. }
  105259. else {
  105260. _index = isInArray(tuplePosNorm, [
  105261. indicePositionFromObj,
  105262. indiceNormalFromObj
  105263. ]);
  105264. }
  105265. //If it not exists
  105266. if (_index == -1) {
  105267. //Add an new indice.
  105268. //The array of indices is only an array with his length equal to the number of triangles - 1.
  105269. //We add vertices data in this order
  105270. indicesForBabylon.push(wrappedPositionForBabylon.length);
  105271. //Push the position of vertice for Babylon
  105272. //Each element is a BABYLON.Vector3(x,y,z)
  105273. wrappedPositionForBabylon.push(positionVectorFromOBJ);
  105274. //Push the uvs for Babylon
  105275. //Each element is a BABYLON.Vector3(u,v)
  105276. wrappedUvsForBabylon.push(textureVectorFromOBJ);
  105277. //Push the normals for Babylon
  105278. //Each element is a BABYLON.Vector3(x,y,z)
  105279. wrappedNormalsForBabylon.push(normalsVectorFromOBJ);
  105280. //Add the tuple in the comparison list
  105281. tuplePosNorm[indicePositionFromObj].normals.push(indiceNormalFromObj);
  105282. tuplePosNorm[indicePositionFromObj].idx.push(curPositionInIndices++);
  105283. if (OBJFileLoader.OPTIMIZE_WITH_UV)
  105284. tuplePosNorm[indicePositionFromObj].uv.push(indiceUvsFromObj);
  105285. }
  105286. else {
  105287. //The tuple already exists
  105288. //Add the index of the already existing tuple
  105289. //At this index we can get the value of position, normal and uvs of vertex
  105290. indicesForBabylon.push(_index);
  105291. }
  105292. };
  105293. /**
  105294. * Transform BABYLON.Vector() object onto 3 digits in an array
  105295. */
  105296. var unwrapData = function () {
  105297. //Every array has the same length
  105298. for (var l = 0; l < wrappedPositionForBabylon.length; l++) {
  105299. //Push the x, y, z values of each element in the unwrapped array
  105300. unwrappedPositionsForBabylon.push(wrappedPositionForBabylon[l].x, wrappedPositionForBabylon[l].y, wrappedPositionForBabylon[l].z);
  105301. unwrappedNormalsForBabylon.push(wrappedNormalsForBabylon[l].x, wrappedNormalsForBabylon[l].y, wrappedNormalsForBabylon[l].z);
  105302. unwrappedUVForBabylon.push(wrappedUvsForBabylon[l].x, wrappedUvsForBabylon[l].y); //z is an optional value not supported by BABYLON
  105303. }
  105304. // Reset arrays for the next new meshes
  105305. wrappedPositionForBabylon = [];
  105306. wrappedNormalsForBabylon = [];
  105307. wrappedUvsForBabylon = [];
  105308. tuplePosNorm = [];
  105309. curPositionInIndices = 0;
  105310. };
  105311. /**
  105312. * Create triangles from polygons by recursion
  105313. * The best to understand how it works is to draw it in the same time you get the recursion.
  105314. * It is important to notice that a triangle is a polygon
  105315. * We get 4 patterns of face defined in OBJ File :
  105316. * facePattern1 = ["1","2","3","4","5","6"]
  105317. * facePattern2 = ["1/1","2/2","3/3","4/4","5/5","6/6"]
  105318. * facePattern3 = ["1/1/1","2/2/2","3/3/3","4/4/4","5/5/5","6/6/6"]
  105319. * facePattern4 = ["1//1","2//2","3//3","4//4","5//5","6//6"]
  105320. * Each pattern is divided by the same method
  105321. * @param face Array[String] The indices of elements
  105322. * @param v Integer The variable to increment
  105323. */
  105324. var getTriangles = function (face, v) {
  105325. //Work for each element of the array
  105326. if (v + 1 < face.length) {
  105327. //Add on the triangle variable the indexes to obtain triangles
  105328. triangles.push(face[0], face[v], face[v + 1]);
  105329. //Incrementation for recursion
  105330. v += 1;
  105331. //Recursion
  105332. getTriangles(face, v);
  105333. }
  105334. //Result obtained after 2 iterations:
  105335. //Pattern1 => triangle = ["1","2","3","1","3","4"];
  105336. //Pattern2 => triangle = ["1/1","2/2","3/3","1/1","3/3","4/4"];
  105337. //Pattern3 => triangle = ["1/1/1","2/2/2","3/3/3","1/1/1","3/3/3","4/4/4"];
  105338. //Pattern4 => triangle = ["1//1","2//2","3//3","1//1","3//3","4//4"];
  105339. };
  105340. /**
  105341. * Create triangles and push the data for each polygon for the pattern 1
  105342. * In this pattern we get vertice positions
  105343. * @param face
  105344. * @param v
  105345. */
  105346. var setDataForCurrentFaceWithPattern1 = function (face, v) {
  105347. //Get the indices of triangles for each polygon
  105348. getTriangles(face, v);
  105349. //For each element in the triangles array.
  105350. //This var could contains 1 to an infinity of triangles
  105351. for (var k = 0; k < triangles.length; k++) {
  105352. // Set position indice
  105353. var indicePositionFromObj = parseInt(triangles[k]) - 1;
  105354. setData(indicePositionFromObj, 0, 0, //In the pattern 1, normals and uvs are not defined
  105355. positions[indicePositionFromObj], //Get the vectors data
  105356. BABYLON.Vector2.Zero(), BABYLON.Vector3.Up() //Create default vectors
  105357. );
  105358. }
  105359. //Reset variable for the next line
  105360. triangles = [];
  105361. };
  105362. /**
  105363. * Create triangles and push the data for each polygon for the pattern 2
  105364. * In this pattern we get vertice positions and uvsu
  105365. * @param face
  105366. * @param v
  105367. */
  105368. var setDataForCurrentFaceWithPattern2 = function (face, v) {
  105369. //Get the indices of triangles for each polygon
  105370. getTriangles(face, v);
  105371. for (var k = 0; k < triangles.length; k++) {
  105372. //triangle[k] = "1/1"
  105373. //Split the data for getting position and uv
  105374. var point = triangles[k].split("/"); // ["1", "1"]
  105375. //Set position indice
  105376. var indicePositionFromObj = parseInt(point[0]) - 1;
  105377. //Set uv indice
  105378. var indiceUvsFromObj = parseInt(point[1]) - 1;
  105379. setData(indicePositionFromObj, indiceUvsFromObj, 0, //Default value for normals
  105380. positions[indicePositionFromObj], //Get the values for each element
  105381. uvs[indiceUvsFromObj], BABYLON.Vector3.Up() //Default value for normals
  105382. );
  105383. }
  105384. //Reset variable for the next line
  105385. triangles = [];
  105386. };
  105387. /**
  105388. * Create triangles and push the data for each polygon for the pattern 3
  105389. * In this pattern we get vertice positions, uvs and normals
  105390. * @param face
  105391. * @param v
  105392. */
  105393. var setDataForCurrentFaceWithPattern3 = function (face, v) {
  105394. //Get the indices of triangles for each polygon
  105395. getTriangles(face, v);
  105396. for (var k = 0; k < triangles.length; k++) {
  105397. //triangle[k] = "1/1/1"
  105398. //Split the data for getting position, uv, and normals
  105399. var point = triangles[k].split("/"); // ["1", "1", "1"]
  105400. // Set position indice
  105401. var indicePositionFromObj = parseInt(point[0]) - 1;
  105402. // Set uv indice
  105403. var indiceUvsFromObj = parseInt(point[1]) - 1;
  105404. // Set normal indice
  105405. var indiceNormalFromObj = parseInt(point[2]) - 1;
  105406. setData(indicePositionFromObj, indiceUvsFromObj, indiceNormalFromObj, positions[indicePositionFromObj], uvs[indiceUvsFromObj], normals[indiceNormalFromObj] //Set the vector for each component
  105407. );
  105408. }
  105409. //Reset variable for the next line
  105410. triangles = [];
  105411. };
  105412. /**
  105413. * Create triangles and push the data for each polygon for the pattern 4
  105414. * In this pattern we get vertice positions and normals
  105415. * @param face
  105416. * @param v
  105417. */
  105418. var setDataForCurrentFaceWithPattern4 = function (face, v) {
  105419. getTriangles(face, v);
  105420. for (var k = 0; k < triangles.length; k++) {
  105421. //triangle[k] = "1//1"
  105422. //Split the data for getting position and normals
  105423. var point = triangles[k].split("//"); // ["1", "1"]
  105424. // We check indices, and normals
  105425. var indicePositionFromObj = parseInt(point[0]) - 1;
  105426. var indiceNormalFromObj = parseInt(point[1]) - 1;
  105427. setData(indicePositionFromObj, 1, //Default value for uv
  105428. indiceNormalFromObj, positions[indicePositionFromObj], //Get each vector of data
  105429. BABYLON.Vector2.Zero(), normals[indiceNormalFromObj]);
  105430. }
  105431. //Reset variable for the next line
  105432. triangles = [];
  105433. };
  105434. var addPreviousObjMesh = function () {
  105435. //Check if it is not the first mesh. Otherwise we don't have data.
  105436. if (meshesFromObj.length > 0) {
  105437. //Get the previous mesh for applying the data about the faces
  105438. //=> in obj file, faces definition append after the name of the mesh
  105439. handledMesh = meshesFromObj[meshesFromObj.length - 1];
  105440. //Set the data into Array for the mesh
  105441. unwrapData();
  105442. // Reverse tab. Otherwise face are displayed in the wrong sens
  105443. indicesForBabylon.reverse();
  105444. //Set the information for the mesh
  105445. //Slice the array to avoid rewriting because of the fact this is the same var which be rewrited
  105446. handledMesh.indices = indicesForBabylon.slice();
  105447. handledMesh.positions = unwrappedPositionsForBabylon.slice();
  105448. handledMesh.normals = unwrappedNormalsForBabylon.slice();
  105449. handledMesh.uvs = unwrappedUVForBabylon.slice();
  105450. //Reset the array for the next mesh
  105451. indicesForBabylon = [];
  105452. unwrappedPositionsForBabylon = [];
  105453. unwrappedNormalsForBabylon = [];
  105454. unwrappedUVForBabylon = [];
  105455. }
  105456. };
  105457. //Main function
  105458. //Split the file into lines
  105459. var lines = data.split('\n');
  105460. //Look at each line
  105461. for (var i = 0; i < lines.length; i++) {
  105462. var line = lines[i].trim();
  105463. var result;
  105464. //Comment or newLine
  105465. if (line.length === 0 || line.charAt(0) === '#') {
  105466. continue;
  105467. //Get information about one position possible for the vertices
  105468. }
  105469. else if ((result = this.vertexPattern.exec(line)) !== null) {
  105470. //Create a Vector3 with the position x, y, z
  105471. //Value of result:
  105472. // ["v 1.0 2.0 3.0", "1.0", "2.0", "3.0"]
  105473. //Add the Vector in the list of positions
  105474. positions.push(new BABYLON.Vector3(parseFloat(result[1]), parseFloat(result[2]), parseFloat(result[3])));
  105475. }
  105476. else if ((result = this.normalPattern.exec(line)) !== null) {
  105477. //Create a Vector3 with the normals x, y, z
  105478. //Value of result
  105479. // ["vn 1.0 2.0 3.0", "1.0", "2.0", "3.0"]
  105480. //Add the Vector in the list of normals
  105481. normals.push(new BABYLON.Vector3(parseFloat(result[1]), parseFloat(result[2]), parseFloat(result[3])));
  105482. }
  105483. else if ((result = this.uvPattern.exec(line)) !== null) {
  105484. //Create a Vector2 with the normals u, v
  105485. //Value of result
  105486. // ["vt 0.1 0.2 0.3", "0.1", "0.2"]
  105487. //Add the Vector in the list of uvs
  105488. uvs.push(new BABYLON.Vector2(parseFloat(result[1]), parseFloat(result[2])));
  105489. //Identify patterns of faces
  105490. //Face could be defined in different type of pattern
  105491. }
  105492. else if ((result = this.facePattern3.exec(line)) !== null) {
  105493. //Value of result:
  105494. //["f 1/1/1 2/2/2 3/3/3", "1/1/1 2/2/2 3/3/3"...]
  105495. //Set the data for this face
  105496. setDataForCurrentFaceWithPattern3(result[1].trim().split(" "), // ["1/1/1", "2/2/2", "3/3/3"]
  105497. 1);
  105498. }
  105499. else if ((result = this.facePattern4.exec(line)) !== null) {
  105500. //Value of result:
  105501. //["f 1//1 2//2 3//3", "1//1 2//2 3//3"...]
  105502. //Set the data for this face
  105503. setDataForCurrentFaceWithPattern4(result[1].trim().split(" "), // ["1//1", "2//2", "3//3"]
  105504. 1);
  105505. }
  105506. else if ((result = this.facePattern2.exec(line)) !== null) {
  105507. //Value of result:
  105508. //["f 1/1 2/2 3/3", "1/1 2/2 3/3"...]
  105509. //Set the data for this face
  105510. setDataForCurrentFaceWithPattern2(result[1].trim().split(" "), // ["1/1", "2/2", "3/3"]
  105511. 1);
  105512. }
  105513. else if ((result = this.facePattern1.exec(line)) !== null) {
  105514. //Value of result
  105515. //["f 1 2 3", "1 2 3"...]
  105516. //Set the data for this face
  105517. setDataForCurrentFaceWithPattern1(result[1].trim().split(" "), // ["1", "2", "3"]
  105518. 1);
  105519. //Define a mesh or an object
  105520. //Each time this keyword is analysed, create a new Object with all data for creating a babylonMesh
  105521. }
  105522. else if (this.group.test(line) || this.obj.test(line)) {
  105523. //Create a new mesh corresponding to the name of the group.
  105524. //Definition of the mesh
  105525. var objMesh =
  105526. //Set the name of the current obj mesh
  105527. {
  105528. name: line.substring(2).trim(),
  105529. indices: undefined,
  105530. positions: undefined,
  105531. normals: undefined,
  105532. uvs: undefined,
  105533. materialName: ""
  105534. };
  105535. addPreviousObjMesh();
  105536. //Push the last mesh created with only the name
  105537. meshesFromObj.push(objMesh);
  105538. //Set this variable to indicate that now meshesFromObj has objects defined inside
  105539. hasMeshes = true;
  105540. isFirstMaterial = true;
  105541. increment = 1;
  105542. //Keyword for applying a material
  105543. }
  105544. else if (this.usemtl.test(line)) {
  105545. //Get the name of the material
  105546. materialNameFromObj = line.substring(7).trim();
  105547. //If this new material is in the same mesh
  105548. if (!isFirstMaterial) {
  105549. //Set the data for the previous mesh
  105550. addPreviousObjMesh();
  105551. //Create a new mesh
  105552. var objMesh =
  105553. //Set the name of the current obj mesh
  105554. {
  105555. name: objMeshName + "_mm" + increment.toString(),
  105556. indices: undefined,
  105557. positions: undefined,
  105558. normals: undefined,
  105559. uvs: undefined,
  105560. materialName: materialNameFromObj
  105561. };
  105562. increment++;
  105563. //If meshes are already defined
  105564. meshesFromObj.push(objMesh);
  105565. }
  105566. //Set the material name if the previous line define a mesh
  105567. if (hasMeshes && isFirstMaterial) {
  105568. //Set the material name to the previous mesh (1 material per mesh)
  105569. meshesFromObj[meshesFromObj.length - 1].materialName = materialNameFromObj;
  105570. isFirstMaterial = false;
  105571. }
  105572. //Keyword for loading the mtl file
  105573. }
  105574. else if (this.mtllib.test(line)) {
  105575. //Get the name of mtl file
  105576. fileToLoad = line.substring(7).trim();
  105577. //Apply smoothing
  105578. }
  105579. else if (this.smooth.test(line)) {
  105580. // smooth shading => apply smoothing
  105581. //Toda y I don't know it work with babylon and with obj.
  105582. //With the obj file an integer is set
  105583. }
  105584. else {
  105585. //If there is another possibility
  105586. console.log("Unhandled expression at line : " + line);
  105587. }
  105588. }
  105589. //At the end of the file, add the last mesh into the meshesFromObj array
  105590. if (hasMeshes) {
  105591. //Set the data for the last mesh
  105592. handledMesh = meshesFromObj[meshesFromObj.length - 1];
  105593. //Reverse indices for displaying faces in the good sens
  105594. indicesForBabylon.reverse();
  105595. //Get the good array
  105596. unwrapData();
  105597. //Set array
  105598. handledMesh.indices = indicesForBabylon;
  105599. handledMesh.positions = unwrappedPositionsForBabylon;
  105600. handledMesh.normals = unwrappedNormalsForBabylon;
  105601. handledMesh.uvs = unwrappedUVForBabylon;
  105602. }
  105603. //If any o or g keyword found, create a mesj with a random id
  105604. if (!hasMeshes) {
  105605. // reverse tab of indices
  105606. indicesForBabylon.reverse();
  105607. //Get positions normals uvs
  105608. unwrapData();
  105609. //Set data for one mesh
  105610. meshesFromObj.push({
  105611. name: BABYLON.Geometry.RandomId(),
  105612. indices: indicesForBabylon,
  105613. positions: unwrappedPositionsForBabylon,
  105614. normals: unwrappedNormalsForBabylon,
  105615. uvs: unwrappedUVForBabylon,
  105616. materialName: materialNameFromObj
  105617. });
  105618. }
  105619. //Create a BABYLON.Mesh list
  105620. var babylonMeshesArray = []; //The mesh for babylon
  105621. var materialToUse = new Array();
  105622. //Set data for each mesh
  105623. for (var j = 0; j < meshesFromObj.length; j++) {
  105624. //check meshesNames (stlFileLoader)
  105625. if (meshesNames && meshesFromObj[j].name) {
  105626. if (meshesNames instanceof Array) {
  105627. if (meshesNames.indexOf(meshesFromObj[j].name) == -1) {
  105628. continue;
  105629. }
  105630. }
  105631. else {
  105632. if (meshesFromObj[j].name !== meshesNames) {
  105633. continue;
  105634. }
  105635. }
  105636. }
  105637. //Get the current mesh
  105638. //Set the data with VertexBuffer for each mesh
  105639. handledMesh = meshesFromObj[j];
  105640. //Create a BABYLON.Mesh with the name of the obj mesh
  105641. var babylonMesh = new BABYLON.Mesh(meshesFromObj[j].name, scene);
  105642. //Push the name of the material to an array
  105643. //This is indispensable for the importMesh function
  105644. materialToUse.push(meshesFromObj[j].materialName);
  105645. var vertexData = new BABYLON.VertexData(); //The container for the values
  105646. //Set the data for the babylonMesh
  105647. vertexData.positions = handledMesh.positions;
  105648. vertexData.normals = handledMesh.normals;
  105649. vertexData.uvs = handledMesh.uvs;
  105650. vertexData.indices = handledMesh.indices;
  105651. //Set the data from the VertexBuffer to the current BABYLON.Mesh
  105652. vertexData.applyToMesh(babylonMesh);
  105653. //Push the mesh into an array
  105654. babylonMeshesArray.push(babylonMesh);
  105655. }
  105656. //load the materials
  105657. //Check if we have a file to load
  105658. if (fileToLoad !== "") {
  105659. //Load the file synchronously
  105660. this._loadMTL(fileToLoad, rootUrl, function (dataLoaded) {
  105661. //Create materials thanks MTLLoader function
  105662. materialsFromMTLFile.parseMTL(scene, dataLoaded, rootUrl);
  105663. //Look at each material loaded in the mtl file
  105664. for (var n = 0; n < materialsFromMTLFile.materials.length; n++) {
  105665. //Three variables to get all meshes with the same material
  105666. var startIndex = 0;
  105667. var _indices = [];
  105668. var _index;
  105669. //The material from MTL file is used in the meshes loaded
  105670. //Push the indice in an array
  105671. //Check if the material is not used for another mesh
  105672. while ((_index = materialToUse.indexOf(materialsFromMTLFile.materials[n].name, startIndex)) > -1) {
  105673. _indices.push(_index);
  105674. startIndex = _index + 1;
  105675. }
  105676. //If the material is not used dispose it
  105677. if (_index == -1 && _indices.length == 0) {
  105678. //If the material is not needed, remove it
  105679. materialsFromMTLFile.materials[n].dispose();
  105680. }
  105681. else {
  105682. for (var o = 0; o < _indices.length; o++) {
  105683. //Apply the material to the BABYLON.Mesh for each mesh with the material
  105684. babylonMeshesArray[_indices[o]].material = materialsFromMTLFile.materials[n];
  105685. }
  105686. }
  105687. }
  105688. });
  105689. }
  105690. //Return an array with all BABYLON.Mesh
  105691. return babylonMeshesArray;
  105692. };
  105693. OBJFileLoader.OPTIMIZE_WITH_UV = false;
  105694. return OBJFileLoader;
  105695. }());
  105696. BABYLON.OBJFileLoader = OBJFileLoader;
  105697. if (BABYLON.SceneLoader) {
  105698. //Add this loader into the register plugin
  105699. BABYLON.SceneLoader.RegisterPlugin(new OBJFileLoader());
  105700. }
  105701. })(BABYLON || (BABYLON = {}));
  105702. //# sourceMappingURL=babylon.objFileLoader.js.map
  105703. var BABYLON;
  105704. (function (BABYLON) {
  105705. var GLTFLoaderCoordinateSystemMode;
  105706. (function (GLTFLoaderCoordinateSystemMode) {
  105707. /**
  105708. * Automatically convert the glTF right-handed data to the appropriate system based on the current coordinate system mode of the scene.
  105709. */
  105710. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["AUTO"] = 0] = "AUTO";
  105711. /**
  105712. * Sets the useRightHandedSystem flag on the scene.
  105713. */
  105714. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["FORCE_RIGHT_HANDED"] = 1] = "FORCE_RIGHT_HANDED";
  105715. })(GLTFLoaderCoordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode || (BABYLON.GLTFLoaderCoordinateSystemMode = {}));
  105716. var GLTFLoaderAnimationStartMode;
  105717. (function (GLTFLoaderAnimationStartMode) {
  105718. /**
  105719. * No animation will start.
  105720. */
  105721. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["NONE"] = 0] = "NONE";
  105722. /**
  105723. * The first animation will start.
  105724. */
  105725. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["FIRST"] = 1] = "FIRST";
  105726. /**
  105727. * All animations will start.
  105728. */
  105729. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["ALL"] = 2] = "ALL";
  105730. })(GLTFLoaderAnimationStartMode = BABYLON.GLTFLoaderAnimationStartMode || (BABYLON.GLTFLoaderAnimationStartMode = {}));
  105731. var GLTFLoaderState;
  105732. (function (GLTFLoaderState) {
  105733. GLTFLoaderState[GLTFLoaderState["Loading"] = 0] = "Loading";
  105734. GLTFLoaderState[GLTFLoaderState["Ready"] = 1] = "Ready";
  105735. GLTFLoaderState[GLTFLoaderState["Complete"] = 2] = "Complete";
  105736. })(GLTFLoaderState = BABYLON.GLTFLoaderState || (BABYLON.GLTFLoaderState = {}));
  105737. var GLTFFileLoader = /** @class */ (function () {
  105738. function GLTFFileLoader() {
  105739. // #region Common options
  105740. /**
  105741. * Raised when the asset has been parsed.
  105742. * The data.json property stores the glTF JSON.
  105743. * The data.bin property stores the BIN chunk from a glTF binary or null if the input is not a glTF binary.
  105744. */
  105745. this.onParsedObservable = new BABYLON.Observable();
  105746. // #endregion
  105747. // #region V2 options
  105748. /**
  105749. * The coordinate system mode (AUTO, FORCE_RIGHT_HANDED).
  105750. */
  105751. this.coordinateSystemMode = GLTFLoaderCoordinateSystemMode.AUTO;
  105752. /**
  105753. * The animation start mode (NONE, FIRST, ALL).
  105754. */
  105755. this.animationStartMode = GLTFLoaderAnimationStartMode.FIRST;
  105756. /**
  105757. * Set to true to compile materials before raising the success callback.
  105758. */
  105759. this.compileMaterials = false;
  105760. /**
  105761. * Set to true to also compile materials with clip planes.
  105762. */
  105763. this.useClipPlane = false;
  105764. /**
  105765. * Set to true to compile shadow generators before raising the success callback.
  105766. */
  105767. this.compileShadowGenerators = false;
  105768. /**
  105769. * Raised when the loader creates a mesh after parsing the glTF properties of the mesh.
  105770. */
  105771. this.onMeshLoadedObservable = new BABYLON.Observable();
  105772. /**
  105773. * Raised when the loader creates a texture after parsing the glTF properties of the texture.
  105774. */
  105775. this.onTextureLoadedObservable = new BABYLON.Observable();
  105776. /**
  105777. * Raised when the loader creates a material after parsing the glTF properties of the material.
  105778. */
  105779. this.onMaterialLoadedObservable = new BABYLON.Observable();
  105780. /**
  105781. * Raised when the loader creates an animation group after parsing the glTF properties of the animation.
  105782. */
  105783. this.onAnimationGroupLoadedObservable = new BABYLON.Observable();
  105784. /**
  105785. * Raised when the asset is completely loaded, immediately before the loader is disposed.
  105786. * For assets with LODs, raised when all of the LODs are complete.
  105787. * For assets without LODs, raised when the model is complete, immediately after onSuccess.
  105788. */
  105789. this.onCompleteObservable = new BABYLON.Observable();
  105790. /**
  105791. * Raised when the loader is disposed.
  105792. */
  105793. this.onDisposeObservable = new BABYLON.Observable();
  105794. /**
  105795. * Raised after a loader extension is created.
  105796. * Set additional options for a loader extension in this event.
  105797. */
  105798. this.onExtensionLoadedObservable = new BABYLON.Observable();
  105799. // #endregion
  105800. this._loader = null;
  105801. this.name = "gltf";
  105802. this.extensions = {
  105803. ".gltf": { isBinary: false },
  105804. ".glb": { isBinary: true }
  105805. };
  105806. }
  105807. Object.defineProperty(GLTFFileLoader.prototype, "onParsed", {
  105808. set: function (callback) {
  105809. if (this._onParsedObserver) {
  105810. this.onParsedObservable.remove(this._onParsedObserver);
  105811. }
  105812. this._onParsedObserver = this.onParsedObservable.add(callback);
  105813. },
  105814. enumerable: true,
  105815. configurable: true
  105816. });
  105817. Object.defineProperty(GLTFFileLoader.prototype, "onMeshLoaded", {
  105818. set: function (callback) {
  105819. if (this._onMeshLoadedObserver) {
  105820. this.onMeshLoadedObservable.remove(this._onMeshLoadedObserver);
  105821. }
  105822. this._onMeshLoadedObserver = this.onMeshLoadedObservable.add(callback);
  105823. },
  105824. enumerable: true,
  105825. configurable: true
  105826. });
  105827. Object.defineProperty(GLTFFileLoader.prototype, "onTextureLoaded", {
  105828. set: function (callback) {
  105829. if (this._onTextureLoadedObserver) {
  105830. this.onTextureLoadedObservable.remove(this._onTextureLoadedObserver);
  105831. }
  105832. this._onTextureLoadedObserver = this.onTextureLoadedObservable.add(callback);
  105833. },
  105834. enumerable: true,
  105835. configurable: true
  105836. });
  105837. Object.defineProperty(GLTFFileLoader.prototype, "onMaterialLoaded", {
  105838. set: function (callback) {
  105839. if (this._onMaterialLoadedObserver) {
  105840. this.onMaterialLoadedObservable.remove(this._onMaterialLoadedObserver);
  105841. }
  105842. this._onMaterialLoadedObserver = this.onMaterialLoadedObservable.add(callback);
  105843. },
  105844. enumerable: true,
  105845. configurable: true
  105846. });
  105847. Object.defineProperty(GLTFFileLoader.prototype, "onAnimationGroupLoaded", {
  105848. set: function (callback) {
  105849. if (this._onAnimationGroupLoadedObserver) {
  105850. this.onAnimationGroupLoadedObservable.remove(this._onAnimationGroupLoadedObserver);
  105851. }
  105852. this._onAnimationGroupLoadedObserver = this.onAnimationGroupLoadedObservable.add(callback);
  105853. },
  105854. enumerable: true,
  105855. configurable: true
  105856. });
  105857. Object.defineProperty(GLTFFileLoader.prototype, "onComplete", {
  105858. set: function (callback) {
  105859. if (this._onCompleteObserver) {
  105860. this.onCompleteObservable.remove(this._onCompleteObserver);
  105861. }
  105862. this._onCompleteObserver = this.onCompleteObservable.add(callback);
  105863. },
  105864. enumerable: true,
  105865. configurable: true
  105866. });
  105867. Object.defineProperty(GLTFFileLoader.prototype, "onDispose", {
  105868. set: function (callback) {
  105869. if (this._onDisposeObserver) {
  105870. this.onDisposeObservable.remove(this._onDisposeObserver);
  105871. }
  105872. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  105873. },
  105874. enumerable: true,
  105875. configurable: true
  105876. });
  105877. Object.defineProperty(GLTFFileLoader.prototype, "onExtensionLoaded", {
  105878. set: function (callback) {
  105879. if (this._onExtensionLoadedObserver) {
  105880. this.onExtensionLoadedObservable.remove(this._onExtensionLoadedObserver);
  105881. }
  105882. this._onExtensionLoadedObserver = this.onExtensionLoadedObservable.add(callback);
  105883. },
  105884. enumerable: true,
  105885. configurable: true
  105886. });
  105887. /**
  105888. * Gets a promise that resolves when the asset is completely loaded.
  105889. * @returns A promise that resolves when the asset is completely loaded.
  105890. */
  105891. GLTFFileLoader.prototype.whenCompleteAsync = function () {
  105892. var _this = this;
  105893. return new Promise(function (resolve) {
  105894. _this.onCompleteObservable.add(function () {
  105895. resolve();
  105896. }, undefined, undefined, undefined, true);
  105897. });
  105898. };
  105899. Object.defineProperty(GLTFFileLoader.prototype, "loaderState", {
  105900. /**
  105901. * The loader state or null if not active.
  105902. */
  105903. get: function () {
  105904. return this._loader ? this._loader.state : null;
  105905. },
  105906. enumerable: true,
  105907. configurable: true
  105908. });
  105909. /**
  105910. * Disposes the loader, releases resources during load, and cancels any outstanding requests.
  105911. */
  105912. GLTFFileLoader.prototype.dispose = function () {
  105913. if (this._loader) {
  105914. this._loader.dispose();
  105915. this._loader = null;
  105916. }
  105917. this.onMeshLoadedObservable.clear();
  105918. this.onTextureLoadedObservable.clear();
  105919. this.onMaterialLoadedObservable.clear();
  105920. this.onDisposeObservable.notifyObservers(this);
  105921. this.onDisposeObservable.clear();
  105922. };
  105923. GLTFFileLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  105924. var _this = this;
  105925. return Promise.resolve().then(function () {
  105926. var loaderData = _this._parse(data);
  105927. _this._loader = _this._getLoader(loaderData);
  105928. return _this._loader.importMeshAsync(meshesNames, scene, loaderData, rootUrl, onProgress);
  105929. });
  105930. };
  105931. GLTFFileLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  105932. var _this = this;
  105933. return Promise.resolve().then(function () {
  105934. var loaderData = _this._parse(data);
  105935. _this._loader = _this._getLoader(loaderData);
  105936. return _this._loader.loadAsync(scene, loaderData, rootUrl, onProgress);
  105937. });
  105938. };
  105939. GLTFFileLoader.prototype.loadAssetContainerAsync = function (scene, data, rootUrl, onProgress) {
  105940. var _this = this;
  105941. return Promise.resolve().then(function () {
  105942. var loaderData = _this._parse(data);
  105943. _this._loader = _this._getLoader(loaderData);
  105944. return _this._loader.importMeshAsync(null, scene, loaderData, rootUrl, onProgress).then(function (result) {
  105945. var container = new BABYLON.AssetContainer(scene);
  105946. Array.prototype.push.apply(container.meshes, result.meshes);
  105947. Array.prototype.push.apply(container.particleSystems, result.particleSystems);
  105948. Array.prototype.push.apply(container.skeletons, result.skeletons);
  105949. container.removeAllFromScene();
  105950. return container;
  105951. });
  105952. });
  105953. };
  105954. GLTFFileLoader.prototype.canDirectLoad = function (data) {
  105955. return ((data.indexOf("scene") !== -1) && (data.indexOf("node") !== -1));
  105956. };
  105957. GLTFFileLoader.prototype.createPlugin = function () {
  105958. return new GLTFFileLoader();
  105959. };
  105960. GLTFFileLoader.prototype._parse = function (data) {
  105961. var parsedData;
  105962. if (data instanceof ArrayBuffer) {
  105963. parsedData = GLTFFileLoader._parseBinary(data);
  105964. }
  105965. else {
  105966. parsedData = {
  105967. json: JSON.parse(data),
  105968. bin: null
  105969. };
  105970. }
  105971. this.onParsedObservable.notifyObservers(parsedData);
  105972. this.onParsedObservable.clear();
  105973. return parsedData;
  105974. };
  105975. GLTFFileLoader.prototype._getLoader = function (loaderData) {
  105976. var _this = this;
  105977. var loaderVersion = { major: 2, minor: 0 };
  105978. var asset = loaderData.json.asset || {};
  105979. var version = GLTFFileLoader._parseVersion(asset.version);
  105980. if (!version) {
  105981. throw new Error("Invalid version: " + asset.version);
  105982. }
  105983. if (asset.minVersion !== undefined) {
  105984. var minVersion = GLTFFileLoader._parseVersion(asset.minVersion);
  105985. if (!minVersion) {
  105986. throw new Error("Invalid minimum version: " + asset.minVersion);
  105987. }
  105988. if (GLTFFileLoader._compareVersion(minVersion, loaderVersion) > 0) {
  105989. throw new Error("Incompatible minimum version: " + asset.minVersion);
  105990. }
  105991. }
  105992. var createLoaders = {
  105993. 1: GLTFFileLoader.CreateGLTFLoaderV1,
  105994. 2: GLTFFileLoader.CreateGLTFLoaderV2
  105995. };
  105996. var createLoader = createLoaders[version.major];
  105997. if (!createLoader) {
  105998. throw new Error("Unsupported version: " + asset.version);
  105999. }
  106000. var loader = createLoader();
  106001. loader.coordinateSystemMode = this.coordinateSystemMode;
  106002. loader.animationStartMode = this.animationStartMode;
  106003. loader.compileMaterials = this.compileMaterials;
  106004. loader.useClipPlane = this.useClipPlane;
  106005. loader.compileShadowGenerators = this.compileShadowGenerators;
  106006. loader.onMeshLoadedObservable.add(function (mesh) { return _this.onMeshLoadedObservable.notifyObservers(mesh); });
  106007. loader.onTextureLoadedObservable.add(function (texture) { return _this.onTextureLoadedObservable.notifyObservers(texture); });
  106008. loader.onMaterialLoadedObservable.add(function (material) { return _this.onMaterialLoadedObservable.notifyObservers(material); });
  106009. loader.onExtensionLoadedObservable.add(function (extension) { return _this.onExtensionLoadedObservable.notifyObservers(extension); });
  106010. loader.onCompleteObservable.add(function () {
  106011. _this.onMeshLoadedObservable.clear();
  106012. _this.onTextureLoadedObservable.clear();
  106013. _this.onMaterialLoadedObservable.clear();
  106014. _this.onCompleteObservable.notifyObservers(_this);
  106015. _this.onCompleteObservable.clear();
  106016. });
  106017. return loader;
  106018. };
  106019. GLTFFileLoader._parseBinary = function (data) {
  106020. var Binary = {
  106021. Magic: 0x46546C67
  106022. };
  106023. var binaryReader = new BinaryReader(data);
  106024. var magic = binaryReader.readUint32();
  106025. if (magic !== Binary.Magic) {
  106026. throw new Error("Unexpected magic: " + magic);
  106027. }
  106028. var version = binaryReader.readUint32();
  106029. switch (version) {
  106030. case 1: return GLTFFileLoader._parseV1(binaryReader);
  106031. case 2: return GLTFFileLoader._parseV2(binaryReader);
  106032. }
  106033. throw new Error("Unsupported version: " + version);
  106034. };
  106035. GLTFFileLoader._parseV1 = function (binaryReader) {
  106036. var ContentFormat = {
  106037. JSON: 0
  106038. };
  106039. var length = binaryReader.readUint32();
  106040. if (length != binaryReader.getLength()) {
  106041. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  106042. }
  106043. var contentLength = binaryReader.readUint32();
  106044. var contentFormat = binaryReader.readUint32();
  106045. var content;
  106046. switch (contentFormat) {
  106047. case ContentFormat.JSON: {
  106048. content = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(contentLength)));
  106049. break;
  106050. }
  106051. default: {
  106052. throw new Error("Unexpected content format: " + contentFormat);
  106053. }
  106054. }
  106055. var bytesRemaining = binaryReader.getLength() - binaryReader.getPosition();
  106056. var body = binaryReader.readUint8Array(bytesRemaining);
  106057. return {
  106058. json: content,
  106059. bin: body
  106060. };
  106061. };
  106062. GLTFFileLoader._parseV2 = function (binaryReader) {
  106063. var ChunkFormat = {
  106064. JSON: 0x4E4F534A,
  106065. BIN: 0x004E4942
  106066. };
  106067. var length = binaryReader.readUint32();
  106068. if (length !== binaryReader.getLength()) {
  106069. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  106070. }
  106071. // JSON chunk
  106072. var chunkLength = binaryReader.readUint32();
  106073. var chunkFormat = binaryReader.readUint32();
  106074. if (chunkFormat !== ChunkFormat.JSON) {
  106075. throw new Error("First chunk format is not JSON");
  106076. }
  106077. var json = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(chunkLength)));
  106078. // Look for BIN chunk
  106079. var bin = null;
  106080. while (binaryReader.getPosition() < binaryReader.getLength()) {
  106081. var chunkLength_1 = binaryReader.readUint32();
  106082. var chunkFormat_1 = binaryReader.readUint32();
  106083. switch (chunkFormat_1) {
  106084. case ChunkFormat.JSON: {
  106085. throw new Error("Unexpected JSON chunk");
  106086. }
  106087. case ChunkFormat.BIN: {
  106088. bin = binaryReader.readUint8Array(chunkLength_1);
  106089. break;
  106090. }
  106091. default: {
  106092. // ignore unrecognized chunkFormat
  106093. binaryReader.skipBytes(chunkLength_1);
  106094. break;
  106095. }
  106096. }
  106097. }
  106098. return {
  106099. json: json,
  106100. bin: bin
  106101. };
  106102. };
  106103. GLTFFileLoader._parseVersion = function (version) {
  106104. if (version === "1.0" || version === "1.0.1") {
  106105. return {
  106106. major: 1,
  106107. minor: 0
  106108. };
  106109. }
  106110. var match = (version + "").match(/^(\d+)\.(\d+)/);
  106111. if (!match) {
  106112. return null;
  106113. }
  106114. return {
  106115. major: parseInt(match[1]),
  106116. minor: parseInt(match[2])
  106117. };
  106118. };
  106119. GLTFFileLoader._compareVersion = function (a, b) {
  106120. if (a.major > b.major)
  106121. return 1;
  106122. if (a.major < b.major)
  106123. return -1;
  106124. if (a.minor > b.minor)
  106125. return 1;
  106126. if (a.minor < b.minor)
  106127. return -1;
  106128. return 0;
  106129. };
  106130. GLTFFileLoader._decodeBufferToText = function (buffer) {
  106131. var result = "";
  106132. var length = buffer.byteLength;
  106133. for (var i = 0; i < length; i++) {
  106134. result += String.fromCharCode(buffer[i]);
  106135. }
  106136. return result;
  106137. };
  106138. // #endregion
  106139. // #region V1 options
  106140. GLTFFileLoader.IncrementalLoading = true;
  106141. GLTFFileLoader.HomogeneousCoordinates = false;
  106142. return GLTFFileLoader;
  106143. }());
  106144. BABYLON.GLTFFileLoader = GLTFFileLoader;
  106145. var BinaryReader = /** @class */ (function () {
  106146. function BinaryReader(arrayBuffer) {
  106147. this._arrayBuffer = arrayBuffer;
  106148. this._dataView = new DataView(arrayBuffer);
  106149. this._byteOffset = 0;
  106150. }
  106151. BinaryReader.prototype.getPosition = function () {
  106152. return this._byteOffset;
  106153. };
  106154. BinaryReader.prototype.getLength = function () {
  106155. return this._arrayBuffer.byteLength;
  106156. };
  106157. BinaryReader.prototype.readUint32 = function () {
  106158. var value = this._dataView.getUint32(this._byteOffset, true);
  106159. this._byteOffset += 4;
  106160. return value;
  106161. };
  106162. BinaryReader.prototype.readUint8Array = function (length) {
  106163. var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length);
  106164. this._byteOffset += length;
  106165. return value;
  106166. };
  106167. BinaryReader.prototype.skipBytes = function (length) {
  106168. this._byteOffset += length;
  106169. };
  106170. return BinaryReader;
  106171. }());
  106172. if (BABYLON.SceneLoader) {
  106173. BABYLON.SceneLoader.RegisterPlugin(new GLTFFileLoader());
  106174. }
  106175. })(BABYLON || (BABYLON = {}));
  106176. //# sourceMappingURL=babylon.glTFFileLoader.js.map
  106177. var BABYLON;
  106178. (function (BABYLON) {
  106179. var GLTF1;
  106180. (function (GLTF1) {
  106181. /**
  106182. * Enums
  106183. */
  106184. var EComponentType;
  106185. (function (EComponentType) {
  106186. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  106187. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  106188. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  106189. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  106190. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  106191. })(EComponentType = GLTF1.EComponentType || (GLTF1.EComponentType = {}));
  106192. var EShaderType;
  106193. (function (EShaderType) {
  106194. EShaderType[EShaderType["FRAGMENT"] = 35632] = "FRAGMENT";
  106195. EShaderType[EShaderType["VERTEX"] = 35633] = "VERTEX";
  106196. })(EShaderType = GLTF1.EShaderType || (GLTF1.EShaderType = {}));
  106197. var EParameterType;
  106198. (function (EParameterType) {
  106199. EParameterType[EParameterType["BYTE"] = 5120] = "BYTE";
  106200. EParameterType[EParameterType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  106201. EParameterType[EParameterType["SHORT"] = 5122] = "SHORT";
  106202. EParameterType[EParameterType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  106203. EParameterType[EParameterType["INT"] = 5124] = "INT";
  106204. EParameterType[EParameterType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  106205. EParameterType[EParameterType["FLOAT"] = 5126] = "FLOAT";
  106206. EParameterType[EParameterType["FLOAT_VEC2"] = 35664] = "FLOAT_VEC2";
  106207. EParameterType[EParameterType["FLOAT_VEC3"] = 35665] = "FLOAT_VEC3";
  106208. EParameterType[EParameterType["FLOAT_VEC4"] = 35666] = "FLOAT_VEC4";
  106209. EParameterType[EParameterType["INT_VEC2"] = 35667] = "INT_VEC2";
  106210. EParameterType[EParameterType["INT_VEC3"] = 35668] = "INT_VEC3";
  106211. EParameterType[EParameterType["INT_VEC4"] = 35669] = "INT_VEC4";
  106212. EParameterType[EParameterType["BOOL"] = 35670] = "BOOL";
  106213. EParameterType[EParameterType["BOOL_VEC2"] = 35671] = "BOOL_VEC2";
  106214. EParameterType[EParameterType["BOOL_VEC3"] = 35672] = "BOOL_VEC3";
  106215. EParameterType[EParameterType["BOOL_VEC4"] = 35673] = "BOOL_VEC4";
  106216. EParameterType[EParameterType["FLOAT_MAT2"] = 35674] = "FLOAT_MAT2";
  106217. EParameterType[EParameterType["FLOAT_MAT3"] = 35675] = "FLOAT_MAT3";
  106218. EParameterType[EParameterType["FLOAT_MAT4"] = 35676] = "FLOAT_MAT4";
  106219. EParameterType[EParameterType["SAMPLER_2D"] = 35678] = "SAMPLER_2D";
  106220. })(EParameterType = GLTF1.EParameterType || (GLTF1.EParameterType = {}));
  106221. var ETextureWrapMode;
  106222. (function (ETextureWrapMode) {
  106223. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  106224. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  106225. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  106226. })(ETextureWrapMode = GLTF1.ETextureWrapMode || (GLTF1.ETextureWrapMode = {}));
  106227. var ETextureFilterType;
  106228. (function (ETextureFilterType) {
  106229. ETextureFilterType[ETextureFilterType["NEAREST"] = 9728] = "NEAREST";
  106230. ETextureFilterType[ETextureFilterType["LINEAR"] = 9728] = "LINEAR";
  106231. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  106232. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  106233. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  106234. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  106235. })(ETextureFilterType = GLTF1.ETextureFilterType || (GLTF1.ETextureFilterType = {}));
  106236. var ETextureFormat;
  106237. (function (ETextureFormat) {
  106238. ETextureFormat[ETextureFormat["ALPHA"] = 6406] = "ALPHA";
  106239. ETextureFormat[ETextureFormat["RGB"] = 6407] = "RGB";
  106240. ETextureFormat[ETextureFormat["RGBA"] = 6408] = "RGBA";
  106241. ETextureFormat[ETextureFormat["LUMINANCE"] = 6409] = "LUMINANCE";
  106242. ETextureFormat[ETextureFormat["LUMINANCE_ALPHA"] = 6410] = "LUMINANCE_ALPHA";
  106243. })(ETextureFormat = GLTF1.ETextureFormat || (GLTF1.ETextureFormat = {}));
  106244. var ECullingType;
  106245. (function (ECullingType) {
  106246. ECullingType[ECullingType["FRONT"] = 1028] = "FRONT";
  106247. ECullingType[ECullingType["BACK"] = 1029] = "BACK";
  106248. ECullingType[ECullingType["FRONT_AND_BACK"] = 1032] = "FRONT_AND_BACK";
  106249. })(ECullingType = GLTF1.ECullingType || (GLTF1.ECullingType = {}));
  106250. var EBlendingFunction;
  106251. (function (EBlendingFunction) {
  106252. EBlendingFunction[EBlendingFunction["ZERO"] = 0] = "ZERO";
  106253. EBlendingFunction[EBlendingFunction["ONE"] = 1] = "ONE";
  106254. EBlendingFunction[EBlendingFunction["SRC_COLOR"] = 768] = "SRC_COLOR";
  106255. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_COLOR"] = 769] = "ONE_MINUS_SRC_COLOR";
  106256. EBlendingFunction[EBlendingFunction["DST_COLOR"] = 774] = "DST_COLOR";
  106257. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_COLOR"] = 775] = "ONE_MINUS_DST_COLOR";
  106258. EBlendingFunction[EBlendingFunction["SRC_ALPHA"] = 770] = "SRC_ALPHA";
  106259. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_ALPHA"] = 771] = "ONE_MINUS_SRC_ALPHA";
  106260. EBlendingFunction[EBlendingFunction["DST_ALPHA"] = 772] = "DST_ALPHA";
  106261. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_ALPHA"] = 773] = "ONE_MINUS_DST_ALPHA";
  106262. EBlendingFunction[EBlendingFunction["CONSTANT_COLOR"] = 32769] = "CONSTANT_COLOR";
  106263. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_COLOR"] = 32770] = "ONE_MINUS_CONSTANT_COLOR";
  106264. EBlendingFunction[EBlendingFunction["CONSTANT_ALPHA"] = 32771] = "CONSTANT_ALPHA";
  106265. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_ALPHA"] = 32772] = "ONE_MINUS_CONSTANT_ALPHA";
  106266. EBlendingFunction[EBlendingFunction["SRC_ALPHA_SATURATE"] = 776] = "SRC_ALPHA_SATURATE";
  106267. })(EBlendingFunction = GLTF1.EBlendingFunction || (GLTF1.EBlendingFunction = {}));
  106268. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  106269. })(BABYLON || (BABYLON = {}));
  106270. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  106271. var BABYLON;
  106272. (function (BABYLON) {
  106273. var GLTF1;
  106274. (function (GLTF1) {
  106275. /**
  106276. * Tokenizer. Used for shaders compatibility
  106277. * Automatically map world, view, projection, worldViewProjection, attributes and so on
  106278. */
  106279. var ETokenType;
  106280. (function (ETokenType) {
  106281. ETokenType[ETokenType["IDENTIFIER"] = 1] = "IDENTIFIER";
  106282. ETokenType[ETokenType["UNKNOWN"] = 2] = "UNKNOWN";
  106283. ETokenType[ETokenType["END_OF_INPUT"] = 3] = "END_OF_INPUT";
  106284. })(ETokenType || (ETokenType = {}));
  106285. var Tokenizer = /** @class */ (function () {
  106286. function Tokenizer(toParse) {
  106287. this._pos = 0;
  106288. this.isLetterOrDigitPattern = /^[a-zA-Z0-9]+$/;
  106289. this._toParse = toParse;
  106290. this._maxPos = toParse.length;
  106291. }
  106292. Tokenizer.prototype.getNextToken = function () {
  106293. if (this.isEnd())
  106294. return ETokenType.END_OF_INPUT;
  106295. this.currentString = this.read();
  106296. this.currentToken = ETokenType.UNKNOWN;
  106297. if (this.currentString === "_" || this.isLetterOrDigitPattern.test(this.currentString)) {
  106298. this.currentToken = ETokenType.IDENTIFIER;
  106299. this.currentIdentifier = this.currentString;
  106300. while (!this.isEnd() && (this.isLetterOrDigitPattern.test(this.currentString = this.peek()) || this.currentString === "_")) {
  106301. this.currentIdentifier += this.currentString;
  106302. this.forward();
  106303. }
  106304. }
  106305. return this.currentToken;
  106306. };
  106307. Tokenizer.prototype.peek = function () {
  106308. return this._toParse[this._pos];
  106309. };
  106310. Tokenizer.prototype.read = function () {
  106311. return this._toParse[this._pos++];
  106312. };
  106313. Tokenizer.prototype.forward = function () {
  106314. this._pos++;
  106315. };
  106316. Tokenizer.prototype.isEnd = function () {
  106317. return this._pos >= this._maxPos;
  106318. };
  106319. return Tokenizer;
  106320. }());
  106321. /**
  106322. * Values
  106323. */
  106324. var glTFTransforms = ["MODEL", "VIEW", "PROJECTION", "MODELVIEW", "MODELVIEWPROJECTION", "JOINTMATRIX"];
  106325. var babylonTransforms = ["world", "view", "projection", "worldView", "worldViewProjection", "mBones"];
  106326. var glTFAnimationPaths = ["translation", "rotation", "scale"];
  106327. var babylonAnimationPaths = ["position", "rotationQuaternion", "scaling"];
  106328. /**
  106329. * Parse
  106330. */
  106331. var parseBuffers = function (parsedBuffers, gltfRuntime) {
  106332. for (var buf in parsedBuffers) {
  106333. var parsedBuffer = parsedBuffers[buf];
  106334. gltfRuntime.buffers[buf] = parsedBuffer;
  106335. gltfRuntime.buffersCount++;
  106336. }
  106337. };
  106338. var parseShaders = function (parsedShaders, gltfRuntime) {
  106339. for (var sha in parsedShaders) {
  106340. var parsedShader = parsedShaders[sha];
  106341. gltfRuntime.shaders[sha] = parsedShader;
  106342. gltfRuntime.shaderscount++;
  106343. }
  106344. };
  106345. var parseObject = function (parsedObjects, runtimeProperty, gltfRuntime) {
  106346. for (var object in parsedObjects) {
  106347. var parsedObject = parsedObjects[object];
  106348. gltfRuntime[runtimeProperty][object] = parsedObject;
  106349. }
  106350. };
  106351. /**
  106352. * Utils
  106353. */
  106354. var normalizeUVs = function (buffer) {
  106355. if (!buffer) {
  106356. return;
  106357. }
  106358. for (var i = 0; i < buffer.length / 2; i++) {
  106359. buffer[i * 2 + 1] = 1.0 - buffer[i * 2 + 1];
  106360. }
  106361. };
  106362. var getAttribute = function (attributeParameter) {
  106363. if (attributeParameter.semantic === "NORMAL") {
  106364. return "normal";
  106365. }
  106366. else if (attributeParameter.semantic === "POSITION") {
  106367. return "position";
  106368. }
  106369. else if (attributeParameter.semantic === "JOINT") {
  106370. return "matricesIndices";
  106371. }
  106372. else if (attributeParameter.semantic === "WEIGHT") {
  106373. return "matricesWeights";
  106374. }
  106375. else if (attributeParameter.semantic === "COLOR") {
  106376. return "color";
  106377. }
  106378. else if (attributeParameter.semantic && attributeParameter.semantic.indexOf("TEXCOORD_") !== -1) {
  106379. var channel = Number(attributeParameter.semantic.split("_")[1]);
  106380. return "uv" + (channel === 0 ? "" : channel + 1);
  106381. }
  106382. return null;
  106383. };
  106384. /**
  106385. * Loads and creates animations
  106386. */
  106387. var loadAnimations = function (gltfRuntime) {
  106388. for (var anim in gltfRuntime.animations) {
  106389. var animation = gltfRuntime.animations[anim];
  106390. if (!animation.channels || !animation.samplers) {
  106391. continue;
  106392. }
  106393. var lastAnimation = null;
  106394. for (var i = 0; i < animation.channels.length; i++) {
  106395. // Get parameters and load buffers
  106396. var channel = animation.channels[i];
  106397. var sampler = animation.samplers[channel.sampler];
  106398. if (!sampler) {
  106399. continue;
  106400. }
  106401. var inputData = null;
  106402. var outputData = null;
  106403. if (animation.parameters) {
  106404. inputData = animation.parameters[sampler.input];
  106405. outputData = animation.parameters[sampler.output];
  106406. }
  106407. else {
  106408. inputData = sampler.input;
  106409. outputData = sampler.output;
  106410. }
  106411. var bufferInput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[inputData]);
  106412. var bufferOutput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[outputData]);
  106413. var targetID = channel.target.id;
  106414. var targetNode = gltfRuntime.scene.getNodeByID(targetID);
  106415. if (targetNode === null) {
  106416. targetNode = gltfRuntime.scene.getNodeByName(targetID);
  106417. }
  106418. if (targetNode === null) {
  106419. BABYLON.Tools.Warn("Creating animation named " + anim + ". But cannot find node named " + targetID + " to attach to");
  106420. continue;
  106421. }
  106422. var isBone = targetNode instanceof BABYLON.Bone;
  106423. // Get target path (position, rotation or scaling)
  106424. var targetPath = channel.target.path;
  106425. var targetPathIndex = glTFAnimationPaths.indexOf(targetPath);
  106426. if (targetPathIndex !== -1) {
  106427. targetPath = babylonAnimationPaths[targetPathIndex];
  106428. }
  106429. // Determine animation type
  106430. var animationType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  106431. if (!isBone) {
  106432. if (targetPath === "rotationQuaternion") {
  106433. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  106434. targetNode.rotationQuaternion = new BABYLON.Quaternion();
  106435. }
  106436. else {
  106437. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  106438. }
  106439. }
  106440. // Create animation and key frames
  106441. var babylonAnimation = null;
  106442. var keys = [];
  106443. var arrayOffset = 0;
  106444. var modifyKey = false;
  106445. if (isBone && lastAnimation && lastAnimation.getKeys().length === bufferInput.length) {
  106446. babylonAnimation = lastAnimation;
  106447. modifyKey = true;
  106448. }
  106449. if (!modifyKey) {
  106450. babylonAnimation = new BABYLON.Animation(anim, isBone ? "_matrix" : targetPath, 1, animationType, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  106451. }
  106452. // For each frame
  106453. for (var j = 0; j < bufferInput.length; j++) {
  106454. var value = null;
  106455. if (targetPath === "rotationQuaternion") {
  106456. value = BABYLON.Quaternion.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2], bufferOutput[arrayOffset + 3]]);
  106457. arrayOffset += 4;
  106458. }
  106459. else {
  106460. value = BABYLON.Vector3.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2]]);
  106461. arrayOffset += 3;
  106462. }
  106463. if (isBone) {
  106464. var bone = targetNode;
  106465. var translation = BABYLON.Vector3.Zero();
  106466. var rotationQuaternion = new BABYLON.Quaternion();
  106467. var scaling = BABYLON.Vector3.Zero();
  106468. // Warning on decompose
  106469. var mat = bone.getBaseMatrix();
  106470. if (modifyKey && lastAnimation) {
  106471. mat = lastAnimation.getKeys()[j].value;
  106472. }
  106473. mat.decompose(scaling, rotationQuaternion, translation);
  106474. if (targetPath === "position") {
  106475. translation = value;
  106476. }
  106477. else if (targetPath === "rotationQuaternion") {
  106478. rotationQuaternion = value;
  106479. }
  106480. else {
  106481. scaling = value;
  106482. }
  106483. value = BABYLON.Matrix.Compose(scaling, rotationQuaternion, translation);
  106484. }
  106485. if (!modifyKey) {
  106486. keys.push({
  106487. frame: bufferInput[j],
  106488. value: value
  106489. });
  106490. }
  106491. else if (lastAnimation) {
  106492. lastAnimation.getKeys()[j].value = value;
  106493. }
  106494. }
  106495. // Finish
  106496. if (!modifyKey && babylonAnimation) {
  106497. babylonAnimation.setKeys(keys);
  106498. targetNode.animations.push(babylonAnimation);
  106499. }
  106500. lastAnimation = babylonAnimation;
  106501. gltfRuntime.scene.stopAnimation(targetNode);
  106502. gltfRuntime.scene.beginAnimation(targetNode, 0, bufferInput[bufferInput.length - 1], true, 1.0);
  106503. }
  106504. }
  106505. };
  106506. /**
  106507. * Returns the bones transformation matrix
  106508. */
  106509. var configureBoneTransformation = function (node) {
  106510. var mat = null;
  106511. if (node.translation || node.rotation || node.scale) {
  106512. var scale = BABYLON.Vector3.FromArray(node.scale || [1, 1, 1]);
  106513. var rotation = BABYLON.Quaternion.FromArray(node.rotation || [0, 0, 0, 1]);
  106514. var position = BABYLON.Vector3.FromArray(node.translation || [0, 0, 0]);
  106515. mat = BABYLON.Matrix.Compose(scale, rotation, position);
  106516. }
  106517. else {
  106518. mat = BABYLON.Matrix.FromArray(node.matrix);
  106519. }
  106520. return mat;
  106521. };
  106522. /**
  106523. * Returns the parent bone
  106524. */
  106525. var getParentBone = function (gltfRuntime, skins, jointName, newSkeleton) {
  106526. // Try to find
  106527. for (var i = 0; i < newSkeleton.bones.length; i++) {
  106528. if (newSkeleton.bones[i].name === jointName) {
  106529. return newSkeleton.bones[i];
  106530. }
  106531. }
  106532. // Not found, search in gltf nodes
  106533. var nodes = gltfRuntime.nodes;
  106534. for (var nde in nodes) {
  106535. var node = nodes[nde];
  106536. if (!node.jointName) {
  106537. continue;
  106538. }
  106539. var children = node.children;
  106540. for (var i = 0; i < children.length; i++) {
  106541. var child = gltfRuntime.nodes[children[i]];
  106542. if (!child.jointName) {
  106543. continue;
  106544. }
  106545. if (child.jointName === jointName) {
  106546. var mat = configureBoneTransformation(node);
  106547. var bone = new BABYLON.Bone(node.name || "", newSkeleton, getParentBone(gltfRuntime, skins, node.jointName, newSkeleton), mat);
  106548. bone.id = nde;
  106549. return bone;
  106550. }
  106551. }
  106552. }
  106553. return null;
  106554. };
  106555. /**
  106556. * Returns the appropriate root node
  106557. */
  106558. var getNodeToRoot = function (nodesToRoot, id) {
  106559. for (var i = 0; i < nodesToRoot.length; i++) {
  106560. var nodeToRoot = nodesToRoot[i];
  106561. for (var j = 0; j < nodeToRoot.node.children.length; j++) {
  106562. var child = nodeToRoot.node.children[j];
  106563. if (child === id) {
  106564. return nodeToRoot.bone;
  106565. }
  106566. }
  106567. }
  106568. return null;
  106569. };
  106570. /**
  106571. * Returns the node with the joint name
  106572. */
  106573. var getJointNode = function (gltfRuntime, jointName) {
  106574. var nodes = gltfRuntime.nodes;
  106575. var node = nodes[jointName];
  106576. if (node) {
  106577. return {
  106578. node: node,
  106579. id: jointName
  106580. };
  106581. }
  106582. for (var nde in nodes) {
  106583. node = nodes[nde];
  106584. if (node.jointName === jointName) {
  106585. return {
  106586. node: node,
  106587. id: nde
  106588. };
  106589. }
  106590. }
  106591. return null;
  106592. };
  106593. /**
  106594. * Checks if a nodes is in joints
  106595. */
  106596. var nodeIsInJoints = function (skins, id) {
  106597. for (var i = 0; i < skins.jointNames.length; i++) {
  106598. if (skins.jointNames[i] === id) {
  106599. return true;
  106600. }
  106601. }
  106602. return false;
  106603. };
  106604. /**
  106605. * Fills the nodes to root for bones and builds hierarchy
  106606. */
  106607. var getNodesToRoot = function (gltfRuntime, newSkeleton, skins, nodesToRoot) {
  106608. // Creates nodes for root
  106609. for (var nde in gltfRuntime.nodes) {
  106610. var node = gltfRuntime.nodes[nde];
  106611. var id = nde;
  106612. if (!node.jointName || nodeIsInJoints(skins, node.jointName)) {
  106613. continue;
  106614. }
  106615. // Create node to root bone
  106616. var mat = configureBoneTransformation(node);
  106617. var bone = new BABYLON.Bone(node.name || "", newSkeleton, null, mat);
  106618. bone.id = id;
  106619. nodesToRoot.push({ bone: bone, node: node, id: id });
  106620. }
  106621. // Parenting
  106622. for (var i = 0; i < nodesToRoot.length; i++) {
  106623. var nodeToRoot = nodesToRoot[i];
  106624. var children = nodeToRoot.node.children;
  106625. for (var j = 0; j < children.length; j++) {
  106626. var child = null;
  106627. for (var k = 0; k < nodesToRoot.length; k++) {
  106628. if (nodesToRoot[k].id === children[j]) {
  106629. child = nodesToRoot[k];
  106630. break;
  106631. }
  106632. }
  106633. if (child) {
  106634. child.bone._parent = nodeToRoot.bone;
  106635. nodeToRoot.bone.children.push(child.bone);
  106636. }
  106637. }
  106638. }
  106639. };
  106640. /**
  106641. * Imports a skeleton
  106642. */
  106643. var importSkeleton = function (gltfRuntime, skins, mesh, newSkeleton, id) {
  106644. if (!newSkeleton) {
  106645. newSkeleton = new BABYLON.Skeleton(skins.name || "", "", gltfRuntime.scene);
  106646. }
  106647. if (!skins.babylonSkeleton) {
  106648. return newSkeleton;
  106649. }
  106650. // Find the root bones
  106651. var nodesToRoot = [];
  106652. var nodesToRootToAdd = [];
  106653. getNodesToRoot(gltfRuntime, newSkeleton, skins, nodesToRoot);
  106654. newSkeleton.bones = [];
  106655. // Joints
  106656. for (var i = 0; i < skins.jointNames.length; i++) {
  106657. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  106658. if (!jointNode) {
  106659. continue;
  106660. }
  106661. var node = jointNode.node;
  106662. if (!node) {
  106663. BABYLON.Tools.Warn("Joint named " + skins.jointNames[i] + " does not exist");
  106664. continue;
  106665. }
  106666. var id = jointNode.id;
  106667. // Optimize, if the bone already exists...
  106668. var existingBone = gltfRuntime.scene.getBoneByID(id);
  106669. if (existingBone) {
  106670. newSkeleton.bones.push(existingBone);
  106671. continue;
  106672. }
  106673. // Search for parent bone
  106674. var foundBone = false;
  106675. var parentBone = null;
  106676. for (var j = 0; j < i; j++) {
  106677. var jointNode_1 = getJointNode(gltfRuntime, skins.jointNames[j]);
  106678. if (!jointNode_1) {
  106679. continue;
  106680. }
  106681. var joint = jointNode_1.node;
  106682. if (!joint) {
  106683. BABYLON.Tools.Warn("Joint named " + skins.jointNames[j] + " does not exist when looking for parent");
  106684. continue;
  106685. }
  106686. var children = joint.children;
  106687. if (!children) {
  106688. continue;
  106689. }
  106690. foundBone = false;
  106691. for (var k = 0; k < children.length; k++) {
  106692. if (children[k] === id) {
  106693. parentBone = getParentBone(gltfRuntime, skins, skins.jointNames[j], newSkeleton);
  106694. foundBone = true;
  106695. break;
  106696. }
  106697. }
  106698. if (foundBone) {
  106699. break;
  106700. }
  106701. }
  106702. // Create bone
  106703. var mat = configureBoneTransformation(node);
  106704. if (!parentBone && nodesToRoot.length > 0) {
  106705. parentBone = getNodeToRoot(nodesToRoot, id);
  106706. if (parentBone) {
  106707. if (nodesToRootToAdd.indexOf(parentBone) === -1) {
  106708. nodesToRootToAdd.push(parentBone);
  106709. }
  106710. }
  106711. }
  106712. var bone = new BABYLON.Bone(node.jointName || "", newSkeleton, parentBone, mat);
  106713. bone.id = id;
  106714. }
  106715. // Polish
  106716. var bones = newSkeleton.bones;
  106717. newSkeleton.bones = [];
  106718. for (var i = 0; i < skins.jointNames.length; i++) {
  106719. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  106720. if (!jointNode) {
  106721. continue;
  106722. }
  106723. for (var j = 0; j < bones.length; j++) {
  106724. if (bones[j].id === jointNode.id) {
  106725. newSkeleton.bones.push(bones[j]);
  106726. break;
  106727. }
  106728. }
  106729. }
  106730. newSkeleton.prepare();
  106731. // Finish
  106732. for (var i = 0; i < nodesToRootToAdd.length; i++) {
  106733. newSkeleton.bones.push(nodesToRootToAdd[i]);
  106734. }
  106735. return newSkeleton;
  106736. };
  106737. /**
  106738. * Imports a mesh and its geometries
  106739. */
  106740. var importMesh = function (gltfRuntime, node, meshes, id, newMesh) {
  106741. if (!newMesh) {
  106742. newMesh = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  106743. newMesh.id = id;
  106744. }
  106745. if (!node.babylonNode) {
  106746. return newMesh;
  106747. }
  106748. var subMaterials = [];
  106749. var vertexData = null;
  106750. var verticesStarts = new Array();
  106751. var verticesCounts = new Array();
  106752. var indexStarts = new Array();
  106753. var indexCounts = new Array();
  106754. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  106755. var meshID = meshes[meshIndex];
  106756. var mesh = gltfRuntime.meshes[meshID];
  106757. if (!mesh) {
  106758. continue;
  106759. }
  106760. // Positions, normals and UVs
  106761. for (var i = 0; i < mesh.primitives.length; i++) {
  106762. // Temporary vertex data
  106763. var tempVertexData = new BABYLON.VertexData();
  106764. var primitive = mesh.primitives[i];
  106765. if (primitive.mode !== 4) {
  106766. // continue;
  106767. }
  106768. var attributes = primitive.attributes;
  106769. var accessor = null;
  106770. var buffer = null;
  106771. // Set positions, normal and uvs
  106772. for (var semantic in attributes) {
  106773. // Link accessor and buffer view
  106774. accessor = gltfRuntime.accessors[attributes[semantic]];
  106775. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  106776. if (semantic === "NORMAL") {
  106777. tempVertexData.normals = new Float32Array(buffer.length);
  106778. tempVertexData.normals.set(buffer);
  106779. }
  106780. else if (semantic === "POSITION") {
  106781. if (BABYLON.GLTFFileLoader.HomogeneousCoordinates) {
  106782. tempVertexData.positions = new Float32Array(buffer.length - buffer.length / 4);
  106783. for (var j = 0; j < buffer.length; j += 4) {
  106784. tempVertexData.positions[j] = buffer[j];
  106785. tempVertexData.positions[j + 1] = buffer[j + 1];
  106786. tempVertexData.positions[j + 2] = buffer[j + 2];
  106787. }
  106788. }
  106789. else {
  106790. tempVertexData.positions = new Float32Array(buffer.length);
  106791. tempVertexData.positions.set(buffer);
  106792. }
  106793. verticesCounts.push(tempVertexData.positions.length);
  106794. }
  106795. else if (semantic.indexOf("TEXCOORD_") !== -1) {
  106796. var channel = Number(semantic.split("_")[1]);
  106797. var uvKind = BABYLON.VertexBuffer.UVKind + (channel === 0 ? "" : (channel + 1));
  106798. var uvs = new Float32Array(buffer.length);
  106799. uvs.set(buffer);
  106800. normalizeUVs(uvs);
  106801. tempVertexData.set(uvs, uvKind);
  106802. }
  106803. else if (semantic === "JOINT") {
  106804. tempVertexData.matricesIndices = new Float32Array(buffer.length);
  106805. tempVertexData.matricesIndices.set(buffer);
  106806. }
  106807. else if (semantic === "WEIGHT") {
  106808. tempVertexData.matricesWeights = new Float32Array(buffer.length);
  106809. tempVertexData.matricesWeights.set(buffer);
  106810. }
  106811. else if (semantic === "COLOR") {
  106812. tempVertexData.colors = new Float32Array(buffer.length);
  106813. tempVertexData.colors.set(buffer);
  106814. }
  106815. }
  106816. // Indices
  106817. accessor = gltfRuntime.accessors[primitive.indices];
  106818. if (accessor) {
  106819. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  106820. tempVertexData.indices = new Int32Array(buffer.length);
  106821. tempVertexData.indices.set(buffer);
  106822. indexCounts.push(tempVertexData.indices.length);
  106823. }
  106824. else {
  106825. // Set indices on the fly
  106826. var indices = [];
  106827. for (var j = 0; j < tempVertexData.positions.length / 3; j++) {
  106828. indices.push(j);
  106829. }
  106830. tempVertexData.indices = new Int32Array(indices);
  106831. indexCounts.push(tempVertexData.indices.length);
  106832. }
  106833. if (!vertexData) {
  106834. vertexData = tempVertexData;
  106835. }
  106836. else {
  106837. vertexData.merge(tempVertexData);
  106838. }
  106839. // Sub material
  106840. var material_1 = gltfRuntime.scene.getMaterialByID(primitive.material);
  106841. subMaterials.push(material_1 === null ? GLTF1.GLTFUtils.GetDefaultMaterial(gltfRuntime.scene) : material_1);
  106842. // Update vertices start and index start
  106843. verticesStarts.push(verticesStarts.length === 0 ? 0 : verticesStarts[verticesStarts.length - 1] + verticesCounts[verticesCounts.length - 2]);
  106844. indexStarts.push(indexStarts.length === 0 ? 0 : indexStarts[indexStarts.length - 1] + indexCounts[indexCounts.length - 2]);
  106845. }
  106846. }
  106847. var material;
  106848. if (subMaterials.length > 1) {
  106849. material = new BABYLON.MultiMaterial("multimat" + id, gltfRuntime.scene);
  106850. material.subMaterials = subMaterials;
  106851. }
  106852. else {
  106853. material = new BABYLON.StandardMaterial("multimat" + id, gltfRuntime.scene);
  106854. }
  106855. if (subMaterials.length === 1) {
  106856. material = subMaterials[0];
  106857. }
  106858. if (!newMesh.material) {
  106859. newMesh.material = material;
  106860. }
  106861. // Apply geometry
  106862. new BABYLON.Geometry(id, gltfRuntime.scene, vertexData, false, newMesh);
  106863. newMesh.computeWorldMatrix(true);
  106864. // Apply submeshes
  106865. newMesh.subMeshes = [];
  106866. var index = 0;
  106867. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  106868. var meshID = meshes[meshIndex];
  106869. var mesh = gltfRuntime.meshes[meshID];
  106870. if (!mesh) {
  106871. continue;
  106872. }
  106873. for (var i = 0; i < mesh.primitives.length; i++) {
  106874. if (mesh.primitives[i].mode !== 4) {
  106875. //continue;
  106876. }
  106877. BABYLON.SubMesh.AddToMesh(index, verticesStarts[index], verticesCounts[index], indexStarts[index], indexCounts[index], newMesh, newMesh, true);
  106878. index++;
  106879. }
  106880. }
  106881. // Finish
  106882. return newMesh;
  106883. };
  106884. /**
  106885. * Configure node transformation from position, rotation and scaling
  106886. */
  106887. var configureNode = function (newNode, position, rotation, scaling) {
  106888. if (newNode.position) {
  106889. newNode.position = position;
  106890. }
  106891. if (newNode.rotationQuaternion || newNode.rotation) {
  106892. newNode.rotationQuaternion = rotation;
  106893. }
  106894. if (newNode.scaling) {
  106895. newNode.scaling = scaling;
  106896. }
  106897. };
  106898. /**
  106899. * Configures node from transformation matrix
  106900. */
  106901. var configureNodeFromMatrix = function (newNode, node, parent) {
  106902. if (node.matrix) {
  106903. var position = new BABYLON.Vector3(0, 0, 0);
  106904. var rotation = new BABYLON.Quaternion();
  106905. var scaling = new BABYLON.Vector3(0, 0, 0);
  106906. var mat = BABYLON.Matrix.FromArray(node.matrix);
  106907. mat.decompose(scaling, rotation, position);
  106908. configureNode(newNode, position, rotation, scaling);
  106909. }
  106910. else if (node.translation && node.rotation && node.scale) {
  106911. configureNode(newNode, BABYLON.Vector3.FromArray(node.translation), BABYLON.Quaternion.FromArray(node.rotation), BABYLON.Vector3.FromArray(node.scale));
  106912. }
  106913. newNode.computeWorldMatrix(true);
  106914. };
  106915. /**
  106916. * Imports a node
  106917. */
  106918. var importNode = function (gltfRuntime, node, id, parent) {
  106919. var lastNode = null;
  106920. if (gltfRuntime.importOnlyMeshes && (node.skin || node.meshes)) {
  106921. if (gltfRuntime.importMeshesNames && gltfRuntime.importMeshesNames.length > 0 && gltfRuntime.importMeshesNames.indexOf(node.name || "") === -1) {
  106922. return null;
  106923. }
  106924. }
  106925. // Meshes
  106926. if (node.skin) {
  106927. if (node.meshes) {
  106928. var skin = gltfRuntime.skins[node.skin];
  106929. var newMesh = importMesh(gltfRuntime, node, node.meshes, id, node.babylonNode);
  106930. newMesh.skeleton = gltfRuntime.scene.getLastSkeletonByID(node.skin);
  106931. if (newMesh.skeleton === null) {
  106932. newMesh.skeleton = importSkeleton(gltfRuntime, skin, newMesh, skin.babylonSkeleton, node.skin);
  106933. if (!skin.babylonSkeleton) {
  106934. skin.babylonSkeleton = newMesh.skeleton;
  106935. }
  106936. }
  106937. lastNode = newMesh;
  106938. }
  106939. }
  106940. else if (node.meshes) {
  106941. /**
  106942. * Improve meshes property
  106943. */
  106944. var newMesh = importMesh(gltfRuntime, node, node.mesh ? [node.mesh] : node.meshes, id, node.babylonNode);
  106945. lastNode = newMesh;
  106946. }
  106947. else if (node.light && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  106948. var light = gltfRuntime.lights[node.light];
  106949. if (light) {
  106950. if (light.type === "ambient") {
  106951. var ambienLight = light[light.type];
  106952. var hemiLight = new BABYLON.HemisphericLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  106953. hemiLight.name = node.name || "";
  106954. if (ambienLight.color) {
  106955. hemiLight.diffuse = BABYLON.Color3.FromArray(ambienLight.color);
  106956. }
  106957. lastNode = hemiLight;
  106958. }
  106959. else if (light.type === "directional") {
  106960. var directionalLight = light[light.type];
  106961. var dirLight = new BABYLON.DirectionalLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  106962. dirLight.name = node.name || "";
  106963. if (directionalLight.color) {
  106964. dirLight.diffuse = BABYLON.Color3.FromArray(directionalLight.color);
  106965. }
  106966. lastNode = dirLight;
  106967. }
  106968. else if (light.type === "point") {
  106969. var pointLight = light[light.type];
  106970. var ptLight = new BABYLON.PointLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  106971. ptLight.name = node.name || "";
  106972. if (pointLight.color) {
  106973. ptLight.diffuse = BABYLON.Color3.FromArray(pointLight.color);
  106974. }
  106975. lastNode = ptLight;
  106976. }
  106977. else if (light.type === "spot") {
  106978. var spotLight = light[light.type];
  106979. var spLight = new BABYLON.SpotLight(node.light, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, gltfRuntime.scene);
  106980. spLight.name = node.name || "";
  106981. if (spotLight.color) {
  106982. spLight.diffuse = BABYLON.Color3.FromArray(spotLight.color);
  106983. }
  106984. if (spotLight.fallOfAngle) {
  106985. spLight.angle = spotLight.fallOfAngle;
  106986. }
  106987. if (spotLight.fallOffExponent) {
  106988. spLight.exponent = spotLight.fallOffExponent;
  106989. }
  106990. lastNode = spLight;
  106991. }
  106992. }
  106993. }
  106994. else if (node.camera && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  106995. var camera = gltfRuntime.cameras[node.camera];
  106996. if (camera) {
  106997. if (camera.type === "orthographic") {
  106998. var orthoCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  106999. orthoCamera.name = node.name || "";
  107000. orthoCamera.mode = BABYLON.Camera.ORTHOGRAPHIC_CAMERA;
  107001. orthoCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  107002. lastNode = orthoCamera;
  107003. }
  107004. else if (camera.type === "perspective") {
  107005. var perspectiveCamera = camera[camera.type];
  107006. var persCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  107007. persCamera.name = node.name || "";
  107008. persCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  107009. if (!perspectiveCamera.aspectRatio) {
  107010. perspectiveCamera.aspectRatio = gltfRuntime.scene.getEngine().getRenderWidth() / gltfRuntime.scene.getEngine().getRenderHeight();
  107011. }
  107012. if (perspectiveCamera.znear && perspectiveCamera.zfar) {
  107013. persCamera.maxZ = perspectiveCamera.zfar;
  107014. persCamera.minZ = perspectiveCamera.znear;
  107015. }
  107016. lastNode = persCamera;
  107017. }
  107018. }
  107019. }
  107020. // Empty node
  107021. if (!node.jointName) {
  107022. if (node.babylonNode) {
  107023. return node.babylonNode;
  107024. }
  107025. else if (lastNode === null) {
  107026. var dummy = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  107027. node.babylonNode = dummy;
  107028. lastNode = dummy;
  107029. }
  107030. }
  107031. if (lastNode !== null) {
  107032. if (node.matrix && lastNode instanceof BABYLON.Mesh) {
  107033. configureNodeFromMatrix(lastNode, node, parent);
  107034. }
  107035. else {
  107036. var translation = node.translation || [0, 0, 0];
  107037. var rotation = node.rotation || [0, 0, 0, 1];
  107038. var scale = node.scale || [1, 1, 1];
  107039. configureNode(lastNode, BABYLON.Vector3.FromArray(translation), BABYLON.Quaternion.FromArray(rotation), BABYLON.Vector3.FromArray(scale));
  107040. }
  107041. lastNode.updateCache(true);
  107042. node.babylonNode = lastNode;
  107043. }
  107044. return lastNode;
  107045. };
  107046. /**
  107047. * Traverses nodes and creates them
  107048. */
  107049. var traverseNodes = function (gltfRuntime, id, parent, meshIncluded) {
  107050. if (meshIncluded === void 0) { meshIncluded = false; }
  107051. var node = gltfRuntime.nodes[id];
  107052. var newNode = null;
  107053. if (gltfRuntime.importOnlyMeshes && !meshIncluded && gltfRuntime.importMeshesNames) {
  107054. if (gltfRuntime.importMeshesNames.indexOf(node.name || "") !== -1 || gltfRuntime.importMeshesNames.length === 0) {
  107055. meshIncluded = true;
  107056. }
  107057. else {
  107058. meshIncluded = false;
  107059. }
  107060. }
  107061. else {
  107062. meshIncluded = true;
  107063. }
  107064. if (!node.jointName && meshIncluded) {
  107065. newNode = importNode(gltfRuntime, node, id, parent);
  107066. if (newNode !== null) {
  107067. newNode.id = id;
  107068. newNode.parent = parent;
  107069. }
  107070. }
  107071. if (node.children) {
  107072. for (var i = 0; i < node.children.length; i++) {
  107073. traverseNodes(gltfRuntime, node.children[i], newNode, meshIncluded);
  107074. }
  107075. }
  107076. };
  107077. /**
  107078. * do stuff after buffers, shaders are loaded (e.g. hook up materials, load animations, etc.)
  107079. */
  107080. var postLoad = function (gltfRuntime) {
  107081. // Nodes
  107082. var currentScene = gltfRuntime.currentScene;
  107083. if (currentScene) {
  107084. for (var i = 0; i < currentScene.nodes.length; i++) {
  107085. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  107086. }
  107087. }
  107088. else {
  107089. for (var thing in gltfRuntime.scenes) {
  107090. currentScene = gltfRuntime.scenes[thing];
  107091. for (var i = 0; i < currentScene.nodes.length; i++) {
  107092. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  107093. }
  107094. }
  107095. }
  107096. // Set animations
  107097. loadAnimations(gltfRuntime);
  107098. for (var i = 0; i < gltfRuntime.scene.skeletons.length; i++) {
  107099. var skeleton = gltfRuntime.scene.skeletons[i];
  107100. gltfRuntime.scene.beginAnimation(skeleton, 0, Number.MAX_VALUE, true, 1.0);
  107101. }
  107102. };
  107103. /**
  107104. * onBind shaderrs callback to set uniforms and matrices
  107105. */
  107106. var onBindShaderMaterial = function (mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess) {
  107107. var materialValues = material.values || technique.parameters;
  107108. for (var unif in unTreatedUniforms) {
  107109. var uniform = unTreatedUniforms[unif];
  107110. var type = uniform.type;
  107111. if (type === GLTF1.EParameterType.FLOAT_MAT2 || type === GLTF1.EParameterType.FLOAT_MAT3 || type === GLTF1.EParameterType.FLOAT_MAT4) {
  107112. if (uniform.semantic && !uniform.source && !uniform.node) {
  107113. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, mesh, uniform, unif, shaderMaterial.getEffect());
  107114. }
  107115. else if (uniform.semantic && (uniform.source || uniform.node)) {
  107116. var source = gltfRuntime.scene.getNodeByName(uniform.source || uniform.node || "");
  107117. if (source === null) {
  107118. source = gltfRuntime.scene.getNodeByID(uniform.source || uniform.node || "");
  107119. }
  107120. if (source === null) {
  107121. continue;
  107122. }
  107123. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, source, uniform, unif, shaderMaterial.getEffect());
  107124. }
  107125. }
  107126. else {
  107127. var value = materialValues[technique.uniforms[unif]];
  107128. if (!value) {
  107129. continue;
  107130. }
  107131. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  107132. var texture = gltfRuntime.textures[material.values ? value : uniform.value].babylonTexture;
  107133. if (texture === null || texture === undefined) {
  107134. continue;
  107135. }
  107136. shaderMaterial.getEffect().setTexture(unif, texture);
  107137. }
  107138. else {
  107139. GLTF1.GLTFUtils.SetUniform((shaderMaterial.getEffect()), unif, value, type);
  107140. }
  107141. }
  107142. }
  107143. onSuccess(shaderMaterial);
  107144. };
  107145. /**
  107146. * Prepare uniforms to send the only one time
  107147. * Loads the appropriate textures
  107148. */
  107149. var prepareShaderMaterialUniforms = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms) {
  107150. var materialValues = material.values || technique.parameters;
  107151. var techniqueUniforms = technique.uniforms;
  107152. /**
  107153. * Prepare values here (not matrices)
  107154. */
  107155. for (var unif in unTreatedUniforms) {
  107156. var uniform = unTreatedUniforms[unif];
  107157. var type = uniform.type;
  107158. var value = materialValues[techniqueUniforms[unif]];
  107159. if (value === undefined) {
  107160. // In case the value is the same for all materials
  107161. value = uniform.value;
  107162. }
  107163. if (!value) {
  107164. continue;
  107165. }
  107166. var onLoadTexture = function (uniformName) {
  107167. return function (texture) {
  107168. if (uniform.value && uniformName) {
  107169. // Static uniform
  107170. shaderMaterial.setTexture(uniformName, texture);
  107171. delete unTreatedUniforms[uniformName];
  107172. }
  107173. };
  107174. };
  107175. // Texture (sampler2D)
  107176. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  107177. GLTF1.GLTFLoaderExtension.LoadTextureAsync(gltfRuntime, material.values ? value : uniform.value, onLoadTexture(unif), function () { return onLoadTexture(null); });
  107178. }
  107179. else {
  107180. if (uniform.value && GLTF1.GLTFUtils.SetUniform(shaderMaterial, unif, material.values ? value : uniform.value, type)) {
  107181. // Static uniform
  107182. delete unTreatedUniforms[unif];
  107183. }
  107184. }
  107185. }
  107186. };
  107187. /**
  107188. * Shader compilation failed
  107189. */
  107190. var onShaderCompileError = function (program, shaderMaterial, onError) {
  107191. return function (effect, error) {
  107192. shaderMaterial.dispose(true);
  107193. onError("Cannot compile program named " + program.name + ". Error: " + error + ". Default material will be applied");
  107194. };
  107195. };
  107196. /**
  107197. * Shader compilation success
  107198. */
  107199. var onShaderCompileSuccess = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess) {
  107200. return function (_) {
  107201. prepareShaderMaterialUniforms(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms);
  107202. shaderMaterial.onBind = function (mesh) {
  107203. onBindShaderMaterial(mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess);
  107204. };
  107205. };
  107206. };
  107207. /**
  107208. * Returns the appropriate uniform if already handled by babylon
  107209. */
  107210. var parseShaderUniforms = function (tokenizer, technique, unTreatedUniforms) {
  107211. for (var unif in technique.uniforms) {
  107212. var uniform = technique.uniforms[unif];
  107213. var uniformParameter = technique.parameters[uniform];
  107214. if (tokenizer.currentIdentifier === unif) {
  107215. if (uniformParameter.semantic && !uniformParameter.source && !uniformParameter.node) {
  107216. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  107217. if (transformIndex !== -1) {
  107218. delete unTreatedUniforms[unif];
  107219. return babylonTransforms[transformIndex];
  107220. }
  107221. }
  107222. }
  107223. }
  107224. return tokenizer.currentIdentifier;
  107225. };
  107226. /**
  107227. * All shaders loaded. Create materials one by one
  107228. */
  107229. var importMaterials = function (gltfRuntime) {
  107230. // Create materials
  107231. for (var mat in gltfRuntime.materials) {
  107232. GLTF1.GLTFLoaderExtension.LoadMaterialAsync(gltfRuntime, mat, function (material) { }, function () { });
  107233. }
  107234. };
  107235. /**
  107236. * Implementation of the base glTF spec
  107237. */
  107238. var GLTFLoaderBase = /** @class */ (function () {
  107239. function GLTFLoaderBase() {
  107240. }
  107241. GLTFLoaderBase.CreateRuntime = function (parsedData, scene, rootUrl) {
  107242. var gltfRuntime = {
  107243. extensions: {},
  107244. accessors: {},
  107245. buffers: {},
  107246. bufferViews: {},
  107247. meshes: {},
  107248. lights: {},
  107249. cameras: {},
  107250. nodes: {},
  107251. images: {},
  107252. textures: {},
  107253. shaders: {},
  107254. programs: {},
  107255. samplers: {},
  107256. techniques: {},
  107257. materials: {},
  107258. animations: {},
  107259. skins: {},
  107260. extensionsUsed: [],
  107261. scenes: {},
  107262. buffersCount: 0,
  107263. shaderscount: 0,
  107264. scene: scene,
  107265. rootUrl: rootUrl,
  107266. loadedBufferCount: 0,
  107267. loadedBufferViews: {},
  107268. loadedShaderCount: 0,
  107269. importOnlyMeshes: false,
  107270. dummyNodes: []
  107271. };
  107272. // Parse
  107273. if (parsedData.extensions) {
  107274. parseObject(parsedData.extensions, "extensions", gltfRuntime);
  107275. }
  107276. if (parsedData.extensionsUsed) {
  107277. parseObject(parsedData.extensionsUsed, "extensionsUsed", gltfRuntime);
  107278. }
  107279. if (parsedData.buffers) {
  107280. parseBuffers(parsedData.buffers, gltfRuntime);
  107281. }
  107282. if (parsedData.bufferViews) {
  107283. parseObject(parsedData.bufferViews, "bufferViews", gltfRuntime);
  107284. }
  107285. if (parsedData.accessors) {
  107286. parseObject(parsedData.accessors, "accessors", gltfRuntime);
  107287. }
  107288. if (parsedData.meshes) {
  107289. parseObject(parsedData.meshes, "meshes", gltfRuntime);
  107290. }
  107291. if (parsedData.lights) {
  107292. parseObject(parsedData.lights, "lights", gltfRuntime);
  107293. }
  107294. if (parsedData.cameras) {
  107295. parseObject(parsedData.cameras, "cameras", gltfRuntime);
  107296. }
  107297. if (parsedData.nodes) {
  107298. parseObject(parsedData.nodes, "nodes", gltfRuntime);
  107299. }
  107300. if (parsedData.images) {
  107301. parseObject(parsedData.images, "images", gltfRuntime);
  107302. }
  107303. if (parsedData.textures) {
  107304. parseObject(parsedData.textures, "textures", gltfRuntime);
  107305. }
  107306. if (parsedData.shaders) {
  107307. parseShaders(parsedData.shaders, gltfRuntime);
  107308. }
  107309. if (parsedData.programs) {
  107310. parseObject(parsedData.programs, "programs", gltfRuntime);
  107311. }
  107312. if (parsedData.samplers) {
  107313. parseObject(parsedData.samplers, "samplers", gltfRuntime);
  107314. }
  107315. if (parsedData.techniques) {
  107316. parseObject(parsedData.techniques, "techniques", gltfRuntime);
  107317. }
  107318. if (parsedData.materials) {
  107319. parseObject(parsedData.materials, "materials", gltfRuntime);
  107320. }
  107321. if (parsedData.animations) {
  107322. parseObject(parsedData.animations, "animations", gltfRuntime);
  107323. }
  107324. if (parsedData.skins) {
  107325. parseObject(parsedData.skins, "skins", gltfRuntime);
  107326. }
  107327. if (parsedData.scenes) {
  107328. gltfRuntime.scenes = parsedData.scenes;
  107329. }
  107330. if (parsedData.scene && parsedData.scenes) {
  107331. gltfRuntime.currentScene = parsedData.scenes[parsedData.scene];
  107332. }
  107333. return gltfRuntime;
  107334. };
  107335. GLTFLoaderBase.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  107336. var buffer = gltfRuntime.buffers[id];
  107337. if (BABYLON.Tools.IsBase64(buffer.uri)) {
  107338. setTimeout(function () { return onSuccess(new Uint8Array(BABYLON.Tools.DecodeBase64(buffer.uri))); });
  107339. }
  107340. else {
  107341. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + buffer.uri, function (data) { return onSuccess(new Uint8Array(data)); }, onProgress, undefined, true, function (request) {
  107342. if (request) {
  107343. onError(request.status + " " + request.statusText);
  107344. }
  107345. });
  107346. }
  107347. };
  107348. GLTFLoaderBase.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  107349. var texture = gltfRuntime.textures[id];
  107350. if (!texture || !texture.source) {
  107351. onError("");
  107352. return;
  107353. }
  107354. if (texture.babylonTexture) {
  107355. onSuccess(null);
  107356. return;
  107357. }
  107358. var source = gltfRuntime.images[texture.source];
  107359. if (BABYLON.Tools.IsBase64(source.uri)) {
  107360. setTimeout(function () { return onSuccess(new Uint8Array(BABYLON.Tools.DecodeBase64(source.uri))); });
  107361. }
  107362. else {
  107363. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + source.uri, function (data) { return onSuccess(new Uint8Array(data)); }, undefined, undefined, true, function (request) {
  107364. if (request) {
  107365. onError(request.status + " " + request.statusText);
  107366. }
  107367. });
  107368. }
  107369. };
  107370. GLTFLoaderBase.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  107371. var texture = gltfRuntime.textures[id];
  107372. if (texture.babylonTexture) {
  107373. onSuccess(texture.babylonTexture);
  107374. return;
  107375. }
  107376. var sampler = gltfRuntime.samplers[texture.sampler];
  107377. var createMipMaps = (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST) ||
  107378. (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_LINEAR) ||
  107379. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST) ||
  107380. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR);
  107381. var samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  107382. var blob = new Blob([buffer]);
  107383. var blobURL = URL.createObjectURL(blob);
  107384. var revokeBlobURL = function () { return URL.revokeObjectURL(blobURL); };
  107385. var newTexture = new BABYLON.Texture(blobURL, gltfRuntime.scene, !createMipMaps, true, samplingMode, revokeBlobURL, revokeBlobURL);
  107386. if (sampler.wrapS !== undefined) {
  107387. newTexture.wrapU = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapS);
  107388. }
  107389. if (sampler.wrapT !== undefined) {
  107390. newTexture.wrapV = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapT);
  107391. }
  107392. newTexture.name = id;
  107393. texture.babylonTexture = newTexture;
  107394. onSuccess(newTexture);
  107395. };
  107396. GLTFLoaderBase.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  107397. var shader = gltfRuntime.shaders[id];
  107398. if (BABYLON.Tools.IsBase64(shader.uri)) {
  107399. var shaderString = atob(shader.uri.split(",")[1]);
  107400. onSuccess(shaderString);
  107401. }
  107402. else {
  107403. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + shader.uri, onSuccess, undefined, undefined, false, function (request) {
  107404. if (request) {
  107405. onError(request.status + " " + request.statusText);
  107406. }
  107407. });
  107408. }
  107409. };
  107410. GLTFLoaderBase.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  107411. var material = gltfRuntime.materials[id];
  107412. if (!material.technique) {
  107413. if (onError) {
  107414. onError("No technique found.");
  107415. }
  107416. return;
  107417. }
  107418. var technique = gltfRuntime.techniques[material.technique];
  107419. if (!technique) {
  107420. var defaultMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  107421. defaultMaterial.diffuseColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  107422. defaultMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  107423. onSuccess(defaultMaterial);
  107424. return;
  107425. }
  107426. var program = gltfRuntime.programs[technique.program];
  107427. var states = technique.states;
  107428. var vertexShader = BABYLON.Effect.ShadersStore[program.vertexShader + "VertexShader"];
  107429. var pixelShader = BABYLON.Effect.ShadersStore[program.fragmentShader + "PixelShader"];
  107430. var newVertexShader = "";
  107431. var newPixelShader = "";
  107432. var vertexTokenizer = new Tokenizer(vertexShader);
  107433. var pixelTokenizer = new Tokenizer(pixelShader);
  107434. var unTreatedUniforms = {};
  107435. var uniforms = [];
  107436. var attributes = [];
  107437. var samplers = [];
  107438. // Fill uniform, sampler2D and attributes
  107439. for (var unif in technique.uniforms) {
  107440. var uniform = technique.uniforms[unif];
  107441. var uniformParameter = technique.parameters[uniform];
  107442. unTreatedUniforms[unif] = uniformParameter;
  107443. if (uniformParameter.semantic && !uniformParameter.node && !uniformParameter.source) {
  107444. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  107445. if (transformIndex !== -1) {
  107446. uniforms.push(babylonTransforms[transformIndex]);
  107447. delete unTreatedUniforms[unif];
  107448. }
  107449. else {
  107450. uniforms.push(unif);
  107451. }
  107452. }
  107453. else if (uniformParameter.type === GLTF1.EParameterType.SAMPLER_2D) {
  107454. samplers.push(unif);
  107455. }
  107456. else {
  107457. uniforms.push(unif);
  107458. }
  107459. }
  107460. for (var attr in technique.attributes) {
  107461. var attribute = technique.attributes[attr];
  107462. var attributeParameter = technique.parameters[attribute];
  107463. if (attributeParameter.semantic) {
  107464. attributes.push(getAttribute(attributeParameter));
  107465. }
  107466. }
  107467. // Configure vertex shader
  107468. while (!vertexTokenizer.isEnd() && vertexTokenizer.getNextToken()) {
  107469. var tokenType = vertexTokenizer.currentToken;
  107470. if (tokenType !== ETokenType.IDENTIFIER) {
  107471. newVertexShader += vertexTokenizer.currentString;
  107472. continue;
  107473. }
  107474. var foundAttribute = false;
  107475. for (var attr in technique.attributes) {
  107476. var attribute = technique.attributes[attr];
  107477. var attributeParameter = technique.parameters[attribute];
  107478. if (vertexTokenizer.currentIdentifier === attr && attributeParameter.semantic) {
  107479. newVertexShader += getAttribute(attributeParameter);
  107480. foundAttribute = true;
  107481. break;
  107482. }
  107483. }
  107484. if (foundAttribute) {
  107485. continue;
  107486. }
  107487. newVertexShader += parseShaderUniforms(vertexTokenizer, technique, unTreatedUniforms);
  107488. }
  107489. // Configure pixel shader
  107490. while (!pixelTokenizer.isEnd() && pixelTokenizer.getNextToken()) {
  107491. var tokenType = pixelTokenizer.currentToken;
  107492. if (tokenType !== ETokenType.IDENTIFIER) {
  107493. newPixelShader += pixelTokenizer.currentString;
  107494. continue;
  107495. }
  107496. newPixelShader += parseShaderUniforms(pixelTokenizer, technique, unTreatedUniforms);
  107497. }
  107498. // Create shader material
  107499. var shaderPath = {
  107500. vertex: program.vertexShader + id,
  107501. fragment: program.fragmentShader + id
  107502. };
  107503. var options = {
  107504. attributes: attributes,
  107505. uniforms: uniforms,
  107506. samplers: samplers,
  107507. needAlphaBlending: states && states.enable && states.enable.indexOf(3042) !== -1
  107508. };
  107509. BABYLON.Effect.ShadersStore[program.vertexShader + id + "VertexShader"] = newVertexShader;
  107510. BABYLON.Effect.ShadersStore[program.fragmentShader + id + "PixelShader"] = newPixelShader;
  107511. var shaderMaterial = new BABYLON.ShaderMaterial(id, gltfRuntime.scene, shaderPath, options);
  107512. shaderMaterial.onError = onShaderCompileError(program, shaderMaterial, onError);
  107513. shaderMaterial.onCompiled = onShaderCompileSuccess(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess);
  107514. shaderMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  107515. if (states && states.functions) {
  107516. var functions = states.functions;
  107517. if (functions.cullFace && functions.cullFace[0] !== GLTF1.ECullingType.BACK) {
  107518. shaderMaterial.backFaceCulling = false;
  107519. }
  107520. var blendFunc = functions.blendFuncSeparate;
  107521. if (blendFunc) {
  107522. 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) {
  107523. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  107524. }
  107525. else if (blendFunc[0] === GLTF1.EBlendingFunction.ONE && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  107526. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  107527. }
  107528. else if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  107529. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ADD;
  107530. }
  107531. 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) {
  107532. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_SUBTRACT;
  107533. }
  107534. else if (blendFunc[0] === GLTF1.EBlendingFunction.DST_COLOR && blendFunc[1] === GLTF1.EBlendingFunction.ZERO && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  107535. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MULTIPLY;
  107536. }
  107537. 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) {
  107538. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MAXIMIZED;
  107539. }
  107540. }
  107541. }
  107542. };
  107543. return GLTFLoaderBase;
  107544. }());
  107545. GLTF1.GLTFLoaderBase = GLTFLoaderBase;
  107546. /**
  107547. * glTF V1 Loader
  107548. */
  107549. var GLTFLoader = /** @class */ (function () {
  107550. function GLTFLoader() {
  107551. // #region Stubs for IGLTFLoader interface
  107552. this.coordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode.AUTO;
  107553. this.animationStartMode = BABYLON.GLTFLoaderAnimationStartMode.FIRST;
  107554. this.compileMaterials = false;
  107555. this.useClipPlane = false;
  107556. this.compileShadowGenerators = false;
  107557. this.onDisposeObservable = new BABYLON.Observable();
  107558. this.onMeshLoadedObservable = new BABYLON.Observable();
  107559. this.onTextureLoadedObservable = new BABYLON.Observable();
  107560. this.onMaterialLoadedObservable = new BABYLON.Observable();
  107561. this.onAnimationGroupLoadedObservable = new BABYLON.Observable();
  107562. this.onCompleteObservable = new BABYLON.Observable();
  107563. this.onExtensionLoadedObservable = new BABYLON.Observable();
  107564. this.state = null;
  107565. }
  107566. GLTFLoader.RegisterExtension = function (extension) {
  107567. if (GLTFLoader.Extensions[extension.name]) {
  107568. BABYLON.Tools.Error("Tool with the same name \"" + extension.name + "\" already exists");
  107569. return;
  107570. }
  107571. GLTFLoader.Extensions[extension.name] = extension;
  107572. };
  107573. GLTFLoader.prototype.dispose = function () { };
  107574. // #endregion
  107575. GLTFLoader.prototype._importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  107576. var _this = this;
  107577. scene.useRightHandedSystem = true;
  107578. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  107579. gltfRuntime.importOnlyMeshes = true;
  107580. if (meshesNames === "") {
  107581. gltfRuntime.importMeshesNames = [];
  107582. }
  107583. else if (typeof meshesNames === "string") {
  107584. gltfRuntime.importMeshesNames = [meshesNames];
  107585. }
  107586. else if (meshesNames && !(meshesNames instanceof Array)) {
  107587. gltfRuntime.importMeshesNames = [meshesNames];
  107588. }
  107589. else {
  107590. gltfRuntime.importMeshesNames = [];
  107591. BABYLON.Tools.Warn("Argument meshesNames must be of type string or string[]");
  107592. }
  107593. // Create nodes
  107594. _this._createNodes(gltfRuntime);
  107595. var meshes = new Array();
  107596. var skeletons = new Array();
  107597. // Fill arrays of meshes and skeletons
  107598. for (var nde in gltfRuntime.nodes) {
  107599. var node = gltfRuntime.nodes[nde];
  107600. if (node.babylonNode instanceof BABYLON.AbstractMesh) {
  107601. meshes.push(node.babylonNode);
  107602. }
  107603. }
  107604. for (var skl in gltfRuntime.skins) {
  107605. var skin = gltfRuntime.skins[skl];
  107606. if (skin.babylonSkeleton instanceof BABYLON.Skeleton) {
  107607. skeletons.push(skin.babylonSkeleton);
  107608. }
  107609. }
  107610. // Load buffers, shaders, materials, etc.
  107611. _this._loadBuffersAsync(gltfRuntime, function () {
  107612. _this._loadShadersAsync(gltfRuntime, function () {
  107613. importMaterials(gltfRuntime);
  107614. postLoad(gltfRuntime);
  107615. if (!BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  107616. onSuccess(meshes, [], skeletons);
  107617. }
  107618. });
  107619. }, onProgress);
  107620. if (BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  107621. onSuccess(meshes, [], skeletons);
  107622. }
  107623. }, onError);
  107624. return true;
  107625. };
  107626. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  107627. var _this = this;
  107628. return new Promise(function (resolve, reject) {
  107629. _this._importMeshAsync(meshesNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  107630. resolve({
  107631. meshes: meshes,
  107632. particleSystems: particleSystems,
  107633. skeletons: skeletons
  107634. });
  107635. }, onProgress, function (message) {
  107636. reject(new Error(message));
  107637. });
  107638. });
  107639. };
  107640. GLTFLoader.prototype._loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  107641. var _this = this;
  107642. scene.useRightHandedSystem = true;
  107643. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  107644. // Load runtime extensios
  107645. GLTF1.GLTFLoaderExtension.LoadRuntimeExtensionsAsync(gltfRuntime, function () {
  107646. // Create nodes
  107647. _this._createNodes(gltfRuntime);
  107648. // Load buffers, shaders, materials, etc.
  107649. _this._loadBuffersAsync(gltfRuntime, function () {
  107650. _this._loadShadersAsync(gltfRuntime, function () {
  107651. importMaterials(gltfRuntime);
  107652. postLoad(gltfRuntime);
  107653. if (!BABYLON.GLTFFileLoader.IncrementalLoading) {
  107654. onSuccess();
  107655. }
  107656. });
  107657. });
  107658. if (BABYLON.GLTFFileLoader.IncrementalLoading) {
  107659. onSuccess();
  107660. }
  107661. }, onError);
  107662. }, onError);
  107663. };
  107664. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  107665. var _this = this;
  107666. return new Promise(function (resolve, reject) {
  107667. _this._loadAsync(scene, data, rootUrl, function () {
  107668. resolve();
  107669. }, onProgress, function (message) {
  107670. reject(new Error(message));
  107671. });
  107672. });
  107673. };
  107674. GLTFLoader.prototype._loadShadersAsync = function (gltfRuntime, onload) {
  107675. var hasShaders = false;
  107676. var processShader = function (sha, shader) {
  107677. GLTF1.GLTFLoaderExtension.LoadShaderStringAsync(gltfRuntime, sha, function (shaderString) {
  107678. gltfRuntime.loadedShaderCount++;
  107679. if (shaderString) {
  107680. BABYLON.Effect.ShadersStore[sha + (shader.type === GLTF1.EShaderType.VERTEX ? "VertexShader" : "PixelShader")] = shaderString;
  107681. }
  107682. if (gltfRuntime.loadedShaderCount === gltfRuntime.shaderscount) {
  107683. onload();
  107684. }
  107685. }, function () {
  107686. BABYLON.Tools.Error("Error when loading shader program named " + sha + " located at " + shader.uri);
  107687. });
  107688. };
  107689. for (var sha in gltfRuntime.shaders) {
  107690. hasShaders = true;
  107691. var shader = gltfRuntime.shaders[sha];
  107692. if (shader) {
  107693. processShader.bind(this, sha, shader)();
  107694. }
  107695. else {
  107696. BABYLON.Tools.Error("No shader named: " + sha);
  107697. }
  107698. }
  107699. if (!hasShaders) {
  107700. onload();
  107701. }
  107702. };
  107703. ;
  107704. GLTFLoader.prototype._loadBuffersAsync = function (gltfRuntime, onLoad, onProgress) {
  107705. var hasBuffers = false;
  107706. var processBuffer = function (buf, buffer) {
  107707. GLTF1.GLTFLoaderExtension.LoadBufferAsync(gltfRuntime, buf, function (bufferView) {
  107708. gltfRuntime.loadedBufferCount++;
  107709. if (bufferView) {
  107710. if (bufferView.byteLength != gltfRuntime.buffers[buf].byteLength) {
  107711. BABYLON.Tools.Error("Buffer named " + buf + " is length " + bufferView.byteLength + ". Expected: " + buffer.byteLength); // Improve error message
  107712. }
  107713. gltfRuntime.loadedBufferViews[buf] = bufferView;
  107714. }
  107715. if (gltfRuntime.loadedBufferCount === gltfRuntime.buffersCount) {
  107716. onLoad();
  107717. }
  107718. }, function () {
  107719. BABYLON.Tools.Error("Error when loading buffer named " + buf + " located at " + buffer.uri);
  107720. });
  107721. };
  107722. for (var buf in gltfRuntime.buffers) {
  107723. hasBuffers = true;
  107724. var buffer = gltfRuntime.buffers[buf];
  107725. if (buffer) {
  107726. processBuffer.bind(this, buf, buffer)();
  107727. }
  107728. else {
  107729. BABYLON.Tools.Error("No buffer named: " + buf);
  107730. }
  107731. }
  107732. if (!hasBuffers) {
  107733. onLoad();
  107734. }
  107735. };
  107736. GLTFLoader.prototype._createNodes = function (gltfRuntime) {
  107737. var currentScene = gltfRuntime.currentScene;
  107738. if (currentScene) {
  107739. // Only one scene even if multiple scenes are defined
  107740. for (var i = 0; i < currentScene.nodes.length; i++) {
  107741. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  107742. }
  107743. }
  107744. else {
  107745. // Load all scenes
  107746. for (var thing in gltfRuntime.scenes) {
  107747. currentScene = gltfRuntime.scenes[thing];
  107748. for (var i = 0; i < currentScene.nodes.length; i++) {
  107749. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  107750. }
  107751. }
  107752. }
  107753. };
  107754. GLTFLoader.Extensions = {};
  107755. return GLTFLoader;
  107756. }());
  107757. GLTF1.GLTFLoader = GLTFLoader;
  107758. ;
  107759. BABYLON.GLTFFileLoader.CreateGLTFLoaderV1 = function () { return new GLTFLoader(); };
  107760. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  107761. })(BABYLON || (BABYLON = {}));
  107762. //# sourceMappingURL=babylon.glTFLoader.js.map
  107763. var BABYLON;
  107764. (function (BABYLON) {
  107765. var GLTF1;
  107766. (function (GLTF1) {
  107767. /**
  107768. * Utils functions for GLTF
  107769. */
  107770. var GLTFUtils = /** @class */ (function () {
  107771. function GLTFUtils() {
  107772. }
  107773. /**
  107774. * Sets the given "parameter" matrix
  107775. * @param scene: the {BABYLON.Scene} object
  107776. * @param source: the source node where to pick the matrix
  107777. * @param parameter: the GLTF technique parameter
  107778. * @param uniformName: the name of the shader's uniform
  107779. * @param shaderMaterial: the shader material
  107780. */
  107781. GLTFUtils.SetMatrix = function (scene, source, parameter, uniformName, shaderMaterial) {
  107782. var mat = null;
  107783. if (parameter.semantic === "MODEL") {
  107784. mat = source.getWorldMatrix();
  107785. }
  107786. else if (parameter.semantic === "PROJECTION") {
  107787. mat = scene.getProjectionMatrix();
  107788. }
  107789. else if (parameter.semantic === "VIEW") {
  107790. mat = scene.getViewMatrix();
  107791. }
  107792. else if (parameter.semantic === "MODELVIEWINVERSETRANSPOSE") {
  107793. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().multiply(scene.getViewMatrix()).invert());
  107794. }
  107795. else if (parameter.semantic === "MODELVIEW") {
  107796. mat = source.getWorldMatrix().multiply(scene.getViewMatrix());
  107797. }
  107798. else if (parameter.semantic === "MODELVIEWPROJECTION") {
  107799. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix());
  107800. }
  107801. else if (parameter.semantic === "MODELINVERSE") {
  107802. mat = source.getWorldMatrix().invert();
  107803. }
  107804. else if (parameter.semantic === "VIEWINVERSE") {
  107805. mat = scene.getViewMatrix().invert();
  107806. }
  107807. else if (parameter.semantic === "PROJECTIONINVERSE") {
  107808. mat = scene.getProjectionMatrix().invert();
  107809. }
  107810. else if (parameter.semantic === "MODELVIEWINVERSE") {
  107811. mat = source.getWorldMatrix().multiply(scene.getViewMatrix()).invert();
  107812. }
  107813. else if (parameter.semantic === "MODELVIEWPROJECTIONINVERSE") {
  107814. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix()).invert();
  107815. }
  107816. else if (parameter.semantic === "MODELINVERSETRANSPOSE") {
  107817. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().invert());
  107818. }
  107819. else {
  107820. debugger;
  107821. }
  107822. if (mat) {
  107823. switch (parameter.type) {
  107824. case GLTF1.EParameterType.FLOAT_MAT2:
  107825. shaderMaterial.setMatrix2x2(uniformName, BABYLON.Matrix.GetAsMatrix2x2(mat));
  107826. break;
  107827. case GLTF1.EParameterType.FLOAT_MAT3:
  107828. shaderMaterial.setMatrix3x3(uniformName, BABYLON.Matrix.GetAsMatrix3x3(mat));
  107829. break;
  107830. case GLTF1.EParameterType.FLOAT_MAT4:
  107831. shaderMaterial.setMatrix(uniformName, mat);
  107832. break;
  107833. default: break;
  107834. }
  107835. }
  107836. };
  107837. /**
  107838. * Sets the given "parameter" matrix
  107839. * @param shaderMaterial: the shader material
  107840. * @param uniform: the name of the shader's uniform
  107841. * @param value: the value of the uniform
  107842. * @param type: the uniform's type (EParameterType FLOAT, VEC2, VEC3 or VEC4)
  107843. */
  107844. GLTFUtils.SetUniform = function (shaderMaterial, uniform, value, type) {
  107845. switch (type) {
  107846. case GLTF1.EParameterType.FLOAT:
  107847. shaderMaterial.setFloat(uniform, value);
  107848. return true;
  107849. case GLTF1.EParameterType.FLOAT_VEC2:
  107850. shaderMaterial.setVector2(uniform, BABYLON.Vector2.FromArray(value));
  107851. return true;
  107852. case GLTF1.EParameterType.FLOAT_VEC3:
  107853. shaderMaterial.setVector3(uniform, BABYLON.Vector3.FromArray(value));
  107854. return true;
  107855. case GLTF1.EParameterType.FLOAT_VEC4:
  107856. shaderMaterial.setVector4(uniform, BABYLON.Vector4.FromArray(value));
  107857. return true;
  107858. default: return false;
  107859. }
  107860. };
  107861. /**
  107862. * Returns the wrap mode of the texture
  107863. * @param mode: the mode value
  107864. */
  107865. GLTFUtils.GetWrapMode = function (mode) {
  107866. switch (mode) {
  107867. case GLTF1.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  107868. case GLTF1.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  107869. case GLTF1.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  107870. default: return BABYLON.Texture.WRAP_ADDRESSMODE;
  107871. }
  107872. };
  107873. /**
  107874. * Returns the byte stride giving an accessor
  107875. * @param accessor: the GLTF accessor objet
  107876. */
  107877. GLTFUtils.GetByteStrideFromType = function (accessor) {
  107878. // Needs this function since "byteStride" isn't requiered in glTF format
  107879. var type = accessor.type;
  107880. switch (type) {
  107881. case "VEC2": return 2;
  107882. case "VEC3": return 3;
  107883. case "VEC4": return 4;
  107884. case "MAT2": return 4;
  107885. case "MAT3": return 9;
  107886. case "MAT4": return 16;
  107887. default: return 1;
  107888. }
  107889. };
  107890. /**
  107891. * Returns the texture filter mode giving a mode value
  107892. * @param mode: the filter mode value
  107893. */
  107894. GLTFUtils.GetTextureFilterMode = function (mode) {
  107895. switch (mode) {
  107896. case GLTF1.ETextureFilterType.LINEAR:
  107897. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST:
  107898. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  107899. case GLTF1.ETextureFilterType.NEAREST:
  107900. case GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_SAMPLINGMODE;
  107901. default: return BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  107902. }
  107903. };
  107904. GLTFUtils.GetBufferFromBufferView = function (gltfRuntime, bufferView, byteOffset, byteLength, componentType) {
  107905. var byteOffset = bufferView.byteOffset + byteOffset;
  107906. var loadedBufferView = gltfRuntime.loadedBufferViews[bufferView.buffer];
  107907. if (byteOffset + byteLength > loadedBufferView.byteLength) {
  107908. throw new Error("Buffer access is out of range");
  107909. }
  107910. var buffer = loadedBufferView.buffer;
  107911. byteOffset += loadedBufferView.byteOffset;
  107912. switch (componentType) {
  107913. case GLTF1.EComponentType.BYTE: return new Int8Array(buffer, byteOffset, byteLength);
  107914. case GLTF1.EComponentType.UNSIGNED_BYTE: return new Uint8Array(buffer, byteOffset, byteLength);
  107915. case GLTF1.EComponentType.SHORT: return new Int16Array(buffer, byteOffset, byteLength);
  107916. case GLTF1.EComponentType.UNSIGNED_SHORT: return new Uint16Array(buffer, byteOffset, byteLength);
  107917. default: return new Float32Array(buffer, byteOffset, byteLength);
  107918. }
  107919. };
  107920. /**
  107921. * Returns a buffer from its accessor
  107922. * @param gltfRuntime: the GLTF runtime
  107923. * @param accessor: the GLTF accessor
  107924. */
  107925. GLTFUtils.GetBufferFromAccessor = function (gltfRuntime, accessor) {
  107926. var bufferView = gltfRuntime.bufferViews[accessor.bufferView];
  107927. var byteLength = accessor.count * GLTFUtils.GetByteStrideFromType(accessor);
  107928. return GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, accessor.byteOffset, byteLength, accessor.componentType);
  107929. };
  107930. /**
  107931. * Decodes a buffer view into a string
  107932. * @param view: the buffer view
  107933. */
  107934. GLTFUtils.DecodeBufferToText = function (view) {
  107935. var result = "";
  107936. var length = view.byteLength;
  107937. for (var i = 0; i < length; ++i) {
  107938. result += String.fromCharCode(view[i]);
  107939. }
  107940. return result;
  107941. };
  107942. /**
  107943. * Returns the default material of gltf. Related to
  107944. * https://github.com/KhronosGroup/glTF/tree/master/specification/1.0#appendix-a-default-material
  107945. * @param scene: the Babylon.js scene
  107946. */
  107947. GLTFUtils.GetDefaultMaterial = function (scene) {
  107948. if (!GLTFUtils._DefaultMaterial) {
  107949. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialVertexShader"] = [
  107950. "precision highp float;",
  107951. "",
  107952. "uniform mat4 worldView;",
  107953. "uniform mat4 projection;",
  107954. "",
  107955. "attribute vec3 position;",
  107956. "",
  107957. "void main(void)",
  107958. "{",
  107959. " gl_Position = projection * worldView * vec4(position, 1.0);",
  107960. "}"
  107961. ].join("\n");
  107962. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialPixelShader"] = [
  107963. "precision highp float;",
  107964. "",
  107965. "uniform vec4 u_emission;",
  107966. "",
  107967. "void main(void)",
  107968. "{",
  107969. " gl_FragColor = u_emission;",
  107970. "}"
  107971. ].join("\n");
  107972. var shaderPath = {
  107973. vertex: "GLTFDefaultMaterial",
  107974. fragment: "GLTFDefaultMaterial"
  107975. };
  107976. var options = {
  107977. attributes: ["position"],
  107978. uniforms: ["worldView", "projection", "u_emission"],
  107979. samplers: new Array(),
  107980. needAlphaBlending: false
  107981. };
  107982. GLTFUtils._DefaultMaterial = new BABYLON.ShaderMaterial("GLTFDefaultMaterial", scene, shaderPath, options);
  107983. GLTFUtils._DefaultMaterial.setColor4("u_emission", new BABYLON.Color4(0.5, 0.5, 0.5, 1.0));
  107984. }
  107985. return GLTFUtils._DefaultMaterial;
  107986. };
  107987. // The GLTF default material
  107988. GLTFUtils._DefaultMaterial = null;
  107989. return GLTFUtils;
  107990. }());
  107991. GLTF1.GLTFUtils = GLTFUtils;
  107992. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  107993. })(BABYLON || (BABYLON = {}));
  107994. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  107995. var BABYLON;
  107996. (function (BABYLON) {
  107997. var GLTF1;
  107998. (function (GLTF1) {
  107999. var GLTFLoaderExtension = /** @class */ (function () {
  108000. function GLTFLoaderExtension(name) {
  108001. this._name = name;
  108002. }
  108003. Object.defineProperty(GLTFLoaderExtension.prototype, "name", {
  108004. get: function () {
  108005. return this._name;
  108006. },
  108007. enumerable: true,
  108008. configurable: true
  108009. });
  108010. /**
  108011. * Defines an override for loading the runtime
  108012. * Return true to stop further extensions from loading the runtime
  108013. */
  108014. GLTFLoaderExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  108015. return false;
  108016. };
  108017. /**
  108018. * Defines an onverride for creating gltf runtime
  108019. * Return true to stop further extensions from creating the runtime
  108020. */
  108021. GLTFLoaderExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  108022. return false;
  108023. };
  108024. /**
  108025. * Defines an override for loading buffers
  108026. * Return true to stop further extensions from loading this buffer
  108027. */
  108028. GLTFLoaderExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  108029. return false;
  108030. };
  108031. /**
  108032. * Defines an override for loading texture buffers
  108033. * Return true to stop further extensions from loading this texture data
  108034. */
  108035. GLTFLoaderExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  108036. return false;
  108037. };
  108038. /**
  108039. * Defines an override for creating textures
  108040. * Return true to stop further extensions from loading this texture
  108041. */
  108042. GLTFLoaderExtension.prototype.createTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  108043. return false;
  108044. };
  108045. /**
  108046. * Defines an override for loading shader strings
  108047. * Return true to stop further extensions from loading this shader data
  108048. */
  108049. GLTFLoaderExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  108050. return false;
  108051. };
  108052. /**
  108053. * Defines an override for loading materials
  108054. * Return true to stop further extensions from loading this material
  108055. */
  108056. GLTFLoaderExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  108057. return false;
  108058. };
  108059. // ---------
  108060. // Utilities
  108061. // ---------
  108062. GLTFLoaderExtension.LoadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  108063. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  108064. return loaderExtension.loadRuntimeAsync(scene, data, rootUrl, onSuccess, onError);
  108065. }, function () {
  108066. setTimeout(function () {
  108067. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  108068. });
  108069. });
  108070. };
  108071. GLTFLoaderExtension.LoadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  108072. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  108073. return loaderExtension.loadRuntimeExtensionsAsync(gltfRuntime, onSuccess, onError);
  108074. }, function () {
  108075. setTimeout(function () {
  108076. onSuccess();
  108077. });
  108078. });
  108079. };
  108080. GLTFLoaderExtension.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  108081. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  108082. return loaderExtension.loadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  108083. }, function () {
  108084. GLTF1.GLTFLoaderBase.LoadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  108085. });
  108086. };
  108087. GLTFLoaderExtension.LoadTextureAsync = function (gltfRuntime, id, onSuccess, onError) {
  108088. GLTFLoaderExtension.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) { return GLTFLoaderExtension.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError); }, onError);
  108089. };
  108090. GLTFLoaderExtension.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  108091. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  108092. return loaderExtension.loadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  108093. }, function () {
  108094. GLTF1.GLTFLoaderBase.LoadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  108095. });
  108096. };
  108097. GLTFLoaderExtension.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  108098. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  108099. return loaderExtension.loadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  108100. }, function () {
  108101. GLTF1.GLTFLoaderBase.LoadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  108102. });
  108103. };
  108104. GLTFLoaderExtension.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  108105. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  108106. return loaderExtension.loadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  108107. }, function () {
  108108. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  108109. });
  108110. };
  108111. GLTFLoaderExtension.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  108112. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  108113. return loaderExtension.createTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  108114. }, function () {
  108115. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  108116. });
  108117. };
  108118. GLTFLoaderExtension.ApplyExtensions = function (func, defaultFunc) {
  108119. for (var extensionName in GLTF1.GLTFLoader.Extensions) {
  108120. var loaderExtension = GLTF1.GLTFLoader.Extensions[extensionName];
  108121. if (func(loaderExtension)) {
  108122. return;
  108123. }
  108124. }
  108125. defaultFunc();
  108126. };
  108127. return GLTFLoaderExtension;
  108128. }());
  108129. GLTF1.GLTFLoaderExtension = GLTFLoaderExtension;
  108130. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  108131. })(BABYLON || (BABYLON = {}));
  108132. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  108133. var BABYLON;
  108134. (function (BABYLON) {
  108135. var GLTF1;
  108136. (function (GLTF1) {
  108137. var BinaryExtensionBufferName = "binary_glTF";
  108138. ;
  108139. ;
  108140. var GLTFBinaryExtension = /** @class */ (function (_super) {
  108141. __extends(GLTFBinaryExtension, _super);
  108142. function GLTFBinaryExtension() {
  108143. return _super.call(this, "KHR_binary_glTF") || this;
  108144. }
  108145. GLTFBinaryExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  108146. var extensionsUsed = data.json.extensionsUsed;
  108147. if (!extensionsUsed || extensionsUsed.indexOf(this.name) === -1 || !data.bin) {
  108148. return false;
  108149. }
  108150. this._bin = data.bin;
  108151. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  108152. return true;
  108153. };
  108154. GLTFBinaryExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  108155. if (gltfRuntime.extensionsUsed.indexOf(this.name) === -1) {
  108156. return false;
  108157. }
  108158. if (id !== BinaryExtensionBufferName) {
  108159. return false;
  108160. }
  108161. onSuccess(this._bin);
  108162. return true;
  108163. };
  108164. GLTFBinaryExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  108165. var texture = gltfRuntime.textures[id];
  108166. var source = gltfRuntime.images[texture.source];
  108167. if (!source.extensions || !(this.name in source.extensions)) {
  108168. return false;
  108169. }
  108170. var sourceExt = source.extensions[this.name];
  108171. var bufferView = gltfRuntime.bufferViews[sourceExt.bufferView];
  108172. var buffer = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  108173. onSuccess(buffer);
  108174. return true;
  108175. };
  108176. GLTFBinaryExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  108177. var shader = gltfRuntime.shaders[id];
  108178. if (!shader.extensions || !(this.name in shader.extensions)) {
  108179. return false;
  108180. }
  108181. var binaryExtensionShader = shader.extensions[this.name];
  108182. var bufferView = gltfRuntime.bufferViews[binaryExtensionShader.bufferView];
  108183. var shaderBytes = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  108184. setTimeout(function () {
  108185. var shaderString = GLTF1.GLTFUtils.DecodeBufferToText(shaderBytes);
  108186. onSuccess(shaderString);
  108187. });
  108188. return true;
  108189. };
  108190. return GLTFBinaryExtension;
  108191. }(GLTF1.GLTFLoaderExtension));
  108192. GLTF1.GLTFBinaryExtension = GLTFBinaryExtension;
  108193. GLTF1.GLTFLoader.RegisterExtension(new GLTFBinaryExtension());
  108194. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  108195. })(BABYLON || (BABYLON = {}));
  108196. //# sourceMappingURL=babylon.glTFBinaryExtension.js.map
  108197. var BABYLON;
  108198. (function (BABYLON) {
  108199. var GLTF1;
  108200. (function (GLTF1) {
  108201. ;
  108202. ;
  108203. ;
  108204. var GLTFMaterialsCommonExtension = /** @class */ (function (_super) {
  108205. __extends(GLTFMaterialsCommonExtension, _super);
  108206. function GLTFMaterialsCommonExtension() {
  108207. return _super.call(this, "KHR_materials_common") || this;
  108208. }
  108209. GLTFMaterialsCommonExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  108210. if (!gltfRuntime.extensions)
  108211. return false;
  108212. var extension = gltfRuntime.extensions[this.name];
  108213. if (!extension)
  108214. return false;
  108215. // Create lights
  108216. var lights = extension.lights;
  108217. if (lights) {
  108218. for (var thing in lights) {
  108219. var light = lights[thing];
  108220. switch (light.type) {
  108221. case "ambient":
  108222. var ambientLight = new BABYLON.HemisphericLight(light.name, new BABYLON.Vector3(0, 1, 0), gltfRuntime.scene);
  108223. var ambient = light.ambient;
  108224. if (ambient) {
  108225. ambientLight.diffuse = BABYLON.Color3.FromArray(ambient.color || [1, 1, 1]);
  108226. }
  108227. break;
  108228. case "point":
  108229. var pointLight = new BABYLON.PointLight(light.name, new BABYLON.Vector3(10, 10, 10), gltfRuntime.scene);
  108230. var point = light.point;
  108231. if (point) {
  108232. pointLight.diffuse = BABYLON.Color3.FromArray(point.color || [1, 1, 1]);
  108233. }
  108234. break;
  108235. case "directional":
  108236. var dirLight = new BABYLON.DirectionalLight(light.name, new BABYLON.Vector3(0, -1, 0), gltfRuntime.scene);
  108237. var directional = light.directional;
  108238. if (directional) {
  108239. dirLight.diffuse = BABYLON.Color3.FromArray(directional.color || [1, 1, 1]);
  108240. }
  108241. break;
  108242. case "spot":
  108243. var spot = light.spot;
  108244. if (spot) {
  108245. 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);
  108246. spotLight.diffuse = BABYLON.Color3.FromArray(spot.color || [1, 1, 1]);
  108247. }
  108248. break;
  108249. default:
  108250. BABYLON.Tools.Warn("GLTF Material Common extension: light type \"" + light.type + "\” not supported");
  108251. break;
  108252. }
  108253. }
  108254. }
  108255. return false;
  108256. };
  108257. GLTFMaterialsCommonExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  108258. var material = gltfRuntime.materials[id];
  108259. if (!material || !material.extensions)
  108260. return false;
  108261. var extension = material.extensions[this.name];
  108262. if (!extension)
  108263. return false;
  108264. var standardMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  108265. standardMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  108266. if (extension.technique === "CONSTANT") {
  108267. standardMaterial.disableLighting = true;
  108268. }
  108269. standardMaterial.backFaceCulling = extension.doubleSided === undefined ? false : !extension.doubleSided;
  108270. standardMaterial.alpha = extension.values.transparency === undefined ? 1.0 : extension.values.transparency;
  108271. standardMaterial.specularPower = extension.values.shininess === undefined ? 0.0 : extension.values.shininess;
  108272. // Ambient
  108273. if (typeof extension.values.ambient === "string") {
  108274. this._loadTexture(gltfRuntime, extension.values.ambient, standardMaterial, "ambientTexture", onError);
  108275. }
  108276. else {
  108277. standardMaterial.ambientColor = BABYLON.Color3.FromArray(extension.values.ambient || [0, 0, 0]);
  108278. }
  108279. // Diffuse
  108280. if (typeof extension.values.diffuse === "string") {
  108281. this._loadTexture(gltfRuntime, extension.values.diffuse, standardMaterial, "diffuseTexture", onError);
  108282. }
  108283. else {
  108284. standardMaterial.diffuseColor = BABYLON.Color3.FromArray(extension.values.diffuse || [0, 0, 0]);
  108285. }
  108286. // Emission
  108287. if (typeof extension.values.emission === "string") {
  108288. this._loadTexture(gltfRuntime, extension.values.emission, standardMaterial, "emissiveTexture", onError);
  108289. }
  108290. else {
  108291. standardMaterial.emissiveColor = BABYLON.Color3.FromArray(extension.values.emission || [0, 0, 0]);
  108292. }
  108293. // Specular
  108294. if (typeof extension.values.specular === "string") {
  108295. this._loadTexture(gltfRuntime, extension.values.specular, standardMaterial, "specularTexture", onError);
  108296. }
  108297. else {
  108298. standardMaterial.specularColor = BABYLON.Color3.FromArray(extension.values.specular || [0, 0, 0]);
  108299. }
  108300. return true;
  108301. };
  108302. GLTFMaterialsCommonExtension.prototype._loadTexture = function (gltfRuntime, id, material, propertyPath, onError) {
  108303. // Create buffer from texture url
  108304. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {
  108305. // Create texture from buffer
  108306. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, function (texture) { return material[propertyPath] = texture; }, onError);
  108307. }, onError);
  108308. };
  108309. return GLTFMaterialsCommonExtension;
  108310. }(GLTF1.GLTFLoaderExtension));
  108311. GLTF1.GLTFMaterialsCommonExtension = GLTFMaterialsCommonExtension;
  108312. GLTF1.GLTFLoader.RegisterExtension(new GLTFMaterialsCommonExtension());
  108313. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  108314. })(BABYLON || (BABYLON = {}));
  108315. //# sourceMappingURL=babylon.glTFMaterialsCommonExtension.js.map
  108316. var BABYLON;
  108317. (function (BABYLON) {
  108318. var GLTF2;
  108319. (function (GLTF2) {
  108320. var ArrayItem = /** @class */ (function () {
  108321. function ArrayItem() {
  108322. }
  108323. ArrayItem.Assign = function (values) {
  108324. if (values) {
  108325. for (var index = 0; index < values.length; index++) {
  108326. values[index]._index = index;
  108327. }
  108328. }
  108329. };
  108330. return ArrayItem;
  108331. }());
  108332. GLTF2.ArrayItem = ArrayItem;
  108333. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  108334. })(BABYLON || (BABYLON = {}));
  108335. //# sourceMappingURL=babylon.glTFLoaderUtilities.js.map
  108336. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  108337. var BABYLON;
  108338. (function (BABYLON) {
  108339. var GLTF2;
  108340. (function (GLTF2) {
  108341. var GLTFLoader = /** @class */ (function () {
  108342. function GLTFLoader() {
  108343. this._completePromises = new Array();
  108344. this._disposed = false;
  108345. this._state = null;
  108346. this._extensions = {};
  108347. this._defaultSampler = {};
  108348. this._requests = new Array();
  108349. this.coordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode.AUTO;
  108350. this.animationStartMode = BABYLON.GLTFLoaderAnimationStartMode.FIRST;
  108351. this.compileMaterials = false;
  108352. this.useClipPlane = false;
  108353. this.compileShadowGenerators = false;
  108354. this.onDisposeObservable = new BABYLON.Observable();
  108355. this.onMeshLoadedObservable = new BABYLON.Observable();
  108356. this.onTextureLoadedObservable = new BABYLON.Observable();
  108357. this.onMaterialLoadedObservable = new BABYLON.Observable();
  108358. this.onAnimationGroupLoadedObservable = new BABYLON.Observable();
  108359. this.onExtensionLoadedObservable = new BABYLON.Observable();
  108360. this.onCompleteObservable = new BABYLON.Observable();
  108361. }
  108362. GLTFLoader._Register = function (name, factory) {
  108363. if (GLTFLoader._Factories[name]) {
  108364. BABYLON.Tools.Error("Extension with the name '" + name + "' already exists");
  108365. return;
  108366. }
  108367. GLTFLoader._Factories[name] = factory;
  108368. // Keep the order of registration so that extensions registered first are called first.
  108369. GLTFLoader._Names.push(name);
  108370. };
  108371. Object.defineProperty(GLTFLoader.prototype, "state", {
  108372. get: function () {
  108373. return this._state;
  108374. },
  108375. enumerable: true,
  108376. configurable: true
  108377. });
  108378. GLTFLoader.prototype.dispose = function () {
  108379. if (this._disposed) {
  108380. return;
  108381. }
  108382. this._disposed = true;
  108383. this.onDisposeObservable.notifyObservers(this);
  108384. this.onDisposeObservable.clear();
  108385. this._clear();
  108386. };
  108387. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  108388. var _this = this;
  108389. return Promise.resolve().then(function () {
  108390. var nodes = null;
  108391. if (meshesNames) {
  108392. var nodeMap_1 = {};
  108393. if (_this._gltf.nodes) {
  108394. for (var _i = 0, _a = _this._gltf.nodes; _i < _a.length; _i++) {
  108395. var node = _a[_i];
  108396. if (node.name) {
  108397. nodeMap_1[node.name] = node;
  108398. }
  108399. }
  108400. }
  108401. var names = (meshesNames instanceof Array) ? meshesNames : [meshesNames];
  108402. nodes = names.map(function (name) {
  108403. var node = nodeMap_1[name];
  108404. if (!node) {
  108405. throw new Error("Failed to find node '" + name + "'");
  108406. }
  108407. return node;
  108408. });
  108409. }
  108410. return _this._loadAsync(nodes, scene, data, rootUrl, onProgress).then(function () {
  108411. return {
  108412. meshes: _this._getMeshes(),
  108413. particleSystems: [],
  108414. skeletons: _this._getSkeletons(),
  108415. };
  108416. });
  108417. });
  108418. };
  108419. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  108420. return this._loadAsync(null, scene, data, rootUrl, onProgress);
  108421. };
  108422. GLTFLoader.prototype._loadAsync = function (nodes, scene, data, rootUrl, onProgress) {
  108423. var _this = this;
  108424. return Promise.resolve().then(function () {
  108425. _this._loadExtensions();
  108426. _this._babylonScene = scene;
  108427. _this._rootUrl = rootUrl;
  108428. _this._progressCallback = onProgress;
  108429. _this._state = BABYLON.GLTFLoaderState.Loading;
  108430. _this._loadData(data);
  108431. _this._checkExtensions();
  108432. var promises = new Array();
  108433. if (nodes) {
  108434. promises.push(_this._loadNodesAsync(nodes));
  108435. }
  108436. else {
  108437. var scene_1 = GLTFLoader._GetProperty("#/scene", _this._gltf.scenes, _this._gltf.scene || 0);
  108438. promises.push(_this._loadSceneAsync("#/scenes/" + scene_1._index, scene_1));
  108439. }
  108440. if (_this.compileMaterials) {
  108441. promises.push(_this._compileMaterialsAsync());
  108442. }
  108443. if (_this.compileShadowGenerators) {
  108444. promises.push(_this._compileShadowGeneratorsAsync());
  108445. }
  108446. var resultPromise = Promise.all(promises).then(function () {
  108447. _this._state = BABYLON.GLTFLoaderState.Ready;
  108448. _this._startAnimations();
  108449. });
  108450. resultPromise.then(function () {
  108451. _this._rootBabylonMesh.setEnabled(true);
  108452. BABYLON.Tools.SetImmediate(function () {
  108453. if (!_this._disposed) {
  108454. Promise.all(_this._completePromises).then(function () {
  108455. _this._state = BABYLON.GLTFLoaderState.Complete;
  108456. _this.onCompleteObservable.notifyObservers(_this);
  108457. _this.onCompleteObservable.clear();
  108458. _this._clear();
  108459. }).catch(function (error) {
  108460. BABYLON.Tools.Error("glTF Loader: " + error.message);
  108461. _this._clear();
  108462. });
  108463. }
  108464. });
  108465. });
  108466. return resultPromise;
  108467. }).catch(function (error) {
  108468. BABYLON.Tools.Error("glTF Loader: " + error.message);
  108469. _this._clear();
  108470. throw error;
  108471. });
  108472. };
  108473. GLTFLoader.prototype._loadExtensions = function () {
  108474. for (var _i = 0, _a = GLTFLoader._Names; _i < _a.length; _i++) {
  108475. var name_1 = _a[_i];
  108476. var extension = GLTFLoader._Factories[name_1](this);
  108477. this._extensions[name_1] = extension;
  108478. this.onExtensionLoadedObservable.notifyObservers(extension);
  108479. }
  108480. this.onExtensionLoadedObservable.clear();
  108481. };
  108482. GLTFLoader.prototype._loadData = function (data) {
  108483. this._gltf = data.json;
  108484. this._setupData();
  108485. if (data.bin) {
  108486. var buffers = this._gltf.buffers;
  108487. if (buffers && buffers[0] && !buffers[0].uri) {
  108488. var binaryBuffer = buffers[0];
  108489. if (binaryBuffer.byteLength < data.bin.byteLength - 3 || binaryBuffer.byteLength > data.bin.byteLength) {
  108490. BABYLON.Tools.Warn("Binary buffer length (" + binaryBuffer.byteLength + ") from JSON does not match chunk length (" + data.bin.byteLength + ")");
  108491. }
  108492. binaryBuffer._data = Promise.resolve(data.bin);
  108493. }
  108494. else {
  108495. BABYLON.Tools.Warn("Unexpected BIN chunk");
  108496. }
  108497. }
  108498. };
  108499. GLTFLoader.prototype._setupData = function () {
  108500. GLTF2.ArrayItem.Assign(this._gltf.accessors);
  108501. GLTF2.ArrayItem.Assign(this._gltf.animations);
  108502. GLTF2.ArrayItem.Assign(this._gltf.buffers);
  108503. GLTF2.ArrayItem.Assign(this._gltf.bufferViews);
  108504. GLTF2.ArrayItem.Assign(this._gltf.cameras);
  108505. GLTF2.ArrayItem.Assign(this._gltf.images);
  108506. GLTF2.ArrayItem.Assign(this._gltf.materials);
  108507. GLTF2.ArrayItem.Assign(this._gltf.meshes);
  108508. GLTF2.ArrayItem.Assign(this._gltf.nodes);
  108509. GLTF2.ArrayItem.Assign(this._gltf.samplers);
  108510. GLTF2.ArrayItem.Assign(this._gltf.scenes);
  108511. GLTF2.ArrayItem.Assign(this._gltf.skins);
  108512. GLTF2.ArrayItem.Assign(this._gltf.textures);
  108513. if (this._gltf.nodes) {
  108514. var nodeParents = {};
  108515. for (var _i = 0, _a = this._gltf.nodes; _i < _a.length; _i++) {
  108516. var node = _a[_i];
  108517. if (node.children) {
  108518. for (var _b = 0, _c = node.children; _b < _c.length; _b++) {
  108519. var index = _c[_b];
  108520. nodeParents[index] = node._index;
  108521. }
  108522. }
  108523. }
  108524. var rootNode = this._createRootNode();
  108525. for (var _d = 0, _e = this._gltf.nodes; _d < _e.length; _d++) {
  108526. var node = _e[_d];
  108527. var parentIndex = nodeParents[node._index];
  108528. node._parent = parentIndex === undefined ? rootNode : this._gltf.nodes[parentIndex];
  108529. }
  108530. }
  108531. };
  108532. GLTFLoader.prototype._checkExtensions = function () {
  108533. if (this._gltf.extensionsRequired) {
  108534. for (var _i = 0, _a = this._gltf.extensionsRequired; _i < _a.length; _i++) {
  108535. var name_2 = _a[_i];
  108536. var extension = this._extensions[name_2];
  108537. if (!extension || !extension.enabled) {
  108538. throw new Error("Require extension " + name_2 + " is not available");
  108539. }
  108540. }
  108541. }
  108542. };
  108543. GLTFLoader.prototype._createRootNode = function () {
  108544. this._rootBabylonMesh = new BABYLON.Mesh("__root__", this._babylonScene);
  108545. this._rootBabylonMesh.setEnabled(false);
  108546. var rootNode = { _babylonMesh: this._rootBabylonMesh };
  108547. switch (this.coordinateSystemMode) {
  108548. case BABYLON.GLTFLoaderCoordinateSystemMode.AUTO: {
  108549. if (!this._babylonScene.useRightHandedSystem) {
  108550. rootNode.rotation = [0, 1, 0, 0];
  108551. rootNode.scale = [1, 1, -1];
  108552. GLTFLoader._LoadTransform(rootNode, this._rootBabylonMesh);
  108553. }
  108554. break;
  108555. }
  108556. case BABYLON.GLTFLoaderCoordinateSystemMode.FORCE_RIGHT_HANDED: {
  108557. this._babylonScene.useRightHandedSystem = true;
  108558. break;
  108559. }
  108560. default: {
  108561. throw new Error("Invalid coordinate system mode (" + this.coordinateSystemMode + ")");
  108562. }
  108563. }
  108564. this.onMeshLoadedObservable.notifyObservers(this._rootBabylonMesh);
  108565. return rootNode;
  108566. };
  108567. GLTFLoader.prototype._loadNodesAsync = function (nodes) {
  108568. var promises = new Array();
  108569. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  108570. var node = nodes_1[_i];
  108571. promises.push(this._loadNodeAsync("#/nodes/" + node._index, node));
  108572. }
  108573. promises.push(this._loadAnimationsAsync());
  108574. return Promise.all(promises).then(function () { });
  108575. };
  108576. GLTFLoader.prototype._loadSceneAsync = function (context, scene) {
  108577. var promise = GLTF2.GLTFLoaderExtension._LoadSceneAsync(this, context, scene);
  108578. if (promise) {
  108579. return promise;
  108580. }
  108581. var promises = new Array();
  108582. for (var _i = 0, _a = scene.nodes; _i < _a.length; _i++) {
  108583. var index = _a[_i];
  108584. var node = GLTFLoader._GetProperty(context + "/nodes/" + index, this._gltf.nodes, index);
  108585. promises.push(this._loadNodeAsync("#/nodes/" + node._index, node));
  108586. }
  108587. promises.push(this._loadAnimationsAsync());
  108588. return Promise.all(promises).then(function () { });
  108589. };
  108590. GLTFLoader.prototype._forEachNodeMesh = function (node, callback) {
  108591. if (node._babylonMesh) {
  108592. callback(node._babylonMesh);
  108593. }
  108594. if (node._primitiveBabylonMeshes) {
  108595. for (var _i = 0, _a = node._primitiveBabylonMeshes; _i < _a.length; _i++) {
  108596. var babylonMesh = _a[_i];
  108597. callback(babylonMesh);
  108598. }
  108599. }
  108600. };
  108601. GLTFLoader.prototype._getMeshes = function () {
  108602. var meshes = new Array();
  108603. // Root mesh is always first.
  108604. meshes.push(this._rootBabylonMesh);
  108605. var nodes = this._gltf.nodes;
  108606. if (nodes) {
  108607. for (var _i = 0, nodes_2 = nodes; _i < nodes_2.length; _i++) {
  108608. var node = nodes_2[_i];
  108609. this._forEachNodeMesh(node, function (mesh) {
  108610. meshes.push(mesh);
  108611. });
  108612. }
  108613. }
  108614. return meshes;
  108615. };
  108616. GLTFLoader.prototype._getSkeletons = function () {
  108617. var skeletons = new Array();
  108618. var skins = this._gltf.skins;
  108619. if (skins) {
  108620. for (var _i = 0, skins_1 = skins; _i < skins_1.length; _i++) {
  108621. var skin = skins_1[_i];
  108622. if (skin._babylonSkeleton) {
  108623. skeletons.push(skin._babylonSkeleton);
  108624. }
  108625. }
  108626. }
  108627. return skeletons;
  108628. };
  108629. GLTFLoader.prototype._startAnimations = function () {
  108630. var animations = this._gltf.animations;
  108631. if (!animations) {
  108632. return;
  108633. }
  108634. switch (this.animationStartMode) {
  108635. case BABYLON.GLTFLoaderAnimationStartMode.NONE: {
  108636. // do nothing
  108637. break;
  108638. }
  108639. case BABYLON.GLTFLoaderAnimationStartMode.FIRST: {
  108640. var animation = animations[0];
  108641. animation._babylonAnimationGroup.start(true);
  108642. break;
  108643. }
  108644. case BABYLON.GLTFLoaderAnimationStartMode.ALL: {
  108645. for (var _i = 0, animations_1 = animations; _i < animations_1.length; _i++) {
  108646. var animation = animations_1[_i];
  108647. animation._babylonAnimationGroup.start(true);
  108648. }
  108649. break;
  108650. }
  108651. default: {
  108652. BABYLON.Tools.Error("Invalid animation start mode (" + this.animationStartMode + ")");
  108653. return;
  108654. }
  108655. }
  108656. };
  108657. GLTFLoader.prototype._loadNodeAsync = function (context, node) {
  108658. var promise = GLTF2.GLTFLoaderExtension._LoadNodeAsync(this, context, node);
  108659. if (promise) {
  108660. return promise;
  108661. }
  108662. if (node._babylonMesh) {
  108663. throw new Error(context + ": Invalid recursive node hierarchy");
  108664. }
  108665. var promises = new Array();
  108666. var babylonMesh = new BABYLON.Mesh(node.name || "node" + node._index, this._babylonScene, node._parent._babylonMesh);
  108667. node._babylonMesh = babylonMesh;
  108668. node._babylonAnimationTargets = node._babylonAnimationTargets || [];
  108669. node._babylonAnimationTargets.push(babylonMesh);
  108670. GLTFLoader._LoadTransform(node, babylonMesh);
  108671. if (node.mesh != undefined) {
  108672. var mesh = GLTFLoader._GetProperty(context + "/mesh", this._gltf.meshes, node.mesh);
  108673. promises.push(this._loadMeshAsync("#/meshes/" + mesh._index, node, mesh, babylonMesh));
  108674. }
  108675. if (node.children) {
  108676. for (var _i = 0, _a = node.children; _i < _a.length; _i++) {
  108677. var index = _a[_i];
  108678. var childNode = GLTFLoader._GetProperty(context + "/children/" + index, this._gltf.nodes, index);
  108679. promises.push(this._loadNodeAsync("#/nodes/" + index, childNode));
  108680. }
  108681. }
  108682. this.onMeshLoadedObservable.notifyObservers(babylonMesh);
  108683. return Promise.all(promises).then(function () { });
  108684. };
  108685. GLTFLoader.prototype._loadMeshAsync = function (context, node, mesh, babylonMesh) {
  108686. // TODO: instancing
  108687. var _this = this;
  108688. var promises = new Array();
  108689. var primitives = mesh.primitives;
  108690. if (!primitives || primitives.length === 0) {
  108691. throw new Error(context + ": Primitives are missing");
  108692. }
  108693. GLTF2.ArrayItem.Assign(primitives);
  108694. if (primitives.length === 1) {
  108695. var primitive = primitives[0];
  108696. promises.push(this._loadPrimitiveAsync(context + "/primitives/" + primitive._index, node, mesh, primitive, babylonMesh));
  108697. }
  108698. else {
  108699. node._primitiveBabylonMeshes = [];
  108700. for (var _i = 0, primitives_1 = primitives; _i < primitives_1.length; _i++) {
  108701. var primitive = primitives_1[_i];
  108702. var primitiveBabylonMesh = new BABYLON.Mesh((mesh.name || babylonMesh.name) + "_" + primitive._index, this._babylonScene, babylonMesh);
  108703. node._primitiveBabylonMeshes.push(babylonMesh);
  108704. promises.push(this._loadPrimitiveAsync(context + "/primitives/" + primitive._index, node, mesh, primitive, primitiveBabylonMesh));
  108705. this.onMeshLoadedObservable.notifyObservers(babylonMesh);
  108706. }
  108707. }
  108708. if (node.skin != undefined) {
  108709. var skin = GLTFLoader._GetProperty(context + "/skin", this._gltf.skins, node.skin);
  108710. promises.push(this._loadSkinAsync("#/skins/" + skin._index, node, mesh, skin));
  108711. }
  108712. return Promise.all(promises).then(function () {
  108713. _this._forEachNodeMesh(node, function (babylonMesh) {
  108714. babylonMesh._refreshBoundingInfo(true);
  108715. });
  108716. });
  108717. };
  108718. GLTFLoader.prototype._loadPrimitiveAsync = function (context, node, mesh, primitive, babylonMesh) {
  108719. var _this = this;
  108720. var promises = new Array();
  108721. this._createMorphTargets(context, node, mesh, primitive, babylonMesh);
  108722. promises.push(this._loadVertexDataAsync(context, primitive, babylonMesh).then(function (babylonVertexData) {
  108723. new BABYLON.Geometry(babylonMesh.name, _this._babylonScene, babylonVertexData, false, babylonMesh);
  108724. return _this._loadMorphTargetsAsync(context, primitive, babylonMesh, babylonVertexData);
  108725. }));
  108726. if (primitive.material == undefined) {
  108727. babylonMesh.material = this._getDefaultMaterial();
  108728. }
  108729. else {
  108730. var material = GLTFLoader._GetProperty(context + "/material}", this._gltf.materials, primitive.material);
  108731. promises.push(this._loadMaterialAsync("#/materials/" + material._index, material, babylonMesh, function (babylonMaterial) {
  108732. babylonMesh.material = babylonMaterial;
  108733. }));
  108734. }
  108735. return Promise.all(promises).then(function () { });
  108736. };
  108737. GLTFLoader.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) {
  108738. var _this = this;
  108739. var promise = GLTF2.GLTFLoaderExtension._LoadVertexDataAsync(this, context, primitive, babylonMesh);
  108740. if (promise) {
  108741. return promise;
  108742. }
  108743. var attributes = primitive.attributes;
  108744. if (!attributes) {
  108745. throw new Error(context + ": Attributes are missing");
  108746. }
  108747. if (primitive.mode != undefined && primitive.mode !== 4 /* TRIANGLES */) {
  108748. // TODO: handle other primitive modes
  108749. throw new Error(context + ": Mode (" + primitive.mode + ") is not currently supported");
  108750. }
  108751. var promises = new Array();
  108752. var babylonVertexData = new BABYLON.VertexData();
  108753. if (primitive.indices == undefined) {
  108754. var positionAccessorIndex = attributes["POSITION"];
  108755. if (positionAccessorIndex != undefined) {
  108756. var accessor = GLTFLoader._GetProperty(context + "/attributes/POSITION", this._gltf.accessors, positionAccessorIndex);
  108757. babylonVertexData.indices = new Uint32Array(accessor.count);
  108758. for (var i = 0; i < babylonVertexData.indices.length; i++) {
  108759. babylonVertexData.indices[i] = i;
  108760. }
  108761. }
  108762. }
  108763. else {
  108764. var indicesAccessor = GLTFLoader._GetProperty(context + "/indices", this._gltf.accessors, primitive.indices);
  108765. promises.push(this._loadAccessorAsync("#/accessors/" + indicesAccessor._index, indicesAccessor).then(function (data) {
  108766. babylonVertexData.indices = data;
  108767. }));
  108768. }
  108769. var loadAttribute = function (attribute, kind) {
  108770. if (attributes[attribute] == undefined) {
  108771. return;
  108772. }
  108773. babylonMesh._delayInfo = babylonMesh._delayInfo || [];
  108774. if (babylonMesh._delayInfo.indexOf(kind) === -1) {
  108775. babylonMesh._delayInfo.push(kind);
  108776. }
  108777. if (attribute === "COLOR_0") {
  108778. // Assume vertex color has alpha on the mesh. The alphaMode of the material controls whether the material should use alpha or not.
  108779. babylonMesh.hasVertexAlpha = true;
  108780. }
  108781. var accessor = GLTFLoader._GetProperty(context + "/attributes/" + attribute, _this._gltf.accessors, attributes[attribute]);
  108782. promises.push(_this._loadAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  108783. var attributeData = GLTFLoader._ConvertToFloat32Array(context, accessor, data);
  108784. if (attribute === "COLOR_0" && accessor.type === "VEC3") {
  108785. attributeData = GLTFLoader._ConvertVec3ToVec4(context, attributeData);
  108786. }
  108787. babylonVertexData.set(attributeData, kind);
  108788. }));
  108789. };
  108790. loadAttribute("POSITION", BABYLON.VertexBuffer.PositionKind);
  108791. loadAttribute("NORMAL", BABYLON.VertexBuffer.NormalKind);
  108792. loadAttribute("TANGENT", BABYLON.VertexBuffer.TangentKind);
  108793. loadAttribute("TEXCOORD_0", BABYLON.VertexBuffer.UVKind);
  108794. loadAttribute("TEXCOORD_1", BABYLON.VertexBuffer.UV2Kind);
  108795. loadAttribute("JOINTS_0", BABYLON.VertexBuffer.MatricesIndicesKind);
  108796. loadAttribute("WEIGHTS_0", BABYLON.VertexBuffer.MatricesWeightsKind);
  108797. loadAttribute("COLOR_0", BABYLON.VertexBuffer.ColorKind);
  108798. return Promise.all(promises).then(function () {
  108799. return babylonVertexData;
  108800. });
  108801. };
  108802. GLTFLoader.prototype._createMorphTargets = function (context, node, mesh, primitive, babylonMesh) {
  108803. if (!primitive.targets) {
  108804. return;
  108805. }
  108806. if (node._numMorphTargets == undefined) {
  108807. node._numMorphTargets = primitive.targets.length;
  108808. }
  108809. else if (primitive.targets.length !== node._numMorphTargets) {
  108810. throw new Error(context + ": Primitives do not have the same number of targets");
  108811. }
  108812. babylonMesh.morphTargetManager = new BABYLON.MorphTargetManager();
  108813. for (var index = 0; index < primitive.targets.length; index++) {
  108814. var weight = node.weights ? node.weights[index] : mesh.weights ? mesh.weights[index] : 0;
  108815. babylonMesh.morphTargetManager.addTarget(new BABYLON.MorphTarget("morphTarget" + index, weight));
  108816. // TODO: tell the target whether it has positions, normals, tangents
  108817. }
  108818. };
  108819. GLTFLoader.prototype._loadMorphTargetsAsync = function (context, primitive, babylonMesh, babylonVertexData) {
  108820. if (!primitive.targets) {
  108821. return Promise.resolve();
  108822. }
  108823. var promises = new Array();
  108824. var morphTargetManager = babylonMesh.morphTargetManager;
  108825. for (var index = 0; index < morphTargetManager.numTargets; index++) {
  108826. var babylonMorphTarget = morphTargetManager.getTarget(index);
  108827. promises.push(this._loadMorphTargetVertexDataAsync(context + "/targets/" + index, babylonVertexData, primitive.targets[index], babylonMorphTarget));
  108828. }
  108829. return Promise.all(promises).then(function () { });
  108830. };
  108831. GLTFLoader.prototype._loadMorphTargetVertexDataAsync = function (context, babylonVertexData, attributes, babylonMorphTarget) {
  108832. var _this = this;
  108833. var promises = new Array();
  108834. var loadAttribute = function (attribute, setData) {
  108835. if (attributes[attribute] == undefined) {
  108836. return;
  108837. }
  108838. var accessor = GLTFLoader._GetProperty(context + "/" + attribute, _this._gltf.accessors, attributes[attribute]);
  108839. promises.push(_this._loadAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  108840. setData(data);
  108841. }));
  108842. };
  108843. loadAttribute("POSITION", function (data) {
  108844. if (babylonVertexData.positions) {
  108845. for (var i = 0; i < data.length; i++) {
  108846. data[i] += babylonVertexData.positions[i];
  108847. }
  108848. babylonMorphTarget.setPositions(data);
  108849. }
  108850. });
  108851. loadAttribute("NORMAL", function (data) {
  108852. if (babylonVertexData.normals) {
  108853. for (var i = 0; i < data.length; i++) {
  108854. data[i] += babylonVertexData.normals[i];
  108855. }
  108856. babylonMorphTarget.setNormals(data);
  108857. }
  108858. });
  108859. loadAttribute("TANGENT", function (data) {
  108860. if (babylonVertexData.tangents) {
  108861. // Tangent data for morph targets is stored as xyz delta.
  108862. // The vertexData.tangent is stored as xyzw.
  108863. // So we need to skip every fourth vertexData.tangent.
  108864. for (var i = 0, j = 0; i < data.length; i++) {
  108865. data[i] += babylonVertexData.tangents[j++];
  108866. if ((i + 1) % 3 == 0) {
  108867. j++;
  108868. }
  108869. }
  108870. babylonMorphTarget.setTangents(data);
  108871. }
  108872. });
  108873. return Promise.all(promises).then(function () { });
  108874. };
  108875. GLTFLoader._ConvertToFloat32Array = function (context, accessor, data) {
  108876. if (accessor.componentType == 5126 /* FLOAT */) {
  108877. return data;
  108878. }
  108879. var factor = 1;
  108880. if (accessor.normalized) {
  108881. switch (accessor.componentType) {
  108882. case 5121 /* UNSIGNED_BYTE */: {
  108883. factor = 1 / 255;
  108884. break;
  108885. }
  108886. case 5123 /* UNSIGNED_SHORT */: {
  108887. factor = 1 / 65535;
  108888. break;
  108889. }
  108890. default: {
  108891. throw new Error(context + ": Invalid component type (" + accessor.componentType + ")");
  108892. }
  108893. }
  108894. }
  108895. var result = new Float32Array(accessor.count * GLTFLoader._GetNumComponents(context, accessor.type));
  108896. for (var i = 0; i < result.length; i++) {
  108897. result[i] = data[i] * factor;
  108898. }
  108899. return result;
  108900. };
  108901. GLTFLoader._ConvertVec3ToVec4 = function (context, data) {
  108902. var result = new Float32Array(data.length / 3 * 4);
  108903. var offset = 0;
  108904. for (var i = 0; i < result.length; i++) {
  108905. if ((i + 1) % 4 === 0) {
  108906. result[i] = 1;
  108907. }
  108908. else {
  108909. result[i] = data[offset++];
  108910. }
  108911. }
  108912. return result;
  108913. };
  108914. GLTFLoader._LoadTransform = function (node, babylonNode) {
  108915. var position = BABYLON.Vector3.Zero();
  108916. var rotation = BABYLON.Quaternion.Identity();
  108917. var scaling = BABYLON.Vector3.One();
  108918. if (node.matrix) {
  108919. var matrix = BABYLON.Matrix.FromArray(node.matrix);
  108920. matrix.decompose(scaling, rotation, position);
  108921. }
  108922. else {
  108923. if (node.translation)
  108924. position = BABYLON.Vector3.FromArray(node.translation);
  108925. if (node.rotation)
  108926. rotation = BABYLON.Quaternion.FromArray(node.rotation);
  108927. if (node.scale)
  108928. scaling = BABYLON.Vector3.FromArray(node.scale);
  108929. }
  108930. babylonNode.position = position;
  108931. babylonNode.rotationQuaternion = rotation;
  108932. babylonNode.scaling = scaling;
  108933. };
  108934. GLTFLoader.prototype._loadSkinAsync = function (context, node, mesh, skin) {
  108935. var _this = this;
  108936. var assignSkeleton = function () {
  108937. _this._forEachNodeMesh(node, function (babylonMesh) {
  108938. babylonMesh.skeleton = skin._babylonSkeleton;
  108939. });
  108940. node._babylonMesh.parent = _this._rootBabylonMesh;
  108941. node._babylonMesh.position = BABYLON.Vector3.Zero();
  108942. node._babylonMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  108943. node._babylonMesh.scaling = BABYLON.Vector3.One();
  108944. };
  108945. if (skin._loaded) {
  108946. return skin._loaded.then(function () {
  108947. assignSkeleton();
  108948. });
  108949. }
  108950. // TODO: split into two parts so that bones are created before inverseBindMatricesData is loaded (for compiling materials).
  108951. return (skin._loaded = this._loadSkinInverseBindMatricesDataAsync(context, skin).then(function (inverseBindMatricesData) {
  108952. var skeletonId = "skeleton" + skin._index;
  108953. var babylonSkeleton = new BABYLON.Skeleton(skin.name || skeletonId, skeletonId, _this._babylonScene);
  108954. skin._babylonSkeleton = babylonSkeleton;
  108955. _this._loadBones(context, skin, inverseBindMatricesData);
  108956. assignSkeleton();
  108957. }));
  108958. };
  108959. GLTFLoader.prototype._loadSkinInverseBindMatricesDataAsync = function (context, skin) {
  108960. if (skin.inverseBindMatrices == undefined) {
  108961. return Promise.resolve(null);
  108962. }
  108963. var accessor = GLTFLoader._GetProperty(context + "/inverseBindMatrices", this._gltf.accessors, skin.inverseBindMatrices);
  108964. return this._loadAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  108965. return data;
  108966. });
  108967. };
  108968. GLTFLoader.prototype._createBone = function (node, skin, parent, localMatrix, baseMatrix, index) {
  108969. var babylonBone = new BABYLON.Bone(node.name || "joint" + node._index, skin._babylonSkeleton, parent, localMatrix, null, baseMatrix, index);
  108970. node._babylonAnimationTargets = node._babylonAnimationTargets || [];
  108971. node._babylonAnimationTargets.push(babylonBone);
  108972. return babylonBone;
  108973. };
  108974. GLTFLoader.prototype._loadBones = function (context, skin, inverseBindMatricesData) {
  108975. var babylonBones = {};
  108976. for (var _i = 0, _a = skin.joints; _i < _a.length; _i++) {
  108977. var index = _a[_i];
  108978. var node = GLTFLoader._GetProperty(context + "/joints/" + index, this._gltf.nodes, index);
  108979. this._loadBone(node, skin, inverseBindMatricesData, babylonBones);
  108980. }
  108981. };
  108982. GLTFLoader.prototype._loadBone = function (node, skin, inverseBindMatricesData, babylonBones) {
  108983. var babylonBone = babylonBones[node._index];
  108984. if (babylonBone) {
  108985. return babylonBone;
  108986. }
  108987. var boneIndex = skin.joints.indexOf(node._index);
  108988. var baseMatrix = BABYLON.Matrix.Identity();
  108989. if (inverseBindMatricesData && boneIndex !== -1) {
  108990. baseMatrix = BABYLON.Matrix.FromArray(inverseBindMatricesData, boneIndex * 16);
  108991. baseMatrix.invertToRef(baseMatrix);
  108992. }
  108993. var babylonParentBone = null;
  108994. if (node._parent._babylonMesh !== this._rootBabylonMesh) {
  108995. babylonParentBone = this._loadBone(node._parent, skin, inverseBindMatricesData, babylonBones);
  108996. baseMatrix.multiplyToRef(babylonParentBone.getInvertedAbsoluteTransform(), baseMatrix);
  108997. }
  108998. babylonBone = this._createBone(node, skin, babylonParentBone, this._getNodeMatrix(node), baseMatrix, boneIndex);
  108999. babylonBones[node._index] = babylonBone;
  109000. return babylonBone;
  109001. };
  109002. GLTFLoader.prototype._getNodeMatrix = function (node) {
  109003. return node.matrix ?
  109004. BABYLON.Matrix.FromArray(node.matrix) :
  109005. 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());
  109006. };
  109007. GLTFLoader.prototype._loadAnimationsAsync = function () {
  109008. var animations = this._gltf.animations;
  109009. if (!animations) {
  109010. return Promise.resolve();
  109011. }
  109012. var promises = new Array();
  109013. for (var index = 0; index < animations.length; index++) {
  109014. var animation = animations[index];
  109015. promises.push(this._loadAnimationAsync("#/animations/" + index, animation));
  109016. }
  109017. return Promise.all(promises).then(function () { });
  109018. };
  109019. GLTFLoader.prototype._loadAnimationAsync = function (context, animation) {
  109020. var babylonAnimationGroup = new BABYLON.AnimationGroup(animation.name || "animation" + animation._index, this._babylonScene);
  109021. animation._babylonAnimationGroup = babylonAnimationGroup;
  109022. var promises = new Array();
  109023. GLTF2.ArrayItem.Assign(animation.channels);
  109024. GLTF2.ArrayItem.Assign(animation.samplers);
  109025. for (var _i = 0, _a = animation.channels; _i < _a.length; _i++) {
  109026. var channel = _a[_i];
  109027. promises.push(this._loadAnimationChannelAsync(context + "/channels/" + channel._index, context, animation, channel, babylonAnimationGroup));
  109028. }
  109029. this.onAnimationGroupLoadedObservable.notifyObservers(babylonAnimationGroup);
  109030. return Promise.all(promises).then(function () {
  109031. babylonAnimationGroup.normalize();
  109032. });
  109033. };
  109034. GLTFLoader.prototype._loadAnimationChannelAsync = function (context, animationContext, animation, channel, babylonAnimationGroup) {
  109035. var _this = this;
  109036. var targetNode = GLTFLoader._GetProperty(context + "/target/node", this._gltf.nodes, channel.target.node);
  109037. if (!targetNode._babylonMesh || targetNode.skin != undefined) {
  109038. return Promise.resolve();
  109039. }
  109040. var sampler = GLTFLoader._GetProperty(context + "/sampler", animation.samplers, channel.sampler);
  109041. return this._loadAnimationSamplerAsync(animationContext + "/samplers/" + channel.sampler, sampler).then(function (data) {
  109042. var targetPath;
  109043. var animationType;
  109044. switch (channel.target.path) {
  109045. case "translation" /* TRANSLATION */: {
  109046. targetPath = "position";
  109047. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  109048. break;
  109049. }
  109050. case "rotation" /* ROTATION */: {
  109051. targetPath = "rotationQuaternion";
  109052. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  109053. break;
  109054. }
  109055. case "scale" /* SCALE */: {
  109056. targetPath = "scaling";
  109057. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  109058. break;
  109059. }
  109060. case "weights" /* WEIGHTS */: {
  109061. targetPath = "influence";
  109062. animationType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  109063. break;
  109064. }
  109065. default: {
  109066. throw new Error(context + ": Invalid target path (" + channel.target.path + ")");
  109067. }
  109068. }
  109069. var outputBufferOffset = 0;
  109070. var getNextOutputValue;
  109071. switch (targetPath) {
  109072. case "position": {
  109073. getNextOutputValue = function () {
  109074. var value = BABYLON.Vector3.FromArray(data.output, outputBufferOffset);
  109075. outputBufferOffset += 3;
  109076. return value;
  109077. };
  109078. break;
  109079. }
  109080. case "rotationQuaternion": {
  109081. getNextOutputValue = function () {
  109082. var value = BABYLON.Quaternion.FromArray(data.output, outputBufferOffset);
  109083. outputBufferOffset += 4;
  109084. return value;
  109085. };
  109086. break;
  109087. }
  109088. case "scaling": {
  109089. getNextOutputValue = function () {
  109090. var value = BABYLON.Vector3.FromArray(data.output, outputBufferOffset);
  109091. outputBufferOffset += 3;
  109092. return value;
  109093. };
  109094. break;
  109095. }
  109096. case "influence": {
  109097. getNextOutputValue = function () {
  109098. var value = new Array(targetNode._numMorphTargets);
  109099. for (var i = 0; i < targetNode._numMorphTargets; i++) {
  109100. value[i] = data.output[outputBufferOffset++];
  109101. }
  109102. return value;
  109103. };
  109104. break;
  109105. }
  109106. }
  109107. var getNextKey;
  109108. switch (data.interpolation) {
  109109. case "STEP" /* STEP */: {
  109110. getNextKey = function (frameIndex) { return ({
  109111. frame: data.input[frameIndex],
  109112. value: getNextOutputValue(),
  109113. interpolation: BABYLON.AnimationKeyInterpolation.STEP
  109114. }); };
  109115. break;
  109116. }
  109117. case "LINEAR" /* LINEAR */: {
  109118. getNextKey = function (frameIndex) { return ({
  109119. frame: data.input[frameIndex],
  109120. value: getNextOutputValue()
  109121. }); };
  109122. break;
  109123. }
  109124. case "CUBICSPLINE" /* CUBICSPLINE */: {
  109125. getNextKey = function (frameIndex) { return ({
  109126. frame: data.input[frameIndex],
  109127. inTangent: getNextOutputValue(),
  109128. value: getNextOutputValue(),
  109129. outTangent: getNextOutputValue()
  109130. }); };
  109131. break;
  109132. }
  109133. }
  109134. var keys;
  109135. if (data.input.length === 1) {
  109136. var key = getNextKey(0);
  109137. keys = [
  109138. { frame: key.frame, value: key.value },
  109139. { frame: key.frame + 1, value: key.value }
  109140. ];
  109141. }
  109142. else {
  109143. keys = new Array(data.input.length);
  109144. for (var frameIndex = 0; frameIndex < data.input.length; frameIndex++) {
  109145. keys[frameIndex] = getNextKey(frameIndex);
  109146. }
  109147. }
  109148. if (targetPath === "influence") {
  109149. var _loop_1 = function (targetIndex) {
  109150. var animationName = babylonAnimationGroup.name + "_channel" + babylonAnimationGroup.targetedAnimations.length;
  109151. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  109152. babylonAnimation.setKeys(keys.map(function (key) { return ({
  109153. frame: key.frame,
  109154. inTangent: key.inTangent ? key.inTangent[targetIndex] : undefined,
  109155. value: key.value[targetIndex],
  109156. outTangent: key.outTangent ? key.outTangent[targetIndex] : undefined
  109157. }); }));
  109158. _this._forEachNodeMesh(targetNode, function (babylonMesh) {
  109159. var morphTarget = babylonMesh.morphTargetManager.getTarget(targetIndex);
  109160. babylonAnimationGroup.addTargetedAnimation(babylonAnimation, morphTarget);
  109161. });
  109162. };
  109163. for (var targetIndex = 0; targetIndex < targetNode._numMorphTargets; targetIndex++) {
  109164. _loop_1(targetIndex);
  109165. }
  109166. }
  109167. else {
  109168. var animationName = babylonAnimationGroup.name + "_channel" + babylonAnimationGroup.targetedAnimations.length;
  109169. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  109170. babylonAnimation.setKeys(keys);
  109171. if (targetNode._babylonAnimationTargets) {
  109172. for (var _i = 0, _a = targetNode._babylonAnimationTargets; _i < _a.length; _i++) {
  109173. var target = _a[_i];
  109174. babylonAnimationGroup.addTargetedAnimation(babylonAnimation, target);
  109175. }
  109176. }
  109177. }
  109178. });
  109179. };
  109180. GLTFLoader.prototype._loadAnimationSamplerAsync = function (context, sampler) {
  109181. if (sampler._data) {
  109182. return sampler._data;
  109183. }
  109184. var interpolation = sampler.interpolation || "LINEAR" /* LINEAR */;
  109185. switch (interpolation) {
  109186. case "STEP" /* STEP */:
  109187. case "LINEAR" /* LINEAR */:
  109188. case "CUBICSPLINE" /* CUBICSPLINE */: {
  109189. break;
  109190. }
  109191. default: {
  109192. throw new Error(context + ": Invalid interpolation (" + sampler.interpolation + ")");
  109193. }
  109194. }
  109195. var inputData;
  109196. var outputData;
  109197. var inputAccessor = GLTFLoader._GetProperty(context + "/input", this._gltf.accessors, sampler.input);
  109198. var outputAccessor = GLTFLoader._GetProperty(context + "/output", this._gltf.accessors, sampler.output);
  109199. sampler._data = Promise.all([
  109200. this._loadAccessorAsync("#/accessors/" + inputAccessor._index, inputAccessor).then(function (data) {
  109201. inputData = data;
  109202. }),
  109203. this._loadAccessorAsync("#/accessors/" + outputAccessor._index, outputAccessor).then(function (data) {
  109204. outputData = data;
  109205. })
  109206. ]).then(function () {
  109207. return {
  109208. input: inputData,
  109209. interpolation: interpolation,
  109210. output: outputData,
  109211. };
  109212. });
  109213. return sampler._data;
  109214. };
  109215. GLTFLoader.prototype._loadBufferAsync = function (context, buffer) {
  109216. if (buffer._data) {
  109217. return buffer._data;
  109218. }
  109219. if (!buffer.uri) {
  109220. throw new Error(context + ": Uri is missing");
  109221. }
  109222. buffer._data = this._loadUriAsync(context, buffer.uri);
  109223. return buffer._data;
  109224. };
  109225. GLTFLoader.prototype._loadBufferViewAsync = function (context, bufferView) {
  109226. if (bufferView._data) {
  109227. return bufferView._data;
  109228. }
  109229. var buffer = GLTFLoader._GetProperty(context + "/buffer", this._gltf.buffers, bufferView.buffer);
  109230. bufferView._data = this._loadBufferAsync("#/buffers/" + buffer._index, buffer).then(function (bufferData) {
  109231. try {
  109232. return new Uint8Array(bufferData.buffer, bufferData.byteOffset + (bufferView.byteOffset || 0), bufferView.byteLength);
  109233. }
  109234. catch (e) {
  109235. throw new Error(context + ": " + e.message);
  109236. }
  109237. });
  109238. return bufferView._data;
  109239. };
  109240. GLTFLoader.prototype._loadAccessorAsync = function (context, accessor) {
  109241. var _this = this;
  109242. if (accessor.sparse) {
  109243. throw new Error(context + ": Sparse accessors are not currently supported");
  109244. }
  109245. if (accessor._data) {
  109246. return accessor._data;
  109247. }
  109248. var bufferView = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, accessor.bufferView);
  109249. accessor._data = this._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView).then(function (bufferViewData) {
  109250. var numComponents = GLTFLoader._GetNumComponents(context, accessor.type);
  109251. var byteOffset = accessor.byteOffset || 0;
  109252. var byteStride = bufferView.byteStride;
  109253. if (byteStride === 0) {
  109254. BABYLON.Tools.Warn(context + ": Byte stride of 0 is not valid");
  109255. }
  109256. try {
  109257. switch (accessor.componentType) {
  109258. case 5120 /* BYTE */: {
  109259. return _this._buildArrayBuffer(Float32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  109260. }
  109261. case 5121 /* UNSIGNED_BYTE */: {
  109262. return _this._buildArrayBuffer(Uint8Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  109263. }
  109264. case 5122 /* SHORT */: {
  109265. return _this._buildArrayBuffer(Int16Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  109266. }
  109267. case 5123 /* UNSIGNED_SHORT */: {
  109268. return _this._buildArrayBuffer(Uint16Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  109269. }
  109270. case 5125 /* UNSIGNED_INT */: {
  109271. return _this._buildArrayBuffer(Uint32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  109272. }
  109273. case 5126 /* FLOAT */: {
  109274. return _this._buildArrayBuffer(Float32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  109275. }
  109276. default: {
  109277. throw new Error(context + ": Invalid component type (" + accessor.componentType + ")");
  109278. }
  109279. }
  109280. }
  109281. catch (e) {
  109282. throw new Error(context + ": " + e.messsage);
  109283. }
  109284. });
  109285. return accessor._data;
  109286. };
  109287. GLTFLoader.prototype._buildArrayBuffer = function (typedArray, data, byteOffset, count, numComponents, byteStride) {
  109288. byteOffset += data.byteOffset;
  109289. var targetLength = count * numComponents;
  109290. if (!byteStride || byteStride === numComponents * typedArray.BYTES_PER_ELEMENT) {
  109291. return new typedArray(data.buffer, byteOffset, targetLength);
  109292. }
  109293. var elementStride = byteStride / typedArray.BYTES_PER_ELEMENT;
  109294. var sourceBuffer = new typedArray(data.buffer, byteOffset, elementStride * count);
  109295. var targetBuffer = new typedArray(targetLength);
  109296. var sourceIndex = 0;
  109297. var targetIndex = 0;
  109298. while (targetIndex < targetLength) {
  109299. for (var componentIndex = 0; componentIndex < numComponents; componentIndex++) {
  109300. targetBuffer[targetIndex] = sourceBuffer[sourceIndex + componentIndex];
  109301. targetIndex++;
  109302. }
  109303. sourceIndex += elementStride;
  109304. }
  109305. return targetBuffer;
  109306. };
  109307. GLTFLoader.prototype._getDefaultMaterial = function () {
  109308. var id = "__gltf_default";
  109309. var babylonMaterial = this._babylonScene.getMaterialByName(id);
  109310. if (!babylonMaterial) {
  109311. babylonMaterial = new BABYLON.PBRMaterial(id, this._babylonScene);
  109312. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  109313. babylonMaterial.sideOrientation = this._babylonScene.useRightHandedSystem ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation;
  109314. babylonMaterial.metallic = 1;
  109315. babylonMaterial.roughness = 1;
  109316. this.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  109317. }
  109318. return babylonMaterial;
  109319. };
  109320. GLTFLoader.prototype._loadMaterialMetallicRoughnessPropertiesAsync = function (context, material) {
  109321. var promises = new Array();
  109322. var babylonMaterial = material._babylonMaterial;
  109323. // Ensure metallic workflow
  109324. babylonMaterial.metallic = 1;
  109325. babylonMaterial.roughness = 1;
  109326. var properties = material.pbrMetallicRoughness;
  109327. if (properties) {
  109328. if (properties.baseColorFactor) {
  109329. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.baseColorFactor);
  109330. babylonMaterial.alpha = properties.baseColorFactor[3];
  109331. }
  109332. else {
  109333. babylonMaterial.albedoColor = BABYLON.Color3.White();
  109334. }
  109335. babylonMaterial.metallic = properties.metallicFactor == undefined ? 1 : properties.metallicFactor;
  109336. babylonMaterial.roughness = properties.roughnessFactor == undefined ? 1 : properties.roughnessFactor;
  109337. if (properties.baseColorTexture) {
  109338. promises.push(this._loadTextureAsync(context + "/baseColorTexture", properties.baseColorTexture, function (texture) {
  109339. babylonMaterial.albedoTexture = texture;
  109340. }));
  109341. }
  109342. if (properties.metallicRoughnessTexture) {
  109343. promises.push(this._loadTextureAsync(context + "/metallicRoughnessTexture", properties.metallicRoughnessTexture, function (texture) {
  109344. babylonMaterial.metallicTexture = texture;
  109345. }));
  109346. babylonMaterial.useMetallnessFromMetallicTextureBlue = true;
  109347. babylonMaterial.useRoughnessFromMetallicTextureGreen = true;
  109348. babylonMaterial.useRoughnessFromMetallicTextureAlpha = false;
  109349. }
  109350. }
  109351. this._loadMaterialAlphaProperties(context, material);
  109352. return Promise.all(promises).then(function () { });
  109353. };
  109354. GLTFLoader.prototype._loadMaterialAsync = function (context, material, babylonMesh, assign) {
  109355. var promise = GLTF2.GLTFLoaderExtension._LoadMaterialAsync(this, context, material, babylonMesh, assign);
  109356. if (promise) {
  109357. return promise;
  109358. }
  109359. material._babylonMeshes = material._babylonMeshes || [];
  109360. material._babylonMeshes.push(babylonMesh);
  109361. if (!material._loaded) {
  109362. var promises = new Array();
  109363. var babylonMaterial = this._createMaterial(material);
  109364. material._babylonMaterial = babylonMaterial;
  109365. promises.push(this._loadMaterialBasePropertiesAsync(context, material));
  109366. promises.push(this._loadMaterialMetallicRoughnessPropertiesAsync(context, material));
  109367. this.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  109368. material._loaded = Promise.all(promises).then(function () { });
  109369. }
  109370. assign(material._babylonMaterial);
  109371. return material._loaded;
  109372. };
  109373. GLTFLoader.prototype._createMaterial = function (material) {
  109374. var babylonMaterial = new BABYLON.PBRMaterial(material.name || "material" + material._index, this._babylonScene);
  109375. babylonMaterial.sideOrientation = this._babylonScene.useRightHandedSystem ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation;
  109376. return babylonMaterial;
  109377. };
  109378. GLTFLoader.prototype._loadMaterialBasePropertiesAsync = function (context, material) {
  109379. var promises = new Array();
  109380. var babylonMaterial = material._babylonMaterial;
  109381. babylonMaterial.emissiveColor = material.emissiveFactor ? BABYLON.Color3.FromArray(material.emissiveFactor) : new BABYLON.Color3(0, 0, 0);
  109382. if (material.doubleSided) {
  109383. babylonMaterial.backFaceCulling = false;
  109384. babylonMaterial.twoSidedLighting = true;
  109385. }
  109386. if (material.normalTexture) {
  109387. promises.push(this._loadTextureAsync(context + "/normalTexture", material.normalTexture, function (texture) {
  109388. babylonMaterial.bumpTexture = texture;
  109389. }));
  109390. babylonMaterial.invertNormalMapX = !this._babylonScene.useRightHandedSystem;
  109391. babylonMaterial.invertNormalMapY = this._babylonScene.useRightHandedSystem;
  109392. if (material.normalTexture.scale != undefined) {
  109393. babylonMaterial.bumpTexture.level = material.normalTexture.scale;
  109394. }
  109395. }
  109396. if (material.occlusionTexture) {
  109397. promises.push(this._loadTextureAsync(context + "/occlusionTexture", material.occlusionTexture, function (texture) {
  109398. babylonMaterial.ambientTexture = texture;
  109399. }));
  109400. babylonMaterial.useAmbientInGrayScale = true;
  109401. if (material.occlusionTexture.strength != undefined) {
  109402. babylonMaterial.ambientTextureStrength = material.occlusionTexture.strength;
  109403. }
  109404. }
  109405. if (material.emissiveTexture) {
  109406. promises.push(this._loadTextureAsync(context + "/emissiveTexture", material.emissiveTexture, function (texture) {
  109407. babylonMaterial.emissiveTexture = texture;
  109408. }));
  109409. }
  109410. return Promise.all(promises).then(function () { });
  109411. };
  109412. GLTFLoader.prototype._loadMaterialAlphaProperties = function (context, material) {
  109413. var babylonMaterial = material._babylonMaterial;
  109414. var alphaMode = material.alphaMode || "OPAQUE" /* OPAQUE */;
  109415. switch (alphaMode) {
  109416. case "OPAQUE" /* OPAQUE */: {
  109417. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  109418. break;
  109419. }
  109420. case "MASK" /* MASK */: {
  109421. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST;
  109422. babylonMaterial.alphaCutOff = (material.alphaCutoff == undefined ? 0.5 : material.alphaCutoff);
  109423. if (babylonMaterial.alpha) {
  109424. if (babylonMaterial.alpha === 0) {
  109425. babylonMaterial.alphaCutOff = 1;
  109426. }
  109427. else {
  109428. babylonMaterial.alphaCutOff /= babylonMaterial.alpha;
  109429. }
  109430. babylonMaterial.alpha = 1;
  109431. }
  109432. if (babylonMaterial.albedoTexture) {
  109433. babylonMaterial.albedoTexture.hasAlpha = true;
  109434. }
  109435. break;
  109436. }
  109437. case "BLEND" /* BLEND */: {
  109438. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND;
  109439. if (babylonMaterial.albedoTexture) {
  109440. babylonMaterial.albedoTexture.hasAlpha = true;
  109441. babylonMaterial.useAlphaFromAlbedoTexture = true;
  109442. }
  109443. break;
  109444. }
  109445. default: {
  109446. throw new Error(context + ": Invalid alpha mode (" + material.alphaMode + ")");
  109447. }
  109448. }
  109449. };
  109450. GLTFLoader.prototype._loadTextureAsync = function (context, textureInfo, assign) {
  109451. var _this = this;
  109452. var texture = GLTFLoader._GetProperty(context + "/index", this._gltf.textures, textureInfo.index);
  109453. context = "#/textures/" + textureInfo.index;
  109454. var promises = new Array();
  109455. var sampler = (texture.sampler == undefined ? this._defaultSampler : GLTFLoader._GetProperty(context + "/sampler", this._gltf.samplers, texture.sampler));
  109456. var samplerData = this._loadSampler("#/samplers/" + sampler._index, sampler);
  109457. var deferred = new BABYLON.Deferred();
  109458. var babylonTexture = new BABYLON.Texture(null, this._babylonScene, samplerData.noMipMaps, false, samplerData.samplingMode, function () {
  109459. if (!_this._disposed) {
  109460. deferred.resolve();
  109461. }
  109462. }, function (message, exception) {
  109463. if (!_this._disposed) {
  109464. deferred.reject(new Error(context + ": " + ((exception && exception.message) ? exception.message : message || "Failed to load texture")));
  109465. }
  109466. });
  109467. promises.push(deferred.promise);
  109468. babylonTexture.name = texture.name || "texture" + texture._index;
  109469. babylonTexture.wrapU = samplerData.wrapU;
  109470. babylonTexture.wrapV = samplerData.wrapV;
  109471. babylonTexture.coordinatesIndex = textureInfo.texCoord || 0;
  109472. var image = GLTFLoader._GetProperty(context + "/source", this._gltf.images, texture.source);
  109473. promises.push(this._loadImageAsync("#/images/" + image._index, image).then(function (objectURL) {
  109474. babylonTexture.updateURL(objectURL);
  109475. }));
  109476. assign(babylonTexture);
  109477. this.onTextureLoadedObservable.notifyObservers(babylonTexture);
  109478. return Promise.all(promises).then(function () { });
  109479. };
  109480. GLTFLoader.prototype._loadSampler = function (context, sampler) {
  109481. if (!sampler._data) {
  109482. sampler._data = {
  109483. noMipMaps: (sampler.minFilter === 9728 /* NEAREST */ || sampler.minFilter === 9729 /* LINEAR */),
  109484. samplingMode: GLTFLoader._GetTextureSamplingMode(context, sampler.magFilter, sampler.minFilter),
  109485. wrapU: GLTFLoader._GetTextureWrapMode(context, sampler.wrapS),
  109486. wrapV: GLTFLoader._GetTextureWrapMode(context, sampler.wrapT)
  109487. };
  109488. }
  109489. ;
  109490. return sampler._data;
  109491. };
  109492. GLTFLoader.prototype._loadImageAsync = function (context, image) {
  109493. if (image._objectURL) {
  109494. return image._objectURL;
  109495. }
  109496. var promise;
  109497. if (image.uri) {
  109498. promise = this._loadUriAsync(context, image.uri);
  109499. }
  109500. else {
  109501. var bufferView = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, image.bufferView);
  109502. promise = this._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView);
  109503. }
  109504. image._objectURL = promise.then(function (data) {
  109505. return URL.createObjectURL(new Blob([data], { type: image.mimeType }));
  109506. });
  109507. return image._objectURL;
  109508. };
  109509. GLTFLoader.prototype._loadUriAsync = function (context, uri) {
  109510. var _this = this;
  109511. var promise = GLTF2.GLTFLoaderExtension._LoadUriAsync(this, context, uri);
  109512. if (promise) {
  109513. return promise;
  109514. }
  109515. if (!GLTFLoader._ValidateUri(uri)) {
  109516. throw new Error(context + ": Uri '" + uri + "' is invalid");
  109517. }
  109518. if (BABYLON.Tools.IsBase64(uri)) {
  109519. return Promise.resolve(new Uint8Array(BABYLON.Tools.DecodeBase64(uri)));
  109520. }
  109521. return new Promise(function (resolve, reject) {
  109522. var request = BABYLON.Tools.LoadFile(_this._rootUrl + uri, function (data) {
  109523. if (!_this._disposed) {
  109524. resolve(new Uint8Array(data));
  109525. }
  109526. }, function (event) {
  109527. if (!_this._disposed) {
  109528. try {
  109529. if (request && _this._state === BABYLON.GLTFLoaderState.Loading) {
  109530. request._lengthComputable = event.lengthComputable;
  109531. request._loaded = event.loaded;
  109532. request._total = event.total;
  109533. _this._onProgress();
  109534. }
  109535. }
  109536. catch (e) {
  109537. reject(e);
  109538. }
  109539. }
  109540. }, _this._babylonScene.database, true, function (request, exception) {
  109541. if (!_this._disposed) {
  109542. reject(new BABYLON.LoadFileError(context + ": Failed to load '" + uri + "'" + (request ? ": " + request.status + " " + request.statusText : ""), request));
  109543. }
  109544. });
  109545. _this._requests.push(request);
  109546. });
  109547. };
  109548. GLTFLoader.prototype._onProgress = function () {
  109549. if (!this._progressCallback) {
  109550. return;
  109551. }
  109552. var lengthComputable = true;
  109553. var loaded = 0;
  109554. var total = 0;
  109555. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  109556. var request = _a[_i];
  109557. if (request._lengthComputable === undefined || request._loaded === undefined || request._total === undefined) {
  109558. return;
  109559. }
  109560. lengthComputable = lengthComputable && request._lengthComputable;
  109561. loaded += request._loaded;
  109562. total += request._total;
  109563. }
  109564. this._progressCallback(new BABYLON.SceneLoaderProgressEvent(lengthComputable, loaded, lengthComputable ? total : 0));
  109565. };
  109566. GLTFLoader._GetProperty = function (context, array, index) {
  109567. if (!array || index == undefined || !array[index]) {
  109568. throw new Error(context + ": Failed to find index (" + index + ")");
  109569. }
  109570. return array[index];
  109571. };
  109572. GLTFLoader._GetTextureWrapMode = function (context, mode) {
  109573. // Set defaults if undefined
  109574. mode = mode == undefined ? 10497 /* REPEAT */ : mode;
  109575. switch (mode) {
  109576. case 33071 /* CLAMP_TO_EDGE */: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  109577. case 33648 /* MIRRORED_REPEAT */: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  109578. case 10497 /* REPEAT */: return BABYLON.Texture.WRAP_ADDRESSMODE;
  109579. default:
  109580. BABYLON.Tools.Warn(context + ": Invalid texture wrap mode (" + mode + ")");
  109581. return BABYLON.Texture.WRAP_ADDRESSMODE;
  109582. }
  109583. };
  109584. GLTFLoader._GetTextureSamplingMode = function (context, magFilter, minFilter) {
  109585. // Set defaults if undefined
  109586. magFilter = magFilter == undefined ? 9729 /* LINEAR */ : magFilter;
  109587. minFilter = minFilter == undefined ? 9987 /* LINEAR_MIPMAP_LINEAR */ : minFilter;
  109588. if (magFilter === 9729 /* LINEAR */) {
  109589. switch (minFilter) {
  109590. case 9728 /* NEAREST */: return BABYLON.Texture.LINEAR_NEAREST;
  109591. case 9729 /* LINEAR */: return BABYLON.Texture.LINEAR_LINEAR;
  109592. case 9984 /* NEAREST_MIPMAP_NEAREST */: return BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST;
  109593. case 9985 /* LINEAR_MIPMAP_NEAREST */: return BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST;
  109594. case 9986 /* NEAREST_MIPMAP_LINEAR */: return BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR;
  109595. case 9987 /* LINEAR_MIPMAP_LINEAR */: return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  109596. default:
  109597. BABYLON.Tools.Warn(context + ": Invalid texture minification filter (" + minFilter + ")");
  109598. return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  109599. }
  109600. }
  109601. else {
  109602. if (magFilter !== 9728 /* NEAREST */) {
  109603. BABYLON.Tools.Warn(context + ": Invalid texture magnification filter (" + magFilter + ")");
  109604. }
  109605. switch (minFilter) {
  109606. case 9728 /* NEAREST */: return BABYLON.Texture.NEAREST_NEAREST;
  109607. case 9729 /* LINEAR */: return BABYLON.Texture.NEAREST_LINEAR;
  109608. case 9984 /* NEAREST_MIPMAP_NEAREST */: return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  109609. case 9985 /* LINEAR_MIPMAP_NEAREST */: return BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST;
  109610. case 9986 /* NEAREST_MIPMAP_LINEAR */: return BABYLON.Texture.NEAREST_NEAREST_MIPLINEAR;
  109611. case 9987 /* LINEAR_MIPMAP_LINEAR */: return BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR;
  109612. default:
  109613. BABYLON.Tools.Warn(context + ": Invalid texture minification filter (" + minFilter + ")");
  109614. return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  109615. }
  109616. }
  109617. };
  109618. GLTFLoader._GetNumComponents = function (context, type) {
  109619. switch (type) {
  109620. case "SCALAR": return 1;
  109621. case "VEC2": return 2;
  109622. case "VEC3": return 3;
  109623. case "VEC4": return 4;
  109624. case "MAT2": return 4;
  109625. case "MAT3": return 9;
  109626. case "MAT4": return 16;
  109627. }
  109628. throw new Error(context + ": Invalid type (" + type + ")");
  109629. };
  109630. GLTFLoader._ValidateUri = function (uri) {
  109631. return (BABYLON.Tools.IsBase64(uri) || uri.indexOf("..") === -1);
  109632. };
  109633. GLTFLoader.prototype._compileMaterialsAsync = function () {
  109634. var promises = new Array();
  109635. if (this._gltf.materials) {
  109636. for (var _i = 0, _a = this._gltf.materials; _i < _a.length; _i++) {
  109637. var material = _a[_i];
  109638. var babylonMaterial = material._babylonMaterial;
  109639. var babylonMeshes = material._babylonMeshes;
  109640. if (babylonMaterial && babylonMeshes) {
  109641. for (var _b = 0, babylonMeshes_1 = babylonMeshes; _b < babylonMeshes_1.length; _b++) {
  109642. var babylonMesh = babylonMeshes_1[_b];
  109643. // Ensure nonUniformScaling is set if necessary.
  109644. babylonMesh.computeWorldMatrix(true);
  109645. promises.push(babylonMaterial.forceCompilationAsync(babylonMesh));
  109646. if (this.useClipPlane) {
  109647. promises.push(babylonMaterial.forceCompilationAsync(babylonMesh, { clipPlane: true }));
  109648. }
  109649. }
  109650. }
  109651. }
  109652. }
  109653. return Promise.all(promises).then(function () { });
  109654. };
  109655. GLTFLoader.prototype._compileShadowGeneratorsAsync = function () {
  109656. var promises = new Array();
  109657. var lights = this._babylonScene.lights;
  109658. for (var _i = 0, lights_1 = lights; _i < lights_1.length; _i++) {
  109659. var light = lights_1[_i];
  109660. var generator = light.getShadowGenerator();
  109661. if (generator) {
  109662. promises.push(generator.forceCompilationAsync());
  109663. }
  109664. }
  109665. return Promise.all(promises).then(function () { });
  109666. };
  109667. GLTFLoader.prototype._clear = function () {
  109668. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  109669. var request = _a[_i];
  109670. request.abort();
  109671. }
  109672. this._requests.length = 0;
  109673. if (this._gltf && this._gltf.images) {
  109674. for (var _b = 0, _c = this._gltf.images; _b < _c.length; _b++) {
  109675. var image = _c[_b];
  109676. if (image._objectURL) {
  109677. image._objectURL.then(function (value) {
  109678. URL.revokeObjectURL(value);
  109679. });
  109680. image._objectURL = undefined;
  109681. }
  109682. }
  109683. }
  109684. delete this._gltf;
  109685. delete this._babylonScene;
  109686. this._completePromises.length = 0;
  109687. for (var name_3 in this._extensions) {
  109688. this._extensions[name_3].dispose();
  109689. }
  109690. this._extensions = {};
  109691. delete this._rootBabylonMesh;
  109692. delete this._progressCallback;
  109693. this.onMeshLoadedObservable.clear();
  109694. this.onTextureLoadedObservable.clear();
  109695. this.onMaterialLoadedObservable.clear();
  109696. };
  109697. GLTFLoader.prototype._applyExtensions = function (actionAsync) {
  109698. for (var _i = 0, _a = GLTFLoader._Names; _i < _a.length; _i++) {
  109699. var name_4 = _a[_i];
  109700. var extension = this._extensions[name_4];
  109701. if (extension.enabled) {
  109702. var promise = actionAsync(extension);
  109703. if (promise) {
  109704. return promise;
  109705. }
  109706. }
  109707. }
  109708. return null;
  109709. };
  109710. GLTFLoader._Names = new Array();
  109711. GLTFLoader._Factories = {};
  109712. return GLTFLoader;
  109713. }());
  109714. GLTF2.GLTFLoader = GLTFLoader;
  109715. BABYLON.GLTFFileLoader.CreateGLTFLoaderV2 = function () { return new GLTFLoader(); };
  109716. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  109717. })(BABYLON || (BABYLON = {}));
  109718. //# sourceMappingURL=babylon.glTFLoader.js.map
  109719. var BABYLON;
  109720. (function (BABYLON) {
  109721. var GLTF2;
  109722. (function (GLTF2) {
  109723. var GLTFLoaderExtension = /** @class */ (function () {
  109724. function GLTFLoaderExtension(loader) {
  109725. this.enabled = true;
  109726. this._loader = loader;
  109727. }
  109728. GLTFLoaderExtension.prototype.dispose = function () {
  109729. delete this._loader;
  109730. };
  109731. // #region Overridable Methods
  109732. /** Override this method to modify the default behavior for loading scenes. */
  109733. GLTFLoaderExtension.prototype._loadSceneAsync = function (context, node) { return null; };
  109734. /** Override this method to modify the default behavior for loading nodes. */
  109735. GLTFLoaderExtension.prototype._loadNodeAsync = function (context, node) { return null; };
  109736. /** Override this method to modify the default behavior for loading mesh primitive vertex data. */
  109737. GLTFLoaderExtension.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) { return null; };
  109738. /** Override this method to modify the default behavior for loading materials. */
  109739. GLTFLoaderExtension.prototype._loadMaterialAsync = function (context, material, babylonMesh, assign) { return null; };
  109740. /** Override this method to modify the default behavior for loading uris. */
  109741. GLTFLoaderExtension.prototype._loadUriAsync = function (context, uri) { return null; };
  109742. // #endregion
  109743. /** Helper method called by a loader extension to load an glTF extension. */
  109744. GLTFLoaderExtension.prototype._loadExtensionAsync = function (context, property, actionAsync) {
  109745. if (!property.extensions) {
  109746. return null;
  109747. }
  109748. var extensions = property.extensions;
  109749. var extension = extensions[this.name];
  109750. if (!extension) {
  109751. return null;
  109752. }
  109753. // Clear out the extension before executing the action to avoid recursing into the same property.
  109754. delete extensions[this.name];
  109755. try {
  109756. return actionAsync(context + "/extensions/" + this.name, extension);
  109757. }
  109758. finally {
  109759. // Restore the extension after executing the action.
  109760. extensions[this.name] = extension;
  109761. }
  109762. };
  109763. /** Helper method called by the loader to allow extensions to override loading scenes. */
  109764. GLTFLoaderExtension._LoadSceneAsync = function (loader, context, scene) {
  109765. return loader._applyExtensions(function (extension) { return extension._loadSceneAsync(context, scene); });
  109766. };
  109767. /** Helper method called by the loader to allow extensions to override loading nodes. */
  109768. GLTFLoaderExtension._LoadNodeAsync = function (loader, context, node) {
  109769. return loader._applyExtensions(function (extension) { return extension._loadNodeAsync(context, node); });
  109770. };
  109771. /** Helper method called by the loader to allow extensions to override loading mesh primitive vertex data. */
  109772. GLTFLoaderExtension._LoadVertexDataAsync = function (loader, context, primitive, babylonMesh) {
  109773. return loader._applyExtensions(function (extension) { return extension._loadVertexDataAsync(context, primitive, babylonMesh); });
  109774. };
  109775. /** Helper method called by the loader to allow extensions to override loading materials. */
  109776. GLTFLoaderExtension._LoadMaterialAsync = function (loader, context, material, babylonMesh, assign) {
  109777. return loader._applyExtensions(function (extension) { return extension._loadMaterialAsync(context, material, babylonMesh, assign); });
  109778. };
  109779. /** Helper method called by the loader to allow extensions to override loading uris. */
  109780. GLTFLoaderExtension._LoadUriAsync = function (loader, context, uri) {
  109781. return loader._applyExtensions(function (extension) { return extension._loadUriAsync(context, uri); });
  109782. };
  109783. return GLTFLoaderExtension;
  109784. }());
  109785. GLTF2.GLTFLoaderExtension = GLTFLoaderExtension;
  109786. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  109787. })(BABYLON || (BABYLON = {}));
  109788. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  109789. var BABYLON;
  109790. (function (BABYLON) {
  109791. var GLTF2;
  109792. (function (GLTF2) {
  109793. var Extensions;
  109794. (function (Extensions) {
  109795. // https://github.com/sbtron/glTF/tree/MSFT_lod/extensions/Vendor/MSFT_lod
  109796. var NAME = "MSFT_lod";
  109797. var MSFT_lod = /** @class */ (function (_super) {
  109798. __extends(MSFT_lod, _super);
  109799. function MSFT_lod() {
  109800. var _this = _super !== null && _super.apply(this, arguments) || this;
  109801. _this.name = NAME;
  109802. /**
  109803. * Maximum number of LODs to load, starting from the lowest LOD.
  109804. */
  109805. _this.maxLODsToLoad = Number.MAX_VALUE;
  109806. _this._loadingNodeLOD = null;
  109807. _this._loadNodeSignals = {};
  109808. _this._loadingMaterialLOD = null;
  109809. _this._loadMaterialSignals = {};
  109810. return _this;
  109811. }
  109812. MSFT_lod.prototype._loadNodeAsync = function (context, node) {
  109813. var _this = this;
  109814. return this._loadExtensionAsync(context, node, function (context, extension) {
  109815. var firstPromise;
  109816. var nodeLODs = _this._getLODs(context, node, _this._loader._gltf.nodes, extension.ids);
  109817. var _loop_1 = function (indexLOD) {
  109818. var nodeLOD = nodeLODs[indexLOD];
  109819. if (indexLOD !== 0) {
  109820. _this._loadingNodeLOD = nodeLOD;
  109821. if (!_this._loadNodeSignals[nodeLOD._index]) {
  109822. _this._loadNodeSignals[nodeLOD._index] = new BABYLON.Deferred();
  109823. }
  109824. }
  109825. var promise = _this._loader._loadNodeAsync("#/nodes/" + nodeLOD._index, nodeLOD).then(function () {
  109826. if (indexLOD !== 0) {
  109827. var previousNodeLOD = nodeLODs[indexLOD - 1];
  109828. if (previousNodeLOD._babylonMesh) {
  109829. previousNodeLOD._babylonMesh.dispose();
  109830. delete previousNodeLOD._babylonMesh;
  109831. }
  109832. }
  109833. if (indexLOD !== nodeLODs.length - 1) {
  109834. var nodeIndex = nodeLODs[indexLOD + 1]._index;
  109835. if (_this._loadNodeSignals[nodeIndex]) {
  109836. _this._loadNodeSignals[nodeIndex].resolve();
  109837. delete _this._loadNodeSignals[nodeIndex];
  109838. }
  109839. }
  109840. });
  109841. if (indexLOD === 0) {
  109842. firstPromise = promise;
  109843. }
  109844. else {
  109845. _this._loader._completePromises.push(promise);
  109846. _this._loadingNodeLOD = null;
  109847. }
  109848. };
  109849. for (var indexLOD = 0; indexLOD < nodeLODs.length; indexLOD++) {
  109850. _loop_1(indexLOD);
  109851. }
  109852. return firstPromise;
  109853. });
  109854. };
  109855. MSFT_lod.prototype._loadMaterialAsync = function (context, material, babylonMesh, assign) {
  109856. var _this = this;
  109857. // Don't load material LODs if already loading a node LOD.
  109858. if (this._loadingNodeLOD) {
  109859. return null;
  109860. }
  109861. return this._loadExtensionAsync(context, material, function (context, extension) {
  109862. var firstPromise;
  109863. var materialLODs = _this._getLODs(context, material, _this._loader._gltf.materials, extension.ids);
  109864. var _loop_2 = function (indexLOD) {
  109865. var materialLOD = materialLODs[indexLOD];
  109866. if (indexLOD !== 0) {
  109867. _this._loadingMaterialLOD = materialLOD;
  109868. if (!_this._loadMaterialSignals[materialLOD._index]) {
  109869. _this._loadMaterialSignals[materialLOD._index] = new BABYLON.Deferred();
  109870. }
  109871. }
  109872. var promise = _this._loader._loadMaterialAsync("#/materials/" + materialLOD._index, materialLOD, babylonMesh, indexLOD === 0 ? assign : function () { }).then(function () {
  109873. if (indexLOD !== 0) {
  109874. assign(materialLOD._babylonMaterial);
  109875. var previousMaterialLOD = materialLODs[indexLOD - 1];
  109876. if (previousMaterialLOD._babylonMaterial) {
  109877. previousMaterialLOD._babylonMaterial.dispose();
  109878. delete previousMaterialLOD._babylonMaterial;
  109879. }
  109880. }
  109881. if (indexLOD !== materialLODs.length - 1) {
  109882. var materialIndex = materialLODs[indexLOD + 1]._index;
  109883. if (_this._loadMaterialSignals[materialIndex]) {
  109884. _this._loadMaterialSignals[materialIndex].resolve();
  109885. delete _this._loadMaterialSignals[materialIndex];
  109886. }
  109887. }
  109888. });
  109889. if (indexLOD === 0) {
  109890. firstPromise = promise;
  109891. }
  109892. else {
  109893. _this._loader._completePromises.push(promise);
  109894. _this._loadingMaterialLOD = null;
  109895. }
  109896. };
  109897. for (var indexLOD = 0; indexLOD < materialLODs.length; indexLOD++) {
  109898. _loop_2(indexLOD);
  109899. }
  109900. return firstPromise;
  109901. });
  109902. };
  109903. MSFT_lod.prototype._loadUriAsync = function (context, uri) {
  109904. var _this = this;
  109905. // Defer the loading of uris if loading a material or node LOD.
  109906. if (this._loadingMaterialLOD) {
  109907. var index = this._loadingMaterialLOD._index;
  109908. return this._loadMaterialSignals[index].promise.then(function () {
  109909. return _this._loader._loadUriAsync(context, uri);
  109910. });
  109911. }
  109912. else if (this._loadingNodeLOD) {
  109913. var index = this._loadingNodeLOD._index;
  109914. return this._loadNodeSignals[index].promise.then(function () {
  109915. return _this._loader._loadUriAsync(context, uri);
  109916. });
  109917. }
  109918. return null;
  109919. };
  109920. /**
  109921. * Gets an array of LOD properties from lowest to highest.
  109922. */
  109923. MSFT_lod.prototype._getLODs = function (context, property, array, ids) {
  109924. if (this.maxLODsToLoad <= 0) {
  109925. throw new Error("maxLODsToLoad must be greater than zero");
  109926. }
  109927. var properties = new Array();
  109928. for (var i = ids.length - 1; i >= 0; i--) {
  109929. properties.push(GLTF2.GLTFLoader._GetProperty(context + "/ids/" + ids[i], array, ids[i]));
  109930. if (properties.length === this.maxLODsToLoad) {
  109931. return properties;
  109932. }
  109933. }
  109934. properties.push(property);
  109935. return properties;
  109936. };
  109937. return MSFT_lod;
  109938. }(GLTF2.GLTFLoaderExtension));
  109939. Extensions.MSFT_lod = MSFT_lod;
  109940. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new MSFT_lod(loader); });
  109941. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  109942. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  109943. })(BABYLON || (BABYLON = {}));
  109944. //# sourceMappingURL=MSFT_lod.js.map
  109945. var BABYLON;
  109946. (function (BABYLON) {
  109947. var GLTF2;
  109948. (function (GLTF2) {
  109949. var Extensions;
  109950. (function (Extensions) {
  109951. // https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_draco_mesh_compression
  109952. var NAME = "KHR_draco_mesh_compression";
  109953. var KHR_draco_mesh_compression = /** @class */ (function (_super) {
  109954. __extends(KHR_draco_mesh_compression, _super);
  109955. function KHR_draco_mesh_compression(loader) {
  109956. var _this = _super.call(this, loader) || this;
  109957. _this.name = NAME;
  109958. _this._dracoCompression = null;
  109959. // Disable extension if decoder is not available.
  109960. if (!BABYLON.DracoCompression.DecoderUrl) {
  109961. _this.enabled = false;
  109962. }
  109963. return _this;
  109964. }
  109965. KHR_draco_mesh_compression.prototype.dispose = function () {
  109966. if (this._dracoCompression) {
  109967. this._dracoCompression.dispose();
  109968. }
  109969. _super.prototype.dispose.call(this);
  109970. };
  109971. KHR_draco_mesh_compression.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) {
  109972. var _this = this;
  109973. return this._loadExtensionAsync(context, primitive, function (extensionContext, extension) {
  109974. if (primitive.mode != undefined) {
  109975. if (primitive.mode !== 5 /* TRIANGLE_STRIP */ &&
  109976. primitive.mode !== 4 /* TRIANGLES */) {
  109977. throw new Error(context + ": Unsupported mode " + primitive.mode);
  109978. }
  109979. // TODO: handle triangle strips
  109980. if (primitive.mode === 5 /* TRIANGLE_STRIP */) {
  109981. throw new Error(context + ": Mode " + primitive.mode + " is not currently supported");
  109982. }
  109983. }
  109984. var attributes = {};
  109985. var loadAttribute = function (name, kind) {
  109986. var uniqueId = extension.attributes[name];
  109987. if (uniqueId == undefined) {
  109988. return;
  109989. }
  109990. babylonMesh._delayInfo = babylonMesh._delayInfo || [];
  109991. if (babylonMesh._delayInfo.indexOf(kind) === -1) {
  109992. babylonMesh._delayInfo.push(kind);
  109993. }
  109994. attributes[kind] = uniqueId;
  109995. };
  109996. loadAttribute("POSITION", BABYLON.VertexBuffer.PositionKind);
  109997. loadAttribute("NORMAL", BABYLON.VertexBuffer.NormalKind);
  109998. loadAttribute("TANGENT", BABYLON.VertexBuffer.TangentKind);
  109999. loadAttribute("TEXCOORD_0", BABYLON.VertexBuffer.UVKind);
  110000. loadAttribute("TEXCOORD_1", BABYLON.VertexBuffer.UV2Kind);
  110001. loadAttribute("JOINTS_0", BABYLON.VertexBuffer.MatricesIndicesKind);
  110002. loadAttribute("WEIGHTS_0", BABYLON.VertexBuffer.MatricesWeightsKind);
  110003. loadAttribute("COLOR_0", BABYLON.VertexBuffer.ColorKind);
  110004. var bufferView = GLTF2.GLTFLoader._GetProperty(extensionContext, _this._loader._gltf.bufferViews, extension.bufferView);
  110005. return _this._loader._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView).then(function (data) {
  110006. try {
  110007. if (!_this._dracoCompression) {
  110008. _this._dracoCompression = new BABYLON.DracoCompression();
  110009. }
  110010. return _this._dracoCompression.decodeMeshAsync(data, attributes);
  110011. }
  110012. catch (e) {
  110013. throw new Error(context + ": " + e.message);
  110014. }
  110015. });
  110016. });
  110017. };
  110018. return KHR_draco_mesh_compression;
  110019. }(GLTF2.GLTFLoaderExtension));
  110020. Extensions.KHR_draco_mesh_compression = KHR_draco_mesh_compression;
  110021. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_draco_mesh_compression(loader); });
  110022. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  110023. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  110024. })(BABYLON || (BABYLON = {}));
  110025. //# sourceMappingURL=KHR_draco_mesh_compression.js.map
  110026. var BABYLON;
  110027. (function (BABYLON) {
  110028. var GLTF2;
  110029. (function (GLTF2) {
  110030. var Extensions;
  110031. (function (Extensions) {
  110032. // https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_pbrSpecularGlossiness
  110033. var NAME = "KHR_materials_pbrSpecularGlossiness";
  110034. var KHR_materials_pbrSpecularGlossiness = /** @class */ (function (_super) {
  110035. __extends(KHR_materials_pbrSpecularGlossiness, _super);
  110036. function KHR_materials_pbrSpecularGlossiness() {
  110037. var _this = _super !== null && _super.apply(this, arguments) || this;
  110038. _this.name = NAME;
  110039. return _this;
  110040. }
  110041. KHR_materials_pbrSpecularGlossiness.prototype._loadMaterialAsync = function (context, material, babylonMesh, assign) {
  110042. var _this = this;
  110043. return this._loadExtensionAsync(context, material, function (context, extension) {
  110044. material._babylonMeshes = material._babylonMeshes || [];
  110045. material._babylonMeshes.push(babylonMesh);
  110046. if (!material._loaded) {
  110047. var promises = new Array();
  110048. var babylonMaterial = _this._loader._createMaterial(material);
  110049. material._babylonMaterial = babylonMaterial;
  110050. promises.push(_this._loader._loadMaterialBasePropertiesAsync(context, material));
  110051. promises.push(_this._loadSpecularGlossinessPropertiesAsync(context, material, extension));
  110052. _this._loader.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  110053. material._loaded = Promise.all(promises).then(function () { });
  110054. }
  110055. assign(material._babylonMaterial);
  110056. return material._loaded;
  110057. });
  110058. };
  110059. KHR_materials_pbrSpecularGlossiness.prototype._loadSpecularGlossinessPropertiesAsync = function (context, material, properties) {
  110060. var promises = new Array();
  110061. var babylonMaterial = material._babylonMaterial;
  110062. if (properties.diffuseFactor) {
  110063. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.diffuseFactor);
  110064. babylonMaterial.alpha = properties.diffuseFactor[3];
  110065. }
  110066. else {
  110067. babylonMaterial.albedoColor = BABYLON.Color3.White();
  110068. }
  110069. babylonMaterial.reflectivityColor = properties.specularFactor ? BABYLON.Color3.FromArray(properties.specularFactor) : BABYLON.Color3.White();
  110070. babylonMaterial.microSurface = properties.glossinessFactor == undefined ? 1 : properties.glossinessFactor;
  110071. if (properties.diffuseTexture) {
  110072. promises.push(this._loader._loadTextureAsync(context + "/diffuseTexture", properties.diffuseTexture, function (texture) {
  110073. babylonMaterial.albedoTexture = texture;
  110074. }));
  110075. }
  110076. if (properties.specularGlossinessTexture) {
  110077. promises.push(this._loader._loadTextureAsync(context + "/specularGlossinessTexture", properties.specularGlossinessTexture, function (texture) {
  110078. babylonMaterial.reflectivityTexture = texture;
  110079. }));
  110080. babylonMaterial.reflectivityTexture.hasAlpha = true;
  110081. babylonMaterial.useMicroSurfaceFromReflectivityMapAlpha = true;
  110082. }
  110083. this._loader._loadMaterialAlphaProperties(context, material);
  110084. return Promise.all(promises).then(function () { });
  110085. };
  110086. return KHR_materials_pbrSpecularGlossiness;
  110087. }(GLTF2.GLTFLoaderExtension));
  110088. Extensions.KHR_materials_pbrSpecularGlossiness = KHR_materials_pbrSpecularGlossiness;
  110089. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_materials_pbrSpecularGlossiness(loader); });
  110090. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  110091. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  110092. })(BABYLON || (BABYLON = {}));
  110093. //# sourceMappingURL=KHR_materials_pbrSpecularGlossiness.js.map
  110094. var BABYLON;
  110095. (function (BABYLON) {
  110096. var GLTF2;
  110097. (function (GLTF2) {
  110098. var Extensions;
  110099. (function (Extensions) {
  110100. // https://github.com/MiiBond/glTF/tree/khr_lights_v1/extensions/Khronos/KHR_lights
  110101. var NAME = "KHR_lights";
  110102. var LightType;
  110103. (function (LightType) {
  110104. LightType["AMBIENT"] = "ambient";
  110105. LightType["DIRECTIONAL"] = "directional";
  110106. LightType["POINT"] = "point";
  110107. LightType["SPOT"] = "spot";
  110108. })(LightType || (LightType = {}));
  110109. var KHR_lights = /** @class */ (function (_super) {
  110110. __extends(KHR_lights, _super);
  110111. function KHR_lights() {
  110112. var _this = _super !== null && _super.apply(this, arguments) || this;
  110113. _this.name = NAME;
  110114. return _this;
  110115. }
  110116. KHR_lights.prototype._loadSceneAsync = function (context, scene) {
  110117. var _this = this;
  110118. return this._loadExtensionAsync(context, scene, function (context, extension) {
  110119. var promise = _this._loader._loadSceneAsync(context, scene);
  110120. var light = GLTF2.GLTFLoader._GetProperty(context, _this._lights, extension.light);
  110121. if (light.type !== LightType.AMBIENT) {
  110122. throw new Error(context + ": Only ambient lights are allowed on a scene");
  110123. }
  110124. _this._loader._babylonScene.ambientColor = light.color ? BABYLON.Color3.FromArray(light.color) : BABYLON.Color3.Black();
  110125. return promise;
  110126. });
  110127. };
  110128. KHR_lights.prototype._loadNodeAsync = function (context, node) {
  110129. var _this = this;
  110130. return this._loadExtensionAsync(context, node, function (context, extension) {
  110131. var promise = _this._loader._loadNodeAsync(context, node);
  110132. var babylonLight;
  110133. var light = GLTF2.GLTFLoader._GetProperty(context, _this._lights, extension.light);
  110134. var name = node._babylonMesh.name;
  110135. switch (light.type) {
  110136. case LightType.AMBIENT: {
  110137. throw new Error(context + ": Ambient lights are not allowed on a node");
  110138. }
  110139. case LightType.DIRECTIONAL: {
  110140. babylonLight = new BABYLON.DirectionalLight(name, BABYLON.Vector3.Forward(), _this._loader._babylonScene);
  110141. break;
  110142. }
  110143. case LightType.POINT: {
  110144. babylonLight = new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), _this._loader._babylonScene);
  110145. break;
  110146. }
  110147. case LightType.SPOT: {
  110148. var spotLight = light;
  110149. // TODO: support inner and outer cone angles
  110150. //const innerConeAngle = spotLight.innerConeAngle || 0;
  110151. var outerConeAngle = spotLight.outerConeAngle || Math.PI / 4;
  110152. babylonLight = new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward(), outerConeAngle, 2, _this._loader._babylonScene);
  110153. break;
  110154. }
  110155. default: {
  110156. throw new Error(context + ": Invalid light type (" + light.type + ")");
  110157. }
  110158. }
  110159. babylonLight.diffuse = light.color ? BABYLON.Color3.FromArray(light.color) : BABYLON.Color3.White();
  110160. babylonLight.intensity = light.intensity == undefined ? 1 : light.intensity;
  110161. babylonLight.parent = node._babylonMesh;
  110162. return promise;
  110163. });
  110164. };
  110165. Object.defineProperty(KHR_lights.prototype, "_lights", {
  110166. get: function () {
  110167. var extensions = this._loader._gltf.extensions;
  110168. if (!extensions || !extensions[this.name]) {
  110169. throw new Error("#/extensions: '" + this.name + "' not found");
  110170. }
  110171. var extension = extensions[this.name];
  110172. return extension.lights;
  110173. },
  110174. enumerable: true,
  110175. configurable: true
  110176. });
  110177. return KHR_lights;
  110178. }(GLTF2.GLTFLoaderExtension));
  110179. Extensions.KHR_lights = KHR_lights;
  110180. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_lights(loader); });
  110181. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  110182. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  110183. })(BABYLON || (BABYLON = {}));
  110184. //# sourceMappingURL=KHR_lights.js.map
  110185. return BABYLON;
  110186. });
  110187. /***/ }),
  110188. /* 33 */
  110189. /***/ (function(module, exports, __webpack_require__) {
  110190. /*!
  110191. * PEP v0.4.3 | https://github.com/jquery/PEP
  110192. * Copyright jQuery Foundation and other contributors | http://jquery.org/license
  110193. */
  110194. !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);
  110195. // define inherited MouseEvent properties
  110196. // skip bubbles and cancelable since they're set above in initEvent()
  110197. for(var d,e=2;e<m.length;e++)d=m[e],c[d]=b[d]||n[e];c.buttons=b.buttons||0;
  110198. // Spec requires that pointers without pressure specified use 0.5 for down
  110199. // state and 0 for up state.
  110200. var f=0;
  110201. // add x/y properties aliased to clientX/Y
  110202. // define the properties of the PointerEvent interface
  110203. 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(){
  110204. // only activate if this platform does not have pointer events
  110205. 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}})}/**
  110206. * This is the constructor for new PointerEvents.
  110207. *
  110208. * New Pointer Events must be given a type, and an optional dictionary of
  110209. * initialization properties.
  110210. *
  110211. * Due to certain platform requirements, events returned from the constructor
  110212. * identify as MouseEvents.
  110213. *
  110214. * @constructor
  110215. * @param {String} inType The type of the event to create.
  110216. * @param {Object} [inDict] An optional dictionary of initial event properties.
  110217. * @return {Event} A new PointerEvent of type `inType`, initialized with properties from `inDict`.
  110218. */
  110219. 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},
  110220. // return value, key, map
  110221. forEach:function(a,b){return this.array.forEach(function(c,d){a.call(b,c,d,this)},this)}};var q=[
  110222. // MouseEvent
  110223. "bubbles","cancelable","view","detail","screenX","screenY","clientX","clientY","ctrlKey","altKey","shiftKey","metaKey","button","relatedTarget",
  110224. // DOM Level 3
  110225. "buttons",
  110226. // PointerEvent
  110227. "pointerId","width","height","pressure","tiltX","tiltY","pointerType","hwTimestamp","isPrimary",
  110228. // event instance
  110229. "type","target","currentTarget","which","pageX","pageY","timeStamp"],r=[
  110230. // MouseEvent
  110231. !1,!1,null,null,0,0,0,0,!1,!1,!1,!1,0,null,
  110232. // DOM Level 3
  110233. 0,
  110234. // PointerEvent
  110235. 0,0,0,0,0,0,"",0,!1,
  110236. // event instance
  110237. "",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),
  110238. // Scope objects for native events.
  110239. // This exists for ease of testing.
  110240. eventSources:Object.create(null),eventSourceList:[],/**
  110241. * Add a new event source that will generate pointer events.
  110242. *
  110243. * `inSource` must contain an array of event names named `events`, and
  110244. * functions with the names specified in the `events` array.
  110245. * @param {string} name A name for the event source
  110246. * @param {Object} source A new source of platform events.
  110247. */
  110248. 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++)
  110249. // call eventsource register
  110250. b.register.call(b,a)},unregister:function(a){for(var b,c=this.eventSourceList.length,d=0;d<c&&(b=this.eventSourceList[d]);d++)
  110251. // call eventsource register
  110252. b.unregister.call(b,a)},contains:/*scope.external.contains || */function(a,b){try{return a.contains(b)}catch(c){
  110253. // most likely: https://bugzilla.mozilla.org/show_bug.cgi?id=208427
  110254. return!1}},
  110255. // EVENTS
  110256. 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)},
  110257. // LISTENER LOGIC
  110258. eventHandler:function(a){
  110259. // This is used to prevent multiple dispatch of pointerevents from
  110260. // platform events. This can happen when two elements in different scopes
  110261. // are set up to create pointer events, which is relevant to Shadow DOM.
  110262. if(!a._handledByPE){var b=a.type,c=this.eventMap&&this.eventMap[b];c&&c(a),a._handledByPE=!0}},
  110263. // set up event listeners
  110264. listen:function(a,b){b.forEach(function(b){this.addEvent(a,b)},this)},
  110265. // remove event listeners
  110266. 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)},
  110267. // EVENT CREATION AND TRACKING
  110268. /**
  110269. * Creates a new Event of type `inType`, based on the information in
  110270. * `inEvent`.
  110271. *
  110272. * @param {string} inType A string representing the type of event to create
  110273. * @param {Event} inEvent A platform event with a target
  110274. * @return {Event} A PointerEvent of type `inType`
  110275. */
  110276. makeEvent:function(b,c){
  110277. // relatedTarget must be null if pointer is captured
  110278. 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},
  110279. // make and dispatch an event in one call
  110280. fireEvent:function(a,b){var c=this.makeEvent(a,b);return this.dispatchEvent(c)},/**
  110281. * Returns a snapshot of inEvent, with writable properties.
  110282. *
  110283. * @param {Event} inEvent An event that contains properties to copy.
  110284. * @return {Object} An object containing shallow copies of `inEvent`'s
  110285. * properties.
  110286. */
  110287. 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],
  110288. // Work around SVGInstanceElement shadow tree
  110289. // Return the <use> element that is represented by the instance for Safari, Chrome, IE.
  110290. // This is the behavior implemented by Firefox.
  110291. !t||"target"!==b&&"relatedTarget"!==b||c[b]instanceof SVGElementInstance&&(c[b]=c[b].correspondingUseElement);
  110292. // keep the semantics of preventDefault
  110293. 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){
  110294. // Order of conditions due to document.contains() missing in IE.
  110295. for(var d=a.target,e=[];d!==document&&!d.contains(a.relatedTarget);)
  110296. // Touch: Do not propagate if node is detached.
  110297. 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)}},/**
  110298. * Dispatches the event to its target.
  110299. *
  110300. * @param {Event} inEvent The event to be dispatched.
  110301. * @return {Boolean} True if an event handler returns true, false otherwise.
  110302. */
  110303. 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(
  110304. // is element a shadow host?
  110305. e=this.targetingShadow(f);e;){if(
  110306. // find the the element inside the shadow root
  110307. d=e.elementFromPoint(b,c)){
  110308. // shadowed element may contain a shadow root
  110309. var g=this.targetingShadow(d);return this.searchRoot(g,b,c)||d}
  110310. // check for older shadows
  110311. e=this.olderShadow(e)}
  110312. // light dom element is the target
  110313. return f}},owner:function(a){
  110314. // walk up until you hit the shadow root or document
  110315. for(var b=a;b.parentNode;)b=b.parentNode;
  110316. // the owner element is expected to be a Document or ShadowRoot
  110317. 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);
  110318. // if x, y is not in this root, fall back to document search
  110319. 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){
  110320. // Only watch scopes that can target find, as these are top-level.
  110321. // Otherwise we can see duplicate additions and removals that add noise.
  110322. //
  110323. // TODO(dfreedman): For some instances with ShadowDOMPolyfill, we can see
  110324. // a removal without an insertion when a node is redistributed among
  110325. // shadows. Since it all ends up correct in the document, watching only
  110326. // the document will yield the correct mutations to watch.
  110327. 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))},
  110328. // register all touch-action = none nodes on document load
  110329. 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){
  110330. // find children with touch-action
  110331. var b=x(a,this.findElements,this);
  110332. // flatten the list
  110333. // make sure the added nodes are accounted for
  110334. 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){}
  110335. // handler block for native mouse events
  110336. 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:[],
  110337. // collide with the global mouse listener
  110338. 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++){
  110339. // simulated mouse events will be swallowed near a primary touchend
  110340. 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);
  110341. // Update buttons state after possible out-of-document mouseup.
  110342. 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];
  110343. // Produces wrong state of buttons in Browsers without `buttons` support
  110344. // when a mouse button that was pressed outside the document is released
  110345. // inside and other buttons are still pressed down.
  110346. c.buttons=b?b.buttons&~d:0,a.buttons=c.buttons}H.set(this.POINTER_ID,a),
  110347. // Support: Firefox <=44 only
  110348. // FF Ubuntu includes the lifted button in the `buttons` property on
  110349. // mouseup.
  110350. // https://bugzilla.mozilla.org/show_bug.cgi?id=1223366
  110351. 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),
  110352. // set touch-action on shadows as well
  110353. 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),
  110354. // remove touch-action from shadow
  110355. 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);
  110356. // simply update scrollType if listeners are already established
  110357. 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){
  110358. // set primary touch if there no pointers, or the only pointer is the mouse
  110359. (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,
  110360. // forward modifier keys
  110361. c.altKey=b.altKey,c.ctrlKey=b.ctrlKey,c.metaKey=b.metaKey,c.shiftKey=b.shiftKey;
  110362. // forward touch preventDefaults
  110363. 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))},
  110364. // For single axis scrollers, determines whether the element should emit
  110365. // pointer events or behave as a scroller
  110366. shouldScroll:function(a){if(this.firstXY){var b,c=a.currentTarget._scrollType;if("none"===c)
  110367. // this element is a touch-action: none, should never scroll
  110368. b=!1;else if("XY"===c)
  110369. // this element should always scroll
  110370. 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]);
  110371. // if delta in the scroll axis > delta other axis, scroll instead of
  110372. // making events
  110373. 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},
  110374. // In some instances, a touchstart can happen without a touchend. This
  110375. // leaves the pointermap in a broken state.
  110376. // Therefore, on every touchstart, we remove the touches that did not fire a
  110377. // touchend event.
  110378. // To keep state globally consistent, we fire a
  110379. // pointercancel for this "abandoned" touch
  110380. vacuumTouches:function(a){var b=a.touches;
  110381. // pointermap.size should be < tl.length here, as the touchstart has not
  110382. // been processed yet.
  110383. if(R.size>=b.length){var c=[];R.forEach(function(a,d){
  110384. // Never remove pointerId == 1, which is mouse.
  110385. // Touch identifiers are 2 smaller than their pointerId, which is the
  110386. // index in pointermap.
  110387. 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);
  110388. // a finger drifted off the screen, ignore it
  110389. if(c){var d=c.out,e=c.outTarget;u.move(b),d&&e!==b.target&&(d.relatedTarget=b.target,b.relatedTarget=e,
  110390. // recover from retargeting by shadow
  110391. d.target=e,b.target?(u.leaveOut(d),u.enterOver(b)):(
  110392. // clean up case when finger leaves the screen
  110393. 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)},
  110394. // prevent synth mouse events from creating pointer events
  110395. dedupSynthMouse:function(a){var b=N.lastTouches,c=a.changedTouches[0];
  110396. // only the primary finger will synth mouse events
  110397. if(this.isPrimaryTouch(c)){
  110398. // remember x/y of last touch
  110399. 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});
  110400. /***/ }),
  110401. /* 34 */
  110402. /***/ (function(module, exports, __webpack_require__) {
  110403. "use strict";
  110404. Object.defineProperty(exports, "__esModule", { value: true });
  110405. var defaultViewer_1 = __webpack_require__(4);
  110406. var mappers_1 = __webpack_require__(1);
  110407. function InitTags(selector) {
  110408. if (selector === void 0) { selector = 'babylon'; }
  110409. var elements = document.querySelectorAll(selector);
  110410. for (var i = 0; i < elements.length; ++i) {
  110411. var element = elements.item(i);
  110412. var configMapper = mappers_1.mapperManager.getMapper('dom');
  110413. var config = configMapper.map(element);
  110414. var viewer = new defaultViewer_1.DefaultViewer(element, config);
  110415. }
  110416. }
  110417. exports.InitTags = InitTags;
  110418. /***/ })
  110419. /******/ ]);
  110420. return BabylonViewer;
  110421. });